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
|
<file_sep>import morgan from 'morgan'
import passport from 'passport'
import { Strategy as jwtStrategy } from 'passport-jwt'
import { ExtractJwt } from 'passport-jwt'
import server from './config/server'
import {authentication} from './routes'
const PORT = 5000 || process.env.PORT
// const server = Express()
morgan('dev')
server.use(passport.initialize())
server.use('/authentication', authentication)
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}`)
})<file_sep>FROM node:12.13.0-alpine
WORKDIR /app
COPY ./package.json .
COPY ./package-lock.json .
RUN npm install -g nodemon && npm install
COPY . .
EXPOSE 5000
CMD ["npm", "run", "dev"]<file_sep>const express = require('express')
const router = express.Router()
router.get("/", (req, res) =>{
res.json({
test: 'test 2'
})
})
export default router<file_sep>
// module.exports = {
// authentication: require('./authentication')
// }
export { default as authentication } from './authentication'
|
9d578c255c2318bbcfd2282c520f669cfb47de95
|
[
"JavaScript",
"Dockerfile"
] | 4
|
JavaScript
|
tylern88/nodeContainerized
|
3958f76fb241bbbb6eece530307485e3f73bb148
|
739eccea4f351e68e4f75ff9e7abc50d581dee54
|
refs/heads/master
|
<file_sep>#---Libraries---
import requests
import re
from bs4 import BeautifulSoup
from stock_screener_options import *
#---Scraper---
_SCREENER_URL_BASE = "https://finviz.com/screener.ashx?v=111&f=" # you can change the 111 to 121 or other values on the site, code is modular enough that you can feed it any one and it will adjust the data_header and data cols
'''
build_url
@param options create a list of params (fs_exch.AMEX,...)
@param page_num offset the number of records found by some k
Builds URL by providing a list of options from the enums
'''
def build_url(options, page_num=0):
#building the query params
extension = ""
for option in options:
extension += str(option.__class__).split("'")[1] + option.name + "," # bit of a string hack
extension = extension[:-1] #cleans up the string by trimming the final ','
if page_num != 0 and page_num > 0:
extension += "&r=" + str(page_num)
return _SCREENER_URL_BASE + extension
'''
scrape_data_row
@param data_row the row BeautifulSoup object to do parsing on
'''
def scrape_data_row(data_row):
data = []
for col in data_row.find_all("td"):
data.append(col.text)
return data
'''
scrape
@param options the list of options built from enum values
@param page_num offset by 20
'''
def scrape(options, page_num=0):
url = build_url(options, page_num)
req = requests.get(url)
#theoretically check for status code 200
soup = BeautifulSoup(req.content) # theoretically include the best parser for a system
total_found = soup.find("td",{"class":"count-text"}).text
total_found = re.findall(r'\b\d+\b', total_found)[0] # regex to find only digits surrounded by spaces
table = soup.find("table", {"width":"100%","border":"0","bgcolor":"#d3d3d3"})
data_header = [td.text for td in table.find_all("tr", {"align":"center"})[0].find_all("td", {"class":"table-top"})]
data_rows = table.find_all("tr")[1:]
data = []
for data_row in data_rows:
data.append(scrape_data_row(data_row))
return (total_found, data_header, data) #3-tuple contains our data
#---Main---
def main():
print("Stock Screener Tests")
#example use
def example(opt ions,page_num=0):
x = scrape(options,page_num)
print("Total Found: " + x[0])
print(x[1])
for line in x[2]:
print(line)
example([exch._nasd, earningsdate._nextdays5])
example([exch._nasd, earningsdate._nextdays5], 21)
if __name__ == "__main__":
main()<file_sep>import requests
_API_KEY = "<KEY>"
def toJson(historical_data):
return historical_data.json()
'''
historical_data
@param company_ticker e.g. AAPL
@param outputsize full or compact
@param datatype csv or json
'''
def historical_data(company_ticker, outputsize="full", datatype="csv"):
return requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&outputsize=" + outputsize + "&symbol=" + company_ticker + "&apikey=" + _API_KEY + "&datatype=" + datatype)
def main():
print("historical data tests")
raw = toJson(historical_data("AAPL", outputsize='compact', datatype='json'))
print(raw)
raw = toJson(historical_data("TSLA", outputsize='compact', datatype='json'))
print(raw)
if __name__ == '__main__':
main()<file_sep>#Libraries
import requests
import stock_historical_data
import datetime
def simple_moving_average(data_set, date, days): #pass raw["Time Series (Daily)"]
key = '4. close'
print("SMA CLALED!")
date_obj = datetime.date(*map(int, date.split("-"))) #build the date_obj
average = float(data_set[date][key])
days_past = days - 1
while days_past != 0:
date_obj = date_obj - datetime.timedelta(1)
p_date = date_obj.strftime("%Y-%m-%d")
if data_set.get(p_date, "ERROR") == 'ERROR': #not a trading day
pass
else:
print(float(data_set[p_date][key]))
average += float(data_set[p_date][key])
days_past -= 1
average /= days
return average
#Main
def main():
print("Stock Tech Ind Tests")
raw = stock_historical_data.toJson(stock_historical_data.historical_data("AAPL", outputsize='compact', datatype='json'))
raw = raw["Time Series (Daily)"]
print(simple_moving_average(raw, '2018-10-17', 5))
if __name__ == '__main__':
main()<file_sep>from enum import Enum
# naming conventions might seem awkward because this entire file was code generated scraping the webpage
class exch(Enum):
_amex = 'AMEX'
_nasd = 'NASDAQ'
_nyse = 'NYSE'
_modal = 'Custom (Elite only)'
class idx(Enum):
_sp500 = 'S&P 500'
_dji = 'DJIA'
class sec(Enum):
_basicmaterials = 'Basic Materials'
_conglomerates = 'Conglomerates'
_consumergoods = 'Consumer Goods'
_financial = 'Financial'
_healthcare = 'Healthcare'
_industrialgoods = 'Industrial Goods'
_services = 'Services'
_technology = 'Technology'
_utilities = 'Utilities'
_modal = 'Custom (Elite only)'
class ind(Enum):
_stocksonly = 'Stocks only (ex-Funds)'
_exchangetradedfund = 'Exchange Traded Fund'
_accidenthealthinsurance = 'Accident & Health Insurance'
_advertisingagencies = 'Advertising Agencies'
_aerospacedefensemajordiversified = 'Aerospace/Defense - Major Diversified'
_aerospacedefenseproductsservices = 'Aerospace/Defense Products & Services'
_agriculturalchemicals = 'Agricultural Chemicals'
_airdeliveryfreightservices = 'Air Delivery & Freight Services'
_airservicesother = 'Air Services, Other'
_aluminum = 'Aluminum'
_apparelstores = 'Apparel Stores'
_appliances = 'Appliances'
_applicationsoftware = 'Application Software'
_assetmanagement = 'Asset Management'
_autodealerships = 'Auto Dealerships'
_automanufacturersmajor = 'Auto Manufacturers - Major'
_autoparts = 'Auto Parts'
_autopartsstores = 'Auto Parts Stores'
_autopartswholesale = 'Auto Parts Wholesale'
_basicmaterialswholesale = 'Basic Materials Wholesale'
_beveragesbrewers = 'Beverages - Brewers'
_beveragessoftdrinks = 'Beverages - Soft Drinks'
_beverageswineriesdistillers = 'Beverages - Wineries & Distillers'
_biotechnology = 'Biotechnology'
_broadcastingradio = 'Broadcasting - Radio'
_broadcastingtv = 'Broadcasting - TV'
_buildingmaterialswholesale = 'Building Materials Wholesale'
_businessequipment = 'Business Equipment'
_businessservices = 'Business Services'
_businesssoftwareservices = 'Business Software & Services'
_catalogmailorderhouses = 'Catalog & Mail Order Houses'
_catvsystems = 'CATV Systems'
_cement = 'Cement'
_chemicalsmajordiversified = 'Chemicals - Major Diversified'
_cigarettes = 'Cigarettes'
_cleaningproducts = 'Cleaning Products'
_closedendfunddebt = 'Closed-End Fund - Debt'
_closedendfundequity = 'Closed-End Fund - Equity'
_closedendfundforeign = 'Closed-End Fund - Foreign'
_communicationequipment = 'Communication Equipment'
_computerbasedsystems = 'Computer Based Systems'
_computerperipherals = 'Computer Peripherals'
_computerswholesale = 'Computers Wholesale'
_confectioners = 'Confectioners'
_conglomerates = 'Conglomerates'
_consumerservices = 'Consumer Services'
_copper = 'Copper'
_creditservices = 'Credit Services'
_dairyproducts = 'Dairy Products'
_datastoragedevices = 'Data Storage Devices'
_departmentstores = 'Department Stores'
_diagnosticsubstances = 'Diagnostic Substances'
_discountvarietystores = 'Discount, Variety Stores'
_diversifiedcommunicationservices = 'Diversified Communication Services'
_diversifiedcomputersystems = 'Diversified Computer Systems'
_diversifiedelectronics = 'Diversified Electronics'
_diversifiedinvestments = 'Diversified Investments'
_diversifiedmachinery = 'Diversified Machinery'
_diversifiedutilities = 'Diversified Utilities'
_drugdelivery = 'Drug Delivery'
_drugmanufacturersmajor = 'Drug Manufacturers - Major'
_drugmanufacturersother = 'Drug Manufacturers - Other'
_drugrelatedproducts = 'Drug Related Products'
_drugsgeneric = 'Drugs - Generic'
_drugstores = 'Drug Stores'
_drugswholesale = 'Drugs Wholesale'
_educationtrainingservices = 'Education & Training Services'
_electricutilities = 'Electric Utilities'
_electronicequipment = 'Electronic Equipment'
_electronicsstores = 'Electronics Stores'
_electronicswholesale = 'Electronics Wholesale'
_entertainmentdiversified = 'Entertainment - Diversified'
_farmconstructionmachinery = 'Farm & Construction Machinery'
_farmproducts = 'Farm Products'
_foodmajordiversified = 'Food - Major Diversified'
_foodwholesale = 'Food Wholesale'
_foreignmoneycenterbanks = 'Foreign Money Center Banks'
_foreignregionalbanks = 'Foreign Regional Banks'
_foreignutilities = 'Foreign Utilities'
_gamingactivities = 'Gaming Activities'
_gasutilities = 'Gas Utilities'
_generalbuildingmaterials = 'General Building Materials'
_generalcontractors = 'General Contractors'
_generalentertainment = 'General Entertainment'
_gold = 'Gold'
_grocerystores = 'Grocery Stores'
_healthcareinformationservices = 'Healthcare Information Services'
_healthcareplans = 'Health Care Plans'
_heavyconstruction = 'Heavy Construction'
_homefurnishingsfixtures = 'Home Furnishings & Fixtures'
_homefurnishingstores = 'Home Furnishing Stores'
_homehealthcare = 'Home Health Care'
_homeimprovementstores = 'Home Improvement Stores'
_hospitals = 'Hospitals'
_housewaresaccessories = 'Housewares & Accessories'
_independentoilgas = 'Independent Oil & Gas'
_industrialelectricalequipment = 'Industrial Electrical Equipment'
_industrialequipmentcomponents = 'Industrial Equipment & Components'
_industrialequipmentwholesale = 'Industrial Equipment Wholesale'
_industrialmetalsminerals = 'Industrial Metals & Minerals'
_informationdeliveryservices = 'Information & Delivery Services'
_informationtechnologyservices = 'Information Technology Services'
_insurancebrokers = 'Insurance Brokers'
_internetinformationproviders = 'Internet Information Providers'
_internetserviceproviders = 'Internet Service Providers'
_internetsoftwareservices = 'Internet Software & Services'
_investmentbrokeragenational = 'Investment Brokerage - National'
_investmentbrokerageregional = 'Investment Brokerage - Regional'
_jewelrystores = 'Jewelry Stores'
_lifeinsurance = 'Life Insurance'
_lodging = 'Lodging'
_longdistancecarriers = 'Long Distance Carriers'
_longtermcarefacilities = 'Long-Term Care Facilities'
_lumberwoodproduction = 'Lumber, Wood Production'
_machinetoolsaccessories = 'Machine Tools & Accessories'
_majorairlines = 'Major Airlines'
_majorintegratedoilgas = 'Major Integrated Oil & Gas'
_managementservices = 'Management Services'
_manufacturedhousing = 'Manufactured Housing'
_marketingservices = 'Marketing Services'
_meatproducts = 'Meat Products'
_medicalappliancesequipment = 'Medical Appliances & Equipment'
_medicalequipmentwholesale = 'Medical Equipment Wholesale'
_medicalinstrumentssupplies = 'Medical Instruments & Supplies'
_medicallaboratoriesresearch = 'Medical Laboratories & Research'
_medicalpractitioners = 'Medical Practitioners'
_metalfabrication = 'Metal Fabrication'
_moneycenterbanks = 'Money Center Banks'
_mortgageinvestment = 'Mortgage Investment'
_movieproductiontheaters = 'Movie Production, Theaters'
_multimediagraphicssoftware = 'Multimedia & Graphics Software'
_musicvideostores = 'Music & Video Stores'
_networkingcommunicationdevices = 'Networking & Communication Devices'
_nonmetallicmineralmining = 'Nonmetallic Mineral Mining'
_officesupplies = 'Office Supplies'
_oilgasdrillingexploration = 'Oil & Gas Drilling & Exploration'
_oilgasequipmentservices = 'Oil & Gas Equipment & Services'
_oilgaspipelines = 'Oil & Gas Pipelines'
_oilgasrefiningmarketing = 'Oil & Gas Refining & Marketing'
_packagingcontainers = 'Packaging & Containers'
_paperpaperproducts = 'Paper & Paper Products'
_personalcomputers = 'Personal Computers'
_personalproducts = 'Personal Products'
_personalservices = 'Personal Services'
_photographicequipmentsupplies = 'Photographic Equipment & Supplies'
_pollutiontreatmentcontrols = 'Pollution & Treatment Controls'
_printedcircuitboards = 'Printed Circuit Boards'
_processedpackagedgoods = 'Processed & Packaged Goods'
_processingsystemsproducts = 'Processing Systems & Products'
_propertycasualtyinsurance = 'Property & Casualty Insurance'
_propertymanagement = 'Property Management'
_publishingbooks = 'Publishing - Books'
_publishingnewspapers = 'Publishing - Newspapers'
_publishingperiodicals = 'Publishing - Periodicals'
_railroads = 'Railroads'
_realestatedevelopment = 'Real Estate Development'
_recreationalgoodsother = 'Recreational Goods, Other'
_recreationalvehicles = 'Recreational Vehicles'
_regionalairlines = 'Regional Airlines'
_regionalmidatlanticbanks = 'Regional - Mid-Atlantic Banks'
_regionalmidwestbanks = 'Regional - Midwest Banks'
_regionalnortheastbanks = 'Regional - Northeast Banks'
_regionalpacificbanks = 'Regional - Pacific Banks'
_regionalsoutheastbanks = 'Regional - Southeast Banks'
_regionalsouthwestbanks = 'Regional - Southwest Banks'
_reitdiversified = 'REIT - Diversified'
_reithealthcarefacilities = 'REIT - Healthcare Facilities'
_reithotelmotel = 'REIT - Hotel/Motel'
_reitindustrial = 'REIT - Industrial'
_reitoffice = 'REIT - Office'
_reitresidential = 'REIT - Residential'
_reitretail = 'REIT - Retail'
_rentalleasingservices = 'Rental & Leasing Services'
_researchservices = 'Research Services'
_residentialconstruction = 'Residential Construction'
_resortscasinos = 'Resorts & Casinos'
_restaurants = 'Restaurants'
_rubberplastics = 'Rubber & Plastics'
_savingsloans = 'Savings & Loans'
_scientifictechnicalinstruments = 'Scientific & Technical Instruments'
_securityprotectionservices = 'Security & Protection Services'
_securitysoftwareservices = 'Security Software & Services'
_semiconductorbroadline = 'Semiconductor - Broad Line'
_semiconductorequipmentmaterials = 'Semiconductor Equipment & Materials'
_semiconductorintegratedcircuits = 'Semiconductor - Integrated Circuits'
_semiconductormemorychips = 'Semiconductor- Memory Chips'
_semiconductorspecialized = 'Semiconductor - Specialized'
_shipping = 'Shipping'
_silver = 'Silver'
_smalltoolsaccessories = 'Small Tools & Accessories'
_specializedhealthservices = 'Specialized Health Services'
_specialtychemicals = 'Specialty Chemicals'
_specialtyeateries = 'Specialty Eateries'
_specialtyretailother = 'Specialty Retail, Other'
_sportingactivities = 'Sporting Activities'
_sportinggoods = 'Sporting Goods'
_sportinggoodsstores = 'Sporting Goods Stores'
_staffingoutsourcingservices = 'Staffing & Outsourcing Services'
_steeliron = 'Steel & Iron'
_suretytitleinsurance = 'Surety & Title Insurance'
_synthetics = 'Synthetics'
_technicalservices = 'Technical Services'
_technicalsystemsoftware = 'Technical & System Software'
_telecomservicesdomestic = 'Telecom Services - Domestic'
_telecomservicesforeign = 'Telecom Services - Foreign'
_textileapparelclothing = 'Textile - Apparel Clothing'
_textileapparelfootwearaccessories = 'Textile - Apparel Footwear & Accessories'
_textileindustrial = 'Textile Industrial'
_tobaccoproductsother = 'Tobacco Products, Other'
_toyhobbystores = 'Toy & Hobby Stores'
_toysgames = 'Toys & Games'
_trucking = 'Trucking'
_trucksothervehicles = 'Trucks & Other Vehicles'
_wastemanagement = 'Waste Management'
_waterutilities = 'Water Utilities'
_wholesaleother = 'Wholesale, Other'
_wirelesscommunications = 'Wireless Communications'
_modal = 'Custom (Elite only)'
class geo(Enum):
_usa = 'USA'
_notusa = 'Foreign (ex-USA)'
_asia = 'Asia'
_europe = 'Europe'
_latinamerica = 'Latin America'
_bric = 'BRIC'
_argentina = 'Argentina'
_australia = 'Australia'
_bahamas = 'Bahamas'
_belgium = 'Belgium'
_benelux = 'BeNeLux'
_bermuda = 'Bermuda'
_brazil = 'Brazil'
_britishvirginislands = 'British Virgin Islands'
_canada = 'Canada'
_caymanislands = 'Cayman Islands'
_channelislands = 'Channel Islands'
_chile = 'Chile'
_china = 'China'
_chinahongkong = 'China & Hong Kong'
_colombia = 'Colombia'
_cyprus = 'Cyprus'
_denmark = 'Denmark'
_finland = 'Finland'
_france = 'France'
_germany = 'Germany'
_greece = 'Greece'
_hongkong = 'Hong Kong'
_hungary = 'Hungary'
_iceland = 'Iceland'
_india = 'India'
_indonesia = 'Indonesia'
_ireland = 'Ireland'
_israel = 'Israel'
_italy = 'Italy'
_japan = 'Japan'
_kazakhstan = 'Kazakhstan'
_luxembourg = 'Luxembourg'
_malaysia = 'Malaysia'
_marshallislands = 'Marshall Islands'
_mexico = 'Mexico'
_monaco = 'Monaco'
_netherlands = 'Netherlands'
_netherlandsantilles = 'Netherlands Antilles'
_newzealand = 'New Zealand'
_norway = 'Norway'
_panama = 'Panama'
_papuanewguinea = 'Papua New Guinea'
_peru = 'Peru'
_philippines = 'Philippines'
_portugal = 'Portugal'
_russia = 'Russia'
_singapore = 'Singapore'
_southafrica = 'South Africa'
_southkorea = 'South Korea'
_spain = 'Spain'
_sweden = 'Sweden'
_switzerland = 'Switzerland'
_taiwan = 'Taiwan'
_turkey = 'Turkey'
_unitedarabemirates = 'United Arab Emirates'
_unitedkingdom = 'United Kingdom'
_modal = 'Custom (Elite only)'
class cap(Enum):
_mega = 'Mega ($200bln and more)'
_large = 'Large ($10bln to $200bln)'
_mid = 'Mid ($2bln to $10bln)'
_small = 'Small ($300mln to $2bln)'
_micro = 'Micro ($50mln to $300mln)'
_nano = 'Nano (under $50mln)'
_largeover = '+Large (over $10bln)'
_midover = '+Mid (over $2bln)'
_smallover = '+Small (over $300mln)'
_microover = '+Micro (over $50mln)'
_largeunder = '-Large (under $200bln)'
_midunder = '-Mid (under $10bln)'
_smallunder = '-Small (under $2bln)'
_microunder = '-Micro (under $300mln)'
_frange = 'Custom (Elite only)'
class fa_div(Enum):
_none = 'None (0%)'
_pos = 'Positive (>0%)'
_high = 'High (>5%)'
_veryhigh = 'Very High (>10%)'
_o1 = 'Over 1%'
_o2 = 'Over 2%'
_o3 = 'Over 3%'
_o4 = 'Over 4%'
_o5 = 'Over 5%'
_o6 = 'Over 6%'
_o7 = 'Over 7%'
_o8 = 'Over 8%'
_o9 = 'Over 9%'
_o10 = 'Over 10%'
_range = 'Custom (Elite only)'
class sh_short(Enum):
_low = 'Low (<5%)'
_high = 'High (>20%)'
_u5 = 'Under 5%'
_u10 = 'Under 10%'
_u15 = 'Under 15%'
_u20 = 'Under 20%'
_u25 = 'Under 25%'
_u30 = 'Under 30%'
_o5 = 'Over 5%'
_o10 = 'Over 10%'
_o15 = 'Over 15%'
_o20 = 'Over 20%'
_o25 = 'Over 25%'
_o30 = 'Over 30%'
_range = 'Custom (Elite only)'
class an_recom(Enum):
_strongbuy = 'Strong Buy (1)'
_buybetter = 'Buy or better'
_buy = 'Buy'
_holdbetter = 'Hold or better'
_hold = 'Hold'
_holdworse = 'Hold or worse'
_sell = 'Sell'
_sellworse = 'Sell or worse'
_strongsell = 'Strong Sell (5)'
_modal = 'Custom (Elite only)'
class sh_opt(Enum):
_option = 'Optionable'
_short = 'Shortable'
_optionshort = 'Optionable and shortable'
class earningsdate(Enum):
_today = 'Today'
_todaybefore = 'Today Before Market Open'
_todayafter = 'Today After Market Close'
_tomorrow = 'Tomorrow'
_tomorrowbefore = 'Tomorrow Before Market Open'
_tomorrowafter = 'Tomorrow After Market Close'
_yesterday = 'Yesterday'
_yesterdaybefore = 'Yesterday Before Market Open'
_yesterdayafter = 'Yesterday After Market Close'
_nextdays5 = 'Next 5 Days'
_prevdays5 = 'Previous 5 Days'
_thisweek = 'This Week'
_nextweek = 'Next Week'
_prevweek = 'Previous Week'
_thismonth = 'This Month'
_modal = 'Custom (Elite only)'
class sh_avgvol(Enum):
_u50 = 'Under 50K'
_u100 = 'Under 100K'
_u500 = 'Under 500K'
_u750 = 'Under 750K'
_u1000 = 'Under 1M'
_o50 = 'Over 50K'
_o100 = 'Over 100K'
_o200 = 'Over 200K'
_o300 = 'Over 300K'
_o400 = 'Over 400K'
_o500 = 'Over 500K'
_o750 = 'Over 750K'
_o1000 = 'Over 1M'
_o2000 = 'Over 2M'
_100to500 = '100K to 500K'
_100to1000 = '100K to 1M'
_500to1000 = '500K to 1M'
_500to10000 = '500K to 10M'
_range = 'Custom (Elite only)'
class sh_relvol(Enum):
_o10 = 'Over 10'
_o5 = 'Over 5'
_o3 = 'Over 3'
_o2 = 'Over 2'
_o15 = 'Over 1.5'
_o1 = 'Over 1'
_o075 = 'Over 0.75'
_o05 = 'Over 0.5'
_o025 = 'Over 0.25'
_u2 = 'Under 2'
_u15 = 'Under 1.5'
_u1 = 'Under 1'
_u075 = 'Under 0.75'
_u05 = 'Under 0.5'
_u025 = 'Under 0.25'
_u01 = 'Under 0.1'
_frange = 'Custom (Elite only)'
class sh_curvol(Enum):
_u50 = 'Under 50K'
_u100 = 'Under 100K'
_u500 = 'Under 500K'
_u750 = 'Under 750K'
_u1000 = 'Under 1M'
_o0 = 'Over 0'
_o50 = 'Over 50K'
_o100 = 'Over 100K'
_o200 = 'Over 200K'
_o300 = 'Over 300K'
_o400 = 'Over 400K'
_o500 = 'Over 500K'
_o750 = 'Over 750K'
_o1000 = 'Over 1M'
_o2000 = 'Over 2M'
_o5000 = 'Over 5M'
_o10000 = 'Over 10M'
_o20000 = 'Over 20M'
_range = 'Custom (Elite only)'
class sh_price(Enum):
_u1 = 'Under $1'
_u2 = 'Under $2'
_u3 = 'Under $3'
_u4 = 'Under $4'
_u5 = 'Under $5'
_u7 = 'Under $7'
_u10 = 'Under $10'
_u15 = 'Under $15'
_u20 = 'Under $20'
_u30 = 'Under $30'
_u40 = 'Under $40'
_u50 = 'Under $50'
_o1 = 'Over $1'
_o2 = 'Over $2'
_o3 = 'Over $3'
_o4 = 'Over $4'
_o5 = 'Over $5'
_o7 = 'Over $7'
_o10 = 'Over $10'
_o15 = 'Over $15'
_o20 = 'Over $20'
_o30 = 'Over $30'
_o40 = 'Over $40'
_o50 = 'Over $50'
_o60 = 'Over $60'
_o70 = 'Over $70'
_o80 = 'Over $80'
_o90 = 'Over $90'
_o100 = 'Over $100'
_1to5 = '$1 to $5'
_1to10 = '$1 to $10'
_1to20 = '$1 to $20'
_5to10 = '$5 to $10'
_5to20 = '$5 to $20'
_5to50 = '$5 to $50'
_10to20 = '$10 to $20'
_10to50 = '$10 to $50'
_20to50 = '$20 to $50'
_50to100 = '$50 to $100'
_range = 'Custom (Elite only)'
class targetprice(Enum):
_a50 = '50% Above Price'
_a40 = '40% Above Price'
_a30 = '30% Above Price'
_a20 = '20% Above Price'
_a10 = '10% Above Price'
_a5 = '5% Above Price'
_above = 'Above Price'
_below = 'Below Price'
_b5 = '5% Below Price'
_b10 = '10% Below Price'
_b20 = '20% Below Price'
_b30 = '30% Below Price'
_b40 = '40% Below Price'
_b50 = '50% Below Price'
class ipodate(Enum):
_today = 'Today'
_yesterday = 'Yesterday'
_prevweek = 'In the last week'
_prevmonth = 'In the last month'
_prevquarter = 'In the last quarter'
_prevyear = 'In the last year'
_more1 = 'More than a year ago'
_more5 = 'More than 5 years ago'
_more10 = 'More than 10 years ago'
_more15 = 'More than 15 years ago'
_more20 = 'More than 20 years ago'
_more25 = 'More than 25 years ago'
|
0eead0e6b505fed65b5e763a0074528a65cc9227
|
[
"Python"
] | 4
|
Python
|
cheenar/Stocks
|
718f101743f38b65e5e89e260c38e9ac2a0d5fb6
|
795dea7c696c75bc92aad62ef17f6b79b31ebfeb
|
refs/heads/master
|
<repo_name>babarindeos/Coops<file_sep>/MainApp/MainApp/Classes/PhotoPath.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace MainApp
{
public static class PhotoPath
{
private static string path;
public static string getPath()
{
path = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
return path;
}
}
}
<file_sep>/MainApp/MainApp/Deductions/UnpostDeductions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class UnpostDeductions : Form
{
private string UserId;
List<string> selDeductionIdDel;
List<string> selDeductionTransactionDel;
int selDeductionId;
string selDedTransactionId;
string selDelMonth;
int selDelYear;
public UnpostDeductions(string userId)
{
InitializeComponent();
this.UserId = userId;
}
private void UnpostDeductions_Load(object sender, EventArgs e)
{
selDeductionTransactionDel = new List<string>();
loadBulk();
loadSingle();
}
private void loadBulk()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionDateID, m.Month, d.Year, d.DatePosted 'Date Posted' from DeductionDates d " +
"left join MonthByName m on d.Month=m.MonthID " +
"order by d.DeductionDateID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "DeductionDates");
DataTable dt = ds.Tables["DeductionDates"];
dtGrdBulkDeductions.DataSource = dt;
dtGrdBulkDeductions.Columns["DeductionDateID"].Visible = false;
dtGrdBulkDeductions.Columns["Date Posted"].DefaultCellStyle.Format = "F";
dtGrdBulkDeductions.Columns["Date Posted"].Width = 250;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadSingle()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionID 'ID', mn.Month, d.Year,m.MemberID, m.FileNo, m.LastName, m.FirstName, m.MiddleName, d.TransactionID, d.DatePosted 'Date Posted' from Deductions d " +
"left join MonthByName mn on d.Month=mn.MonthID " +
"left join Members m on m.MemberID = d.MemberID " +
"order by d.DeductionID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Deductions");
DataTable dt = ds.Tables["Deductions"];
dtGrdSingleDeductions.DataSource = dt;
dtGrdSingleDeductions.Columns["MemberID"].Visible = false;
dtGrdSingleDeductions.Columns["ID"].Width = 60;
dtGrdSingleDeductions.Columns["Month"].Width = 70;
dtGrdSingleDeductions.Columns["Year"].Width = 40;
dtGrdSingleDeductions.Columns["FileNo"].Width = 60;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void dtGrdBulkDeductions_SelectionChanged(object sender, EventArgs e)
{
}
private void dtGrdBulkDeductions_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dtGrdBulkDeductions.SelectedRows.Count > 0)
{
DateTime postedDate = Convert.ToDateTime(dtGrdBulkDeductions.SelectedRows[0].Cells[3].Value.ToString());
DateTime today = DateTime.Now;
int daysDiff = Convert.ToInt16((today - postedDate).TotalDays);
if (daysDiff > 10)
{
lblBulkStatus.Text = "Status: Posted " + daysDiff + " days ago";
btnBulkUnpost.Enabled = false;
}
else
{
lblBulkStatus.Text = "Status: Posted " + daysDiff + " days ago";
btnBulkUnpost.Enabled = true;
}
}
}
private void btnBulkUnpost_Click(object sender, EventArgs e)
{
if (dtGrdBulkDeductions.SelectedRows.Count>0)
{
selDeductionId = Convert.ToInt16(dtGrdBulkDeductions.SelectedRows[0].Cells[0].Value.ToString());
selDelMonth = dtGrdBulkDeductions.SelectedRows[0].Cells[1].Value.ToString();
selDelYear = Convert.ToInt16(dtGrdBulkDeductions.SelectedRows[0].Cells[2].Value.ToString());
//MessageBox.Show("ID: " + selDeductionId.ToString() + "Month: " + selDelMonth.ToString() + " Year: " + selDelYear.ToString());
}
else
{
MessageBox.Show("Choose a Deduction Record to Delete","Unpost Deduction",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
DialogResult res = MessageBox.Show("Do you wish to Unpost the Selected Deduction?", "Unpost Deduction", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
SqlConnection conn = ConnectDB.GetConnection();
SqlCommand cmd;
try
{
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Transaction = sqlTrans;
cmd.CommandText = "Select distinct d.TransactionID from Deductions d " +
"inner join MonthByName m on m.MonthID=d.Month " +
"where m.month='" + selDelMonth + "' And d.Year=" + selDelYear;
SqlDataReader reader = cmd.ExecuteReader();
selDeductionTransactionDel.Clear();
while (reader.Read())
{
selDeductionTransactionDel.Add(reader["TransactionID"].ToString());
}
reader.Close();
//MessageBox.Show(selDeductionTransactionDel.Count.ToString());
Cl_UnpostDeductions deletePosting = new Cl_UnpostDeductions();
string savingsDelStatus = deletePosting.unpostSavingsDeductions(conn, cmd, selDeductionTransactionDel);
string loanDelStatus = deletePosting.unpostLoansDeduction(conn, cmd, selDeductionTransactionDel);
string deductionDelStatus = deletePosting.unpostDeductions(conn, cmd, selDeductionTransactionDel, selDelMonth, selDelYear);
string deductionDetailsDelStatus = deletePosting.unpostDeductionDetails(conn, cmd, selDeductionTransactionDel);
string deductionDatesDelStatus = deletePosting.unpostDeductionDates(conn, cmd, selDelMonth, selDelYear);
//MessageBox.Show("Savings Status: " + savingsDelStatus + "\nLoans Status: " + loanDelStatus + "\nDeductions: " + deductionDelStatus + "\nDeduction Detials: " + deductionDetailsDelStatus);
if ((Convert.ToInt16(deductionDelStatus) != 0) && (Convert.ToInt16(deductionDetailsDelStatus) != 0) && (Convert.ToInt16(deductionDelStatus) != 0))
{
sqlTrans.Commit();
ActivityLog.logActivity(UserId, "Unpost Deduction - Bulk", "Unpost Deduction Record ID:" + selDeductionId + " for " + selDelMonth + " " + selDelYear);
MessageBox.Show("Selected record has been Successfully Deleted.", "Unpost Deduction", MessageBoxButtons.OK, MessageBoxIcon.Information);
UnpostDeductions unpostDeductions = new UnpostDeductions(UserId);
unpostDeductions.MdiParent = this.ParentForm;
unpostDeductions.Show();
this.Close();
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred.", "Unpost Deduction", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void dtGrdSingleDeductions_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dtGrdSingleDeductions.SelectedRows.Count > 0)
{
DateTime postedDate = Convert.ToDateTime(dtGrdSingleDeductions.SelectedRows[0].Cells[9].Value.ToString());
DateTime today = DateTime.Now;
int daysDiff = Convert.ToInt16((today - postedDate).TotalDays);
if (daysDiff > 10)
{
lblSingleStatus.Text = "Status: Posted " + daysDiff + " days ago";
btnSingleUnpost.Enabled = false;
}
else
{
lblSingleStatus.Text = "Status: Posted " + daysDiff + " days ago";
btnSingleUnpost.Enabled = true;
}
}
}
private void btnSingleUnpost_Click(object sender, EventArgs e)
{
int memberID;
if (dtGrdSingleDeductions.SelectedRows.Count > 0)
{
selDeductionId = Convert.ToInt16(dtGrdSingleDeductions.SelectedRows[0].Cells[0].Value.ToString());
selDelMonth = dtGrdSingleDeductions.SelectedRows[0].Cells[1].Value.ToString();
selDelYear = Convert.ToInt16(dtGrdSingleDeductions.SelectedRows[0].Cells[2].Value.ToString());
memberID = Convert.ToInt16(dtGrdSingleDeductions.SelectedRows[0].Cells[3].Value.ToString());
selDedTransactionId = dtGrdSingleDeductions.SelectedRows[0].Cells[8].Value.ToString();
//MessageBox.Show("ID: " + selDeductionId.ToString() + "Month: " + selDelMonth.ToString() + " Year: " + selDelYear.ToString() + "MemberID: " + memberID.ToString() + "TransactionID: " + selDedTransactionId);
}
else
{
MessageBox.Show("Choose a Member Deduction Record to Delete", "Unpost Deduction", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
DialogResult res = MessageBox.Show("Do you wish to Unpost the Selected Record?", "Unpost", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
SqlConnection conn = ConnectDB.GetConnection();
SqlCommand cmd = conn.CreateCommand();
try
{
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
cmd.CommandType = CommandType.Text;
cmd.Transaction = sqlTrans;
Cl_UnpostDeductions deletePosting = new Cl_UnpostDeductions();
string savingsDelStatus = deletePosting.unpostSavingsDeductions(conn, cmd, memberID, selDedTransactionId);
string loanDelStatus = deletePosting.unpostLoansDeduction(conn, cmd, memberID, selDedTransactionId);
string deductionDelStatus = deletePosting.unpostDeductions(conn, cmd, memberID, selDedTransactionId, selDelMonth, selDelYear);
string deductionDetailsDelStatus = deletePosting.unpostDeductionDetails(conn, cmd, memberID, selDedTransactionId);
//MessageBox.Show("Savings Status: " + savingsDelStatus + "\nLoans Status: " + loanDelStatus + "\nDeductions: " + deductionDelStatus + "\nDeduction Detials: " + deductionDetailsDelStatus);
if ((Convert.ToInt16(savingsDelStatus) != 0) || (Convert.ToInt16(deductionDetailsDelStatus) != 0) || (Convert.ToInt16(deductionDelStatus) != 0))
{
sqlTrans.Commit();
ActivityLog.logActivity(UserId, "Unpost Deduction - Single", "Unpost Deduction for MemberID:" + memberID + " for " + selDelMonth + " " + selDelYear);
MessageBox.Show("Selected record has been Successfully Deleted.", "Unpost Deduction", MessageBoxButtons.OK, MessageBoxIcon.Information);
UnpostDeductions unpostDeductions = new UnpostDeductions(UserId);
unpostDeductions.MdiParent = this.ParentForm;
unpostDeductions.Show();
this.Close();
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred.", "Unpost Deduction", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void btnFilter_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
SqlCommand cmd = conn.CreateCommand();
string strQuery = "Select d.DeductionID 'ID', mn.Month, d.Year,m.MemberID, m.FileNo, m.LastName, m.FirstName, m.MiddleName, d.TransactionID, d.DatePosted 'Date Posted' from Deductions d " +
"left join MonthByName mn on d.Month=mn.MonthID " +
"left join Members m on m.MemberID = d.MemberID " +
"where m.FileNo='" + txtSearch.Text.Trim() + "' OR LastName='" + txtSearch.Text.Trim() + "' " +
"order by d.DeductionID desc";
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Deductions");
DataTable dt = ds.Tables["Deductions"];
dtGrdSingleDeductions.DataSource = dt;
dtGrdSingleDeductions.Columns["MemberID"].Visible = false;
dtGrdSingleDeductions.Columns["ID"].Width = 60;
dtGrdSingleDeductions.Columns["Month"].Width = 70;
dtGrdSingleDeductions.Columns["Year"].Width = 40;
dtGrdSingleDeductions.Columns["FileNo"].Width = 60;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Settings/CreateLoanCategory.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class CreateLoanCategory : Form
{
public CreateLoanCategory()
{
InitializeComponent();
}
private void txtName_TextChanged(object sender, EventArgs e)
{
if (txtName.Text != string.Empty)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into LoanCategory(Name,Description)values(@Name,@Description)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100);
cmd.Parameters["@Name"].Value = txtName.Text.Trim();
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmd.Parameters["@Description"].Value = txtDescription.Text.Trim();
try
{
conn.Open();
int rowsAffected = 0;
rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Category " + txtName.Text + " has been successfully created.", "Create Loan Category", MessageBoxButtons.OK, MessageBoxIcon.Information);
clearFields();
loadLoanCategories();
}
else
{
MessageBox.Show("An error has occurred!", "Create Loan Category", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void clearFields()
{
txtName.Text = string.Empty;
txtDescription.Text = string.Empty;
}
private void CreateLoanCategory_Load(object sender, EventArgs e)
{
loadLoanCategories();
}
private void loadLoanCategories()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select Name, Description, DateCreated as [Date Created] from LoanCategory";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
grdLoansCategory.DataSource = dt;
lblRecord.Text = "No. of Records: " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
clearFields();
}
}
}
<file_sep>/MainApp/MainApp/Classes/FieldValidator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MainApp
{
public static class FieldValidator
{
public static bool isBlank(string fieldValue)
{
bool result;
if (fieldValue == string.Empty)
{
result = true;
}
else
{
result = false;
}
return result;
}
}
}
<file_sep>/MainApp/MainApp/Savings/ViewSavingsDetails.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewSavingsDetails : Form
{
private string selectedSavingsID;
private string selectedSavingSource;
private string selectedTransactionID;
public ViewSavingsDetails(string savingsID, string savingSource, string transactionID)
{
InitializeComponent();
selectedSavingsID = savingsID;
selectedSavingSource = savingSource;
selectedTransactionID = transactionID;
}
private void ViewSavingsDetails_Load(object sender, EventArgs e)
{
string tableName = string.Empty;
switch (selectedSavingSource)
{
case "Contribution":
tableName = "Contributions";
break;
case "Loan":
tableName = "Loans";
break;
case "Deduction":
tableName = "Deductions";
break;
case "Deduction - Loan Repayment Excess":
tableName = "Deductions";
break;
case "SavingsForward":
tableName = "SavingsForward";
break;
case "Withdrawal":
tableName = "SavingsWithdrawal";
break;
}
getSavingsInfo();
getSavingDetailsInfo(tableName,selectedTransactionID);
}
private void getSavingsInfo()
{
//MessageBox.Show(selectedSavingsID.ToString());
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select s.SavingsID 'Savings ID', m.FileNo 'File No',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"s.SavingSource 'Saving Source', s.Amount, mon.Month + ' ' + s.Year 'Period', s.Date " +
"from Savings s left join Members m on m.MemberID = s.MemberID " +
"left join MonthByName mon on s.Month=mon.MonthID where s.SavingsID=" + selectedSavingsID;
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds,"Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdSavings.DataSource = dt;
dtGrdSavings.Columns["File No"].Width = 90;
dtGrdSavings.Columns["Full Name"].Width = 200;
dtGrdSavings.Columns["Saving Source"].Width = 150;
dtGrdSavings.Columns["Savings ID"].Visible = true;
dtGrdSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getSavingDetailsInfo(string tableName, string selectedTransactionID)
{
string strQuery = string.Empty;
//MessageBox.Show("TableName: " + tableName + "\nTransactionID: " + selectedTransactionID);
switch (tableName)
{
case "Deductions":
strQuery = "Select d.DeductionID 'Deduction ID',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"mon.Month,d.Year,d.Savings,d.Loans,d.Total,d.TransactionID,d.DatePosted as 'Date Posted' " +
"from Deductions d left join Members m on d.MemberID = m.MemberID " +
"left join MonthByName mon on mon.MonthID=d.Month " +
"where d.TransactionID='" + selectedTransactionID + "'";
//MessageBox.Show(strQuery);
break;
case "SavingsForward":
BuildTempSavingsAcctType.Create();
strQuery = "Select SavingsForwardID 'SF ID',mon.Month,sf.Year,t.SavingsName 'Saving Type',sf.Amount,sf.Comment, " +
"sf.TransactionID,sf.DatePosted from SavingsForward sf left join MonthByName mon on sf.Month=mon.MonthID " +
"left join TempSavingsAcctType t on sf.SavingsTypeID=t.SavingsTypeID " +
"where sf.SavingsID=" + selectedSavingsID;
break;
case "Contributions":
BuildTempSavingsAcctType.Create();
strQuery = "Select c.ContributionID 'Contribution ID',p.PaymentMode 'Payment Mode',c.OtherPayment 'Other Payment',b.BankName 'Bank Name',t.SavingsName 'Savings Type',c.TellerNo 'Teller No',c.ReceiptNo 'ReceiptNo', " +
"c.Comment,c.TransactionID,c.Date from Contributions c " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join Banks b on b.BankID=c.BankID " +
"left join TempSavingsAcctType t on c.SavingsAcctID=t.SavingsTypeID " +
"where c.SavingsID=" + selectedSavingsID;
break;
case "Loans":
strQuery = "Select l.LoansID 'Loan ID',l.LoanApplicationID 'App. ID', m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"a.LoanAmount 'Loan Amount',a.InterestRate 'Interest Rate',a.interestAmount 'Interest Amt.',a.MonthlyRepayment 'Monthly Repayment', " +
"l.RepaymentAmount 'Total Repayment',l.AmountPaid 'Amt. Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status', " +
"mon.Month 'App. Month',a.AppYear 'App. Year',mth.Month 'Start Repayment Mth.',a.StartRepaymentYear 'Start Repayment Yr.', lc.Name 'Loan Category',lt.Type 'Loan Type', l.DateFinishedPayment 'Finished Repayment', l.TransactionID,l.DateCreated 'Date Created'" +
"from Loans l inner join LoanApplication a on a.LoanApplicationID=l.LoanApplicationID " +
"left join Members m on m.MemberID=a.MemberID " +
"left join LoanCategory lc on a.LoanCategoryID=lc.LoanCategoryID " +
"left join LoanType lt on a.LoanTypeID=lt.LoanTypeID " +
"left join MonthByName mon on mon.MonthID=a.AppMonth " +
"left join MonthByName mth on mth.MonthID=a.StartRepaymentMonth " +
"where l.TransactionID='" + selectedTransactionID + "'";
break;
case "SavingsWithdrawal":
strQuery = "Select w.SavingsWithdrawalID 'ID',w.SavingsID 'Savings ID', st.SavingsName 'Savings Type', w.Amount,w.WithdrawAmount 'Withdrawal',w.Balance,w.Date from SavingsWithdrawal w " +
"inner join SavingsType st on w.SavingsTypeID=st.SavingsTypeID " +
"where w.SavingsID = " + selectedSavingsID +
" order by w.SavingsWithdrawalID desc";
break;
}
SqlConnection conn = ConnectDB.GetConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingDetails");
DataTable dt = ds.Tables["SavingDetails"];
dtGrdSavingDetails.DataSource = dt;
if (tableName == "Deductions")
{
dtGrdSavingDetails.Columns["Savings"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Loans"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Total"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Full Name"].Width = 250;
}
else if (tableName=="SavingsForward")
{
dtGrdSavingDetails.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
else if (tableName == "Loans")
{
dtGrdSavingDetails.Columns["Loan Amount"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Loan Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Interest Rate"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Interest Rate"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Interest Amt."].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Interest Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Monthly Repayment"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Monthly Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Total Repayment"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Total Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Amt. Paid"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Amt. Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Payment Status"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Payment Status"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
else if (tableName == "SavingsWithdrawal")
{
dtGrdSavingDetails.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Withdrawal"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Withdrawal"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdSavingDetails.Columns["Balance"].DefaultCellStyle.Format = "N2";
dtGrdSavingDetails.Columns["Balance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Banks/EditBank.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditBank : Form
{
Hashtable banks;
public EditBank()
{
InitializeComponent();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void EditBank_Load(object sender, EventArgs e)
{
//LV properties
lstBank.View = View.Details;
lstBank.FullRowSelect = true;
//column name
lstBank.Columns.Add("Banks", 450);
loadBanks();
}
#region Load Banks into ListView
private void loadBanks()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName, Description from Banks";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
banks = new Hashtable();
SqlDataReader reader = cmd.ExecuteReader();
lstBank.Items.Clear();
int countRecords = 0;
while (reader.Read())
{
banks.Add(reader["BankName"].ToString(), reader["Description"].ToString());
lstBank.Items.Add(reader["BankName"].ToString());
countRecords++;
}
lblRecordNo.Text = "No. of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
private void lstBank_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstBank.SelectedItems.Count != 0)
{
string BankName = lstBank.SelectedItems[0].SubItems[0].Text;
txtName.Text = BankName;
txtDescription.Text = banks[BankName].ToString();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lstBank.SelectedItems.Count == 0)
{
MessageBox.Show("No Bank Information has been selected for Update","Edit Bank",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
else
{
string selectedBank = lstBank.SelectedItems[0].SubItems[0].Text;
if (txtName.Text == string.Empty)
{
MessageBox.Show("Bank Name is required to edit '" + selectedBank + "' Information", "Edit Bank", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateBankInfo(selectedBank);
}
}
}
private void updateBankInfo(string selectedBank)
{
string selBank = selectedBank;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Update Banks set BankName=@BankName,Description=@Description where BankName=@selBank";
SqlCommand cmd = new SqlCommand(strQuery,conn);
cmd.Parameters.Add("@BankName", SqlDbType.NVarChar, 50);
cmd.Parameters["@BankName"].Value = txtName.Text.Trim();
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmd.Parameters["@Description"].Value = txtDescription.Text.Trim();
cmd.Parameters.Add("@selBank", SqlDbType.NVarChar, 50);
cmd.Parameters["@selBank"].Value = selBank;
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected>0)
{
MessageBox.Show("The Bank '" + selBank + "' has been edited and updated!", "Edit Bank", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadBanks();
}
else
{
MessageBox.Show("An error has occurred updating '" + selBank + "'", "Edit Bank", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
txtName.Clear();
txtDescription.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtName.Clear();
txtDescription.Clear();
}
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName, Description from Banks where BankName LIKE '%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
banks = new Hashtable();
int countRecords = 0;
lstBank.Items.Clear();
while (reader.Read())
{
banks.Add(reader["BankName"].ToString(), reader["Description"].ToString());
string[] row = { reader["BankName"].ToString() };
ListViewItem item = new ListViewItem(row);
lstBank.Items.Add(item);
countRecords++;
}
lblRecordNo.Text = "No. of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnAll_Click(object sender, EventArgs e)
{
txtSearch.Clear();
loadBanks();
}
}
}
<file_sep>/MainApp/MainApp/Members/FindMember.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class FindMember : Form
{
public FindMember()
{
InitializeComponent();
}
private void FindMember_Load(object sender, EventArgs e)
{
loadMembersIntoList();
//Savings ListView Properties
lstVSavings.View = View.Details;
lstVSavings.FullRowSelect = true;
//Setting ListView Columns
lstVSavings.Columns.Add("Savings Type", 250);
lstVSavings.Columns.Add("Amount", 100);
}
private void loadMembersIntoList()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "select MemberID,FileNo,Title + ' ' + LastName + ' ' + MiddleName + ' ' + FirstName as FullName from Members order by FileNo";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int counter = 0;
lstMembers.Items.Clear();
while (reader.Read())
{
lstMembers.Items.Add(reader["FileNo"] + " - " + reader["FullName"]);
counter++;
}
lblRecordNo.Text = "No. of Records : " + counter;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void lstMembers_SelectedIndexChanged(object sender, EventArgs e)
{
if (grpMemberInfo.Visible == false)
{
grpMemberInfo.Visible = true;
}
//Clear lstVSavingsType of Existing Information
lstVSavings.Items.Clear();
int memberID = 0;
string recordIdentifier = lstMembers.SelectedItem.ToString();
string selectedRecordFileNo = recordIdentifier.Substring(0, recordIdentifier.IndexOf("-")).Trim();
SqlConnection conn = ConnectDB.GetConnection();
//Get Member Profile Info
memberID = fetchMemberProfileData(memberID, selectedRecordFileNo, conn);
//Get Member Shares
fetchMemberSharesInfo(memberID, conn);
fetchMemberSavingsAcct(memberID, conn);
}
private void fetchMemberSharesInfo(int memberID, SqlConnection conn)
{
string strShares = "Select MemberID, Shares from Shares where MemberID=" + memberID;
SqlCommand cmdShares = new SqlCommand(strShares, conn);
try
{
conn.Open();
SqlDataReader readShares = cmdShares.ExecuteReader();
if (readShares.HasRows)
{
readShares.Read();
string savingsType = "Shares";
string amount = readShares["Shares"].ToString();
amount = string.Format("{0:0,0.00}", Convert.ToDecimal(amount));
string[] row = { savingsType, amount };
ListViewItem item = new ListViewItem(row);
lstVSavings.Items.Add(item);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private int fetchMemberProfileData(int memberID, string selectedRecordFileNo, SqlConnection conn)
{
string strQuery = "Select m.MemberID, m.FileNo, m.Title, m.FirstName, m.MiddleName, m.LastName, m.Gender, m.Address," +
"m.LGA, s.State, m.Phone, m.Email, d.DepartmentName, b.BankName, m.AccountNo, m.Photo,m.NOKFullName,m.NOKAddress," +
"m.NOKPhone from Members m inner join States s on m.StateID = s.StateID " +
"inner join Departments d on m.DepartmentID = d.DepartmentID " +
"inner join Banks b on m.BankID = b.BankID " +
"where m.FileNo='" + selectedRecordFileNo + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txtFileNo.Text = reader["FileNo"].ToString();
txtTitle.Text = reader["Title"].ToString();
txtFirstName.Text = reader["FirstName"].ToString();
txtMIddleName.Text = reader["MiddleName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtGender.Text = (reader["Gender"].ToString() == "M" ? "Male" : "Female");
txtAddress.Text = reader["Address"].ToString();
txtLGA.Text = reader["LGA"].ToString();
txtState.Text = reader["State"].ToString();
txtPhone.Text = reader["Phone"].ToString();
txtEmail.Text = reader["EMail"].ToString();
txtDepartment.Text = reader["DepartmentName"].ToString();
txtBank.Text = reader["BankName"].ToString();
txtAccountNo.Text = reader["AccountNo"].ToString();
txtNOKName.Text = reader["NOKFullName"].ToString();
txtNOKAddress.Text = reader["NOKAddress"].ToString();
txtNOKPhone.Text = reader["NOKPhone"].ToString();
string paths = PhotoPath.getPath();
if (reader["Photo"].ToString() != string.Empty)
{
//Load User picture
//string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 9));
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
//MessageBox.Show(paths);
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
memberID = (int)reader["MemberID"];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return memberID;
}
private void fetchMemberSavingsAcct(int memberID, SqlConnection conn)
{
string strSavingsAcct = "Select MemberID, SavingsTypeID, Amount, Remark from MemberSavingsTypeAcct where MemberID=" + memberID + " order by SavingsTypeID desc";
SqlCommand cmdSavingsAcct = new SqlCommand(strSavingsAcct, conn);
try
{
conn.Open();
SqlDataReader readerSavingsAcct = cmdSavingsAcct.ExecuteReader();
if (readerSavingsAcct.HasRows)
{
while (readerSavingsAcct.Read())
{
string savingTypeAcct = readerSavingsAcct["Remark"].ToString();
string amount = readerSavingsAcct["Amount"].ToString();
amount = string.Format("{0:0,0.00}", Convert.ToDecimal(amount));
string[] row = { savingTypeAcct, amount };
ListViewItem item = new ListViewItem(row);
lstVSavings.Items.Add(item);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnFindMember_Click(object sender, EventArgs e)
{
if (txtFindMember.Text != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select FileNo, Title + ' ' + LastName + ' ' + MiddleName + ' ' + FirstName as FullName from Members where FileNo LIKE '%"
+ txtFindMember.Text + "%' OR LastName LIKE '%" + txtFindMember.Text + "%' OR FirstName LIKE '%"
+ txtFindMember.Text + "%' OR MiddleName LIKE '%" + txtMIddleName + "%' order by FileNo";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int counter = 0;
lstMembers.Items.Clear();
if (reader.HasRows)
{
while (reader.Read())
{
lstMembers.Items.Add(reader["FileNo"] + " - " + reader["FullName"]);
counter++;
}
}
else
{
grpMemberInfo.Visible = false;
MessageBox.Show("Sorry, no record with that information is found", "Find Member", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
lblRecordNo.Text = "No. of Records : " + counter.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}else{
loadMembersIntoList();
}
}
private void txtFindMember_TextChanged(object sender, EventArgs e)
{
if (txtFindMember.Text == string.Empty)
{
loadMembersIntoList();
}
}
}
}
<file_sep>/MainApp/MainApp/Departments/AddDepartment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class AddDepartment : Form
{
public AddDepartment()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void AddDepartment_Load(object sender, EventArgs e)
{
loadDepartments();
}
public void loadDepartments()
{
SqlConnection conn = ConnectDB.GetConnection();
string selectDept = "Select DepartmentID, DepartmentName,Description from Departments";
SqlCommand cmd = new SqlCommand(selectDept, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Departments");
DataTable dt = ds.Tables["Departments"];
dtGrdDepartment.DataSource = dt;
dtGrdDepartment.Columns["DepartmentID"].Visible = false;
dtGrdDepartment.Columns[1].HeaderText = "Department Name";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " From Load Departments Function");
}
finally
{
conn.Close();
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
//check if Department Name has been supplied into the Department Field
if (txtDepartmentName.Text == string.Empty)
{
MessageBox.Show("Department Name is required","Add Department Info",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
else
{
string departmentName = txtDepartmentName.Text;
string description = txtDescription.Text;
//check if department name has been already supplied
bool deptAlreadyExist = checkDeptExist(departmentName);
if (deptAlreadyExist == false)
{
SqlConnection conn = ConnectDB.GetConnection();
string strInsert = "Insert into Departments(DepartmentName,Description)values(@DepartmentName,@Description)";
SqlCommand cmdInsert = new SqlCommand(strInsert, conn);
cmdInsert.Parameters.Add("@DepartmentName", SqlDbType.NVarChar, 100);
cmdInsert.Parameters["@DepartmentName"].Value = departmentName;
cmdInsert.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmdInsert.Parameters["@Description"].Value = description;
try
{
conn.Open();
int rowsAffected = cmdInsert.ExecuteNonQuery();
if (rowsAffected > 0)
{
this.loadDepartments();
this.dtGrdDepartment.Update();
MessageBox.Show("The Department '" + departmentName + "' has been added", "Add Department", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtDepartmentName.Clear();
}
else
{
MessageBox.Show("An error has occured!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Button Add click function... ");
}
finally
{
conn.Close();
}
}
else
{
//Show Message that DepartmentName has already been added
MessageBox.Show("The Department '" + departmentName + "' has been created", "Department Creation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}//end of if (deptAlreadyExist==false)
}// end of if (txtDepartmentName.Text == string.Empty)
}
private bool checkDeptExist(string departmentName)
{
int deptAlreadyExist=0;
SqlConnection conn = ConnectDB.GetConnection();
string checkDept = "Select count(*) from Departments where DepartmentName=@DepartmentName";
SqlCommand cmd = new SqlCommand(checkDept,conn);
cmd.Parameters.Add("@DepartmentName", SqlDbType.NVarChar,100);
cmd.Parameters["@DepartmentName"].Value = departmentName;
try{
conn.Open();
deptAlreadyExist = Convert.ToInt16(cmd.ExecuteScalar().ToString());
}catch(Exception ex)
{
MessageBox.Show(ex.Message + "from CheckDeptExist function");
}finally{
conn.Close();
}
if (deptAlreadyExist>0)
{
return true;
}else{
return false;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtDepartmentName.Clear();
txtDescription.Clear();
}
}
}
<file_sep>/MainApp/MainApp/Banks/DeleteBank.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
namespace MainApp
{
public partial class DeleteBank : Form
{
public DeleteBank()
{
InitializeComponent();
}
private void DeleteBank_Load(object sender, EventArgs e)
{
//LV properties
lstBank.View = View.Details;
lstBank.FullRowSelect = true;
//LV Column Name
lstBank.Columns.Add("Bank", 400);
loadBank();
}
#region Load Bank
private void loadBank()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName from Banks";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int countRecord = 0;
lstBank.Items.Clear();
while (reader.Read())
{
string[] row = { reader["BankName"].ToString() };
ListViewItem item = new ListViewItem(row);
lstBank.Items.Add(item);
countRecord++;
}
lblRecord.Text = "No. of Records: " + countRecord.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
private void btnSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text != string.Empty)
{
searchBank();
}
else
{
MessageBox.Show("Bank Name is required to make a search", "Bank Search", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
#region Search Bank
private void searchBank()
{
string bankName = txtSearch.Text.Trim();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName from Banks where BankName LIKE '%" + bankName + "%'";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int countRecords = 0;
lstBank.Items.Clear();
while(reader.Read())
{
string[] row = {reader["BankName"].ToString()};
ListViewItem item = new ListViewItem(row);
lstBank.Items.Add(item);
countRecords++;
}
lblRecord.Text = "No. of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
private void btnAll_Click(object sender, EventArgs e)
{
loadBank();
}
private void btnDeleteBank_Click(object sender, EventArgs e)
{
if (lstBank.SelectedItems.Count != 0)
{
DialogResult result = MessageBox.Show("Do you wish to Delete '" + lstBank.SelectedItems[0].SubItems[0].Text + "'?","Delete Bank",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
deleteBank();
}
else
{
loadBank();
}
}
else
{
MessageBox.Show("No Bank has been selected for Deletion","Delete Bank",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
#region Delete Bank
private void deleteBank()
{
string bankName = lstBank.SelectedItems[0].SubItems[0].Text.Trim();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Delete from Banks where BankName='" + bankName + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("The Bank '" + bankName + "' has been successfully deleted.", "Delete Bank", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadBank();
}
else
{
MessageBox.Show("An error has occurred deleting '" + bankName + "'", "Delete Bank", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
}
}
<file_sep>/MainApp/MainApp/Classes/SavingsByAcctType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace MainApp
{
public class SavingsByAcctType
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = string.Empty;
public SavingsByAcctType()
{
}
public decimal getContributionSavings(string memberID,int savingsTypeID)
{
decimal contributionSavings = 0;
string strFound = "Select count(*) from Savings s inner join Contributions c " +
"on c.SavingsID=s.SavingsID where s.MemberID='" + memberID +
"' and c.SavingsAcctID=" + savingsTypeID;
strQuery = "Select SUM(s.Amount) from Savings s inner join Contributions c " +
"on c.SavingsID=s.SavingsID where s.MemberID='" + memberID +
"' and c.SavingsAcctID=" + savingsTypeID;
SqlCommand cmdFound = new SqlCommand(strFound, conn);
SqlCommand cmdQuery = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowFound = Convert.ToInt16(cmdFound.ExecuteScalar());
if (rowFound > 0)
{
contributionSavings = Convert.ToDecimal(cmdQuery.ExecuteScalar());
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
return contributionSavings;
}
public decimal getSavingsForward(string memberID, int savingsTypeID)
{
decimal savingsForwardByType = 0;
string strFound = "Select count(*) from SavingsForward sf inner join Savings s " +
"on s.SavingsID=sf.SavingsID where s.MemberID='" + memberID +
"' and sf.SavingsTypeID=" + savingsTypeID ;
strQuery = "Select Sum(sf.Amount) from SavingsForward sf inner join Savings s " +
"on s.SavingsID=sf.SavingsID where s.MemberID='" + memberID +
"' and sf.SavingsTypeID=" + savingsTypeID;
SqlCommand cmdFound = new SqlCommand(strFound, conn);
SqlCommand cmdQuery = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowFound = Convert.ToInt16(cmdFound.ExecuteScalar());
if (rowFound > 0)
{
savingsForwardByType = Convert.ToDecimal(cmdQuery.ExecuteScalar());
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
return savingsForwardByType;
}
public decimal getDeductionSavings(string memberID, int savingsTypeID)
{
decimal deductionSavingType = 0;
SqlConnection conn = ConnectDB.GetConnection();
string strFound = "Select count(*) from DeductionDetails dd left join Deductions d on " +
"dd.DeductionID=d.DeductionID where d.MemberID='" + memberID + "' and dd.SavingsTypeID=" + savingsTypeID;
string strQuery = "Select SUM(dd.Amount) from DeductionDetails dd inner join Deductions d on " +
"dd.DeductionID=d.DeductionID where d.MemberID='" + memberID + "' and dd.SavingsTypeID=" + savingsTypeID;
SqlCommand cmdFound = new SqlCommand(strFound, conn);
SqlCommand cmdQuery = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowFound = Convert.ToInt16(cmdFound.ExecuteScalar());
if (rowFound > 0)
{
deductionSavingType = Convert.ToDecimal(cmdQuery.ExecuteScalar());
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
return deductionSavingType;
}
public decimal getWithdrawalSavings(string memberID, int savingsTypeID)
{
decimal withdrawalSavingsType = 0;
SqlConnection conn = ConnectDB.GetConnection();
string strFound = "Select count(*) from SavingsWithdrawal where MemberID=" + memberID + " and " +
"SavingsTypeID=" + savingsTypeID;
string strQuery = "Select SUM(WithdrawAmount) from SavingsWithdrawal where MemberID=" + memberID + " and " +
"SavingsTypeID=" + savingsTypeID;
SqlCommand cmdFound = new SqlCommand(strFound, conn);
SqlCommand cmdQuery = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowFound = Convert.ToInt16(cmdFound.ExecuteScalar());
if (rowFound > 0)
{
withdrawalSavingsType = Convert.ToDecimal(cmdQuery.ExecuteScalar());
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
return withdrawalSavingsType;
}
}
}
<file_sep>/MainApp/MainApp/Classes/BuildTempSavingsAcctType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public static class BuildTempSavingsAcctType
{
public static void Create()
{
Hashtable savingsType = new Hashtable();
savingsType.Add("99","Shares Savings");
SqlConnection conn = ConnectDB.GetConnection();
string strTruncate = "Truncate Table TempSavingsAcctType";
string strQuery = "Select SavingsTypeID,SavingsName from SavingsType";
string strInsert = "Insert into TempSavingsAcctType(SavingsTypeID,SavingsName)Values(@SavingsTypeID,@SavingsName)";
SqlCommand cmdTruncate = new SqlCommand(strTruncate, conn);
SqlCommand cmdQuery = new SqlCommand(strQuery,conn);
SqlCommand cmdInsert = new SqlCommand(strInsert, conn);
try
{
conn.Open();
SqlDataReader reader = cmdQuery.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
savingsType.Add(reader["SavingsTypeID"].ToString(), reader["SavingsName"].ToString());
}
}
reader.Close();
//Excute Truncate Command on Table
cmdTruncate.ExecuteNonQuery();
//Sqlcommand parameters
cmdInsert.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmdInsert.Parameters.Add("@SavingsName", SqlDbType.NVarChar, 50);
foreach (DictionaryEntry item in savingsType)
{
cmdInsert.Parameters["@SavingsTypeID"].Value = item.Key;
cmdInsert.Parameters["@SavingsName"].Value = item.Value;
cmdInsert.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Members/MembershipWithdrawal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class MembershipWithdrawal : Form
{
SqlConnection conn;
string memberID;
public MembershipWithdrawal()
{
InitializeComponent();
}
private void btnFindMember_Click(object sender, EventArgs e)
{
conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo, LastName + ' ' + FirstName + ' ' + MiddleName as FullName, photo from Members " +
"where FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = reader["MemberID"].ToString();
lblMemberProfileInfo.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
//display member photo
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
if (reader["Photo"].ToString() != null || reader["Photo"].ToString() == string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
picMember.Visible = true;
lblMemberProfileInfo.Visible = true;
getSavingStatus();
getLoanStatus();
}
else
{
MessageBox.Show("Sorry, there is no member with that File No.", "Membership", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}finally{
conn.Close();
}
}
private void getSavingStatus()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SUM(Amount) as TotalSavings from Savings where MemberID=" + memberID;
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
lblFinancialStatus.Text = "Savings: " + CheckForNumber.formatCurrency2(reader["TotalSavings"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
lblFinancialStatus.Visible = true;
}
private void getLoanStatus()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select count(*) as counter from Loans l " +
"left join LoanApplication a on l.LoanApplicationID = a.LoanApplicationID " +
"where (l.PaymentFinished is NULL or l.PaymentFinished='No') " +
"and a.MemberID=" + memberID;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
int recFound =(int) cmd.ExecuteScalar();
if (recFound > 0)
{
strQuery = "Select SUM(l.OutstandingAmount) as Outstanding from Loans l " +
"left join LoanApplication a on l.LoanApplicationID = a.LoanApplicationID " +
"where (l.PaymentFinished is NULL or l.PaymentFinished='No') " +
"and a.MemberID=" + memberID;
cmd.CommandText = strQuery;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
string outstandingAmount = reader["Outstanding"].ToString();
lblFinancialStatus.Text += "\nOutstanding Loan: " + CheckForNumber.formatCurrency2(outstandingAmount) + " from " + recFound.ToString() + " Loan Applications";
reader.Close();
}
else
{
lblFinancialStatus.Text += "\n" + "No Outstanding Loan to pay.";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtComment_TextChanged(object sender, EventArgs e)
{
if (txtComment.Text == string.Empty)
{
btnWithdraw.Enabled = false;
}
else
{
btnWithdraw.Enabled = true;
}
}
private void btnShowHide_Click(object sender, EventArgs e)
{
if (btnShowHide.Text == "Show Withdrawned Sheet")
{
this.Height = 523;
btnShowHide.Text = "Hide Withdrawned Sheet";
}
else
{
this.Height = 207;
btnShowHide.Text = "Show Withdrawned Sheet";
}
}
private void MembershipWithdrawal_Load(object sender, EventArgs e)
{
this.Height = 207;
}
}
}
<file_sep>/MainApp/MainApp/Loans/DeleteLoanApplication.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class DeleteLoanApplication : Form
{
string strFilterMonth = string.Empty;
string strFilterYear = string.Empty;
DataTable dt;
public DeleteLoanApplication()
{
InitializeComponent();
}
private void DeleteLoanApplication_Load(object sender, EventArgs e)
{
loadAllLoanApplicationRecords(strFilterMonth,strFilterYear);
}
private void loadAllLoanApplicationRecords(string strFilterMonth, string strFilterYear)
{
string strWhereClause = string.Empty;
if (strFilterMonth == "0")
{
strFilterMonth = string.Empty;
}
if (strFilterMonth != string.Empty && strFilterYear == string.Empty)
{
strWhereClause = "where a.AppMonth like '" + strFilterMonth + "'";
}
else if (strFilterMonth == string.Empty && strFilterYear != string.Empty)
{
strWhereClause = "where a.AppYear like '" + strFilterYear + "'";
}
else if (strFilterMonth != string.Empty && strFilterYear != string.Empty)
{
strWhereClause = "where a.AppMonth like '" + strFilterMonth + "' and a.AppYear like '" + strFilterYear + "'";
}
//MessageBox.Show(strWhereClause.ToString());
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select a.LoanApplicationID as ID, c.Month, a.AppYear as Year, m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"lc.Name as Category, lt.Type as Type, a.LoanAmount as Amount, a.InterestRate 'Interest Rate (%)', a.InterestAmount 'Interest Amount', a.TotalRepayment 'Total Repayment', " +
"a.MonthlyRepayment 'Monthly Repayment', a.LoanDuration 'Loan Duration (Mnths)', sr.Month as 'Start Repay Month',a.StartRepaymentYear as 'Start Repay Year.', " +
"s1.LastName + ' ' + s1.FirstName + ' ' + s1.MiddleName as 'Surety1', " +
"s2.LastName + ' ' + s2.FirstName + ' ' + s2.MiddleName as 'Surety2', " +
"s3.LastName + ' ' + s3.FirstName + ' ' + s3.MiddleName as Witness, " +
"a.NonMemberSurety1 as 'Non-Member Surety1', a.NonMemberSurety2 as 'Non-Member Surety2', " +
"a.NonMemberWitness as 'Non-Member Witness', " +
"a.ApprovalStatus 'Approval Status', a.TransactionID, a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Members m on a.MemberID = m.MemberID " +
"left join MonthByName c on a.AppMonth= c.MonthID " +
"left join MonthByName sr on a.StartRepaymentMonth = sr.MonthID " +
"left join LoanCategory lc on lc.LoanCategoryID = a.LoanCategoryID " +
"left join LoanType lt on lt.LoanTypeID = a.LoanTypeID " +
"left join Members s1 on s1.MemberID=a.SuretyMemberID1 " +
"left join Members s2 on s2.MemberID=a.SuretyMemberID2 " +
"left join Members s3 on s3.MemberID=a.WitnessMemberID " + strWhereClause +
"order by a.LoanApplicationID desc";
string strTotalFilteredRecords = "Select count(*) from LoanApplication a " + strWhereClause;
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanApplications");
dt = ds.Tables["LoanApplications"];
datGrdVwLoansApp.DataSource = dt;
datGrdVwLoansApp.Columns["ID"].Visible = false;
datGrdVwLoansApp.Columns["Full Name"].Width = 200;
datGrdVwLoansApp.Columns["Month"].Width = 70;
datGrdVwLoansApp.Columns["Year"].Width = 50;
datGrdVwLoansApp.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansApp.Columns["Interest Rate (%)"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansApp.Columns["Interest Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansApp.Columns["Total Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansApp.Columns["Monthly Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansApp.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGrdVwLoansApp.Columns["Interest Amount"].DefaultCellStyle.Format = "N2";
datGrdVwLoansApp.Columns["Total Repayment"].DefaultCellStyle.Format = "N2";
cmd = new SqlCommand(strTotalFilteredRecords, conn);
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
lblRecordNo.Text = "No. of Records: " + recordCount.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnFindRecord_Click(object sender, EventArgs e)
{
if (cboMonth.Text != string.Empty || cboYear.Text != string.Empty)
{
//MessageBox.Show(cboMonth.SelectedIndex.ToString());
strFilterMonth = cboMonth.SelectedIndex.ToString();
strFilterYear = cboYear.Text.ToString();
//MessageBox.Show(cboYear.Text.ToString());
loadAllLoanApplicationRecords(strFilterMonth, strFilterYear);
}
else
{
MessageBox.Show("Please Select Month and Year to Proceed with Search", "Find Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (datGrdVwLoansApp.SelectedCells.Count > 0)
{
int selectedRowIndex = datGrdVwLoansApp.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = datGrdVwLoansApp.Rows[selectedRowIndex];
string applicationID = Convert.ToString(selectedRow.Cells["ID"].Value);
string applicationStatus = Convert.ToString(selectedRow.Cells["Approval Status"].Value);
//MessageBox.Show(applicationID + ' ' + applicationStatus);
if (applicationStatus == string.Empty)
{
DialogResult res = MessageBox.Show("Do you really wish to delete the Selected Record?","Loan Application",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
DeleteSelectedAppRecord(applicationID);
}
}
else
{
MessageBox.Show("Selected Loan Application Record cannot be Deleted as it has been Treated and Archived", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
}
}
private void DeleteSelectedAppRecord(string applicationID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strDelete = "Delete from LoanApplication where LoanApplicationID=" + applicationID;
SqlCommand cmd = new SqlCommand(strDelete, conn);
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
//MessageBox.Show("The Selected Record has been Deleted", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
strFilterMonth = string.Empty;
strFilterYear = string.Empty;
loadAllLoanApplicationRecords(strFilterMonth,strFilterYear);
string userId = this.MdiParent.Controls["lblLoggedInUserID"].Text;
ActivityLog.logActivity(userId, "Delete Loan Application", "Loan Application with ID - " + applicationID + " was deleted.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnExport_Click(object sender, EventArgs e)
{
ExportData exportSavingsDetails = new ExportData();
exportSavingsDetails.ExportToExcel(dt, saveFD);
}
private void btnReload_Click(object sender, EventArgs e)
{
strFilterMonth = string.Empty;
strFilterYear = string.Empty;
loadAllLoanApplicationRecords(strFilterMonth, strFilterYear);
}
}
}
<file_sep>/MainApp/MainApp/Banks/ViewBanks.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewBanks : Form
{
public ViewBanks()
{
InitializeComponent();
}
private void ViewBanks_Load(object sender, EventArgs e)
{
//LV properties
lstBanks.View = View.Details;
lstBanks.FullRowSelect = true;
//column width
lstBanks.Columns.Add("Bank", 300);
lstBanks.Columns.Add("Description", 500);
loadBankList();
}
private void loadBankList()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "select BankName, Description from Banks";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
lstBanks.Items.Clear();
int countRecord = 0;
while(reader.Read())
{
string[] row = { reader["BankName"].ToString(), reader["Description"].ToString() };
ListViewItem item = new ListViewItem(row);
lstBanks.Items.Add(item);
countRecord++;
}
lblRecord.Text = "No.of Records: " + countRecord;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName,Description from Banks where BankName LIKE '%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
lstBanks.Items.Clear();
int countRecord = 0;
while (reader.Read())
{
string[] row = { reader["BankName"].ToString(), reader["Description"].ToString() };
ListViewItem item = new ListViewItem(row);
lstBanks.Items.Add(item);
countRecord++;
}
lblRecord.Text = "No.of Records: " + countRecord;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnAll_Click(object sender, EventArgs e)
{
loadBankList();
}
}
}
<file_sep>/MainApp/MainApp/Banks/AddBank.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class AddBank : Form
{
public AddBank()
{
InitializeComponent();
}
private void AddBank_Load(object sender, EventArgs e)
{
//LV properties
lstBank.View = View.Details;
lstBank.FullRowSelect = true;
//construct column
lstBank.Columns.Add("Bank", 250);
lstBank.Columns.Add("Description", 350);
loadBankList();
}
private void loadBankList()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankName, Description from Banks";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
lstBank.Items.Clear();
while (reader.Read())
{
string[] row = { reader["BankName"].ToString(), reader["Description"].ToString() };
ListViewItem item = new ListViewItem(row);
lstBank.Items.Add(item);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#region Bank Name Already Exist Procedure
private bool bankNameAlreadyExist()
{
int rowsCount=0;
SqlConnection conn = ConnectDB.GetConnection();
string bankName = txtName.Text;
bankName = bankName.Trim();
string strQuery = "Select count(*) from Banks where BankName='" + bankName + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
rowsCount = (int) cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
if (rowsCount > 0)
{
return true;
}
else
{
return false;
}
}
#endregion
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtName.Text != string.Empty)
{
if (bankNameAlreadyExist())
{
MessageBox.Show("Bank Name '" + txtName.Text + "' already exist");
}
else
{
addBankProc();
loadBankList();
}
}
else
{
MessageBox.Show("Bank Name is required to Add a Bank!", "Add Bank", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}//end of txtName.Text!=string.Empty
}
#region Add Bank Procedure
private void addBankProc()
{
string BankName = txtName.Text;
string Description = txtDescription.Text;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into Banks(BankName,Description)values(@BankName,@Description)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@BankName", SqlDbType.NVarChar, 50);
cmd.Parameters["@BankName"].Value = BankName;
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmd.Parameters["@Description"].Value = Description;
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Bank '" + BankName + "' has been successfully added", "Add Bank", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("An error occurred adding Bank", "Add Bank", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtName.Clear();
txtDescription.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}//end of addBankProc
#endregion
private void btnCancel_Click(object sender, EventArgs e)
{
txtName.Clear();
txtDescription.Clear();
loadBankList();
txtName.Focus();
}
}
}
<file_sep>/MainApp/MainApp/Loans/NewLoanBroughtForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class NewLoanBroughtForward : Form
{
string paths = PhotoPath.getPath();
private string memberID = string.Empty;
private string strInterestRate = string.Empty;
private string paymentStatus = string.Empty;
private string paymentFinished = string.Empty;
private string dateFinishedPayment = string.Empty;
private string userId;
public NewLoanBroughtForward(string UserID)
{
InitializeComponent();
this.userId = UserID;
}
private void NewLoanBroughtForward_Load(object sender, EventArgs e)
{
loadLoanCategoryIntoCombo();
}
private void loadLoanCategoryIntoCombo()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanCategoryID, Name from LoanCategory";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
DataRow row = dt.NewRow();
row["Name"] = "-- Select a Loan Category --";
dt.Rows.InsertAt(row, 0);
cboLoanCategory.DisplayMember = "Name";
cboLoanCategory.ValueMember = "LoanCategoryID";
cboLoanCategory.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cboLoanCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboLoanCategory.Text != "-- Select a Loan Category --")
{
//retrieve LoanType Based on the selected LoanCategory
#region retrieveLoanType
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID,LoanCategoryID,Type from LoanType where LoanCategoryID=" + (Convert.ToInt16(cboLoanCategory.SelectedValue));
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanType");
DataTable dt = ds.Tables["LoanType"];
DataRow row = dt.NewRow();
row["Type"] = "-- Select a Loan Type --";
dt.Rows.InsertAt(row, 0);
cboLoanType.DisplayMember = "Type";
cboLoanType.ValueMember = "LoanTypeID";
cboLoanType.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Loan Category");
}
finally
{
conn.Close();
}
#endregion
}
else
{
//cboType.Items.Clear();
}
}
private void txtFileNo_Leave(object sender, EventArgs e)
{
if (txtFileNo.Text != string.Empty)
{
#region retrieveMemberProfile
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID,Title,FileNo,FirstName,MiddleName,LastName,Photo from Members " +
"where FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
lblMemberProfile.Visible = true;
lblMemberProfile.Text = reader["Title"].ToString() + " " + reader["LastName"].ToString() + " " + reader["FirstName"].ToString() + " " + reader["MiddleName"].ToString().Substring(0) + ".";
memberID = reader["MemberID"].ToString();
if ( reader["Photo"].ToString()!=null && reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "//photos//profile_img.png");
}
}
}
else
{
MessageBox.Show("Sorry, no record with that File No. [" + txtFileNo.Text + "] exist.", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
picMember.Image = Image.FromFile(paths + "//photos//profile_img.png");
lblMemberProfile.Text = string.Empty;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion end of retrieveMemberProfile
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
lblMemberProfile.Text = string.Empty;
lblMemberProfile.Visible = false;
} //end of if (--Select a File No. --)
}
private void cboLoanType_Leave(object sender, EventArgs e)
{
if (cboLoanType.SelectedIndex > 0)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID, Duration, InterestRate from LoanType " +
"where LoanTypeID=" + cboLoanType.SelectedValue.ToString();
SqlCommand cmd = new SqlCommand(strQuery, conn);
//MessageBox.Show(cboLoanType.SelectedValue.ToString());
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string strDuration = reader["Duration"].ToString();
strInterestRate = reader["InterestRate"].ToString();
string strBoth = strDuration + " Months | " + strInterestRate + "%";
lblDuration.Text = strDuration;
lblInterestRate.Text = strInterestRate;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void txtAmount_Leave(object sender, EventArgs e)
{
if (txtAmount.Text != string.Empty && (CheckForNumber.isNumeric(txtAmount.Text)))
{
if (Convert.ToDecimal(txtAmount.Text) > 0)
{
txtAmountPaid.Enabled = true;
decimal loanAmount = Convert.ToDecimal(txtAmount.Text);
decimal interestRate = Convert.ToDecimal(strInterestRate);
int duration = Convert.ToInt16(lblDuration.Text);
decimal totalRepayment;
decimal monthlyRepayment;
decimal interestAmount = loanAmount * (interestRate / 100);
txtInterest.Text = CheckForNumber.formatCurrency2(interestAmount.ToString());
totalRepayment = loanAmount + interestAmount;
monthlyRepayment = totalRepayment / duration;
txtTotalRepayment.Text = CheckForNumber.formatCurrency2(totalRepayment.ToString());
txtAmount.Text = CheckForNumber.formatCurrency2(txtAmount.Text);
txtMonthlyRepayment.Text = CheckForNumber.formatCurrency2(monthlyRepayment.ToString());
}
else
{
txtAmountPaid.Text = string.Empty;
txtAmountPaid.Enabled = false;
MessageBox.Show("The Amount is required to proceed", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
txtAmountPaid.Text = string.Empty;
txtAmountPaid.Enabled = false;
}
}
private void btnPost_Click(object sender, EventArgs e)
{
if ((memberID != string.Empty) && (cboLoanCategory.SelectedIndex > 0) && (cboLoanType.SelectedIndex > 0) && (txtInterest.Text != string.Empty) && (txtAmount.Text != string.Empty) && (txtTotalRepayment.Text != string.Empty) && (txtMonthlyRepayment.Text != string.Empty) && (txtAmountPaid.Text != string.Empty) && (txtOutstandingAmt.Text != string.Empty))
{
if (txtOutstandingAmt.Text != string.Empty)
{
DialogResult res = MessageBox.Show("Do you wish to Post this Transaction?", "Loans", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
executePosting();
}
}
else
{
MessageBox.Show("Supply Outstanding Amount to Proceed.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("All Fields must be proper filled in to Execute Post","Loans",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
private void executePosting()
{
btnPost.Enabled = false;
string appMonth = dtAppDate.Value.Month.ToString();
string appYear = dtAppDate.Value.Year.ToString();
string rePay_StartMonth = dtStartRepayment.Value.Month.ToString();
string rePay_StartYear = dtStartRepayment.Value.Year.ToString();
string transactionID = "LBF" + DateTime.Now.ToString("ddMMyyhhmmss");
SqlConnection conn = ConnectDB.GetConnection();
conn.Open();
try
{
SqlTransaction sqlTrans = conn.BeginTransaction();
string strQuery = "Insert into LoanApplication(AppMonth,AppYear,MemberID,LoanCategoryID,"+
"LoanTypeID,LoanAmount,StartRepaymentMonth,StartRepaymentYear,LoanDuration,InterestRate,"+
"InterestAmount,TotalRepayment,MonthlyRepayment,ApprovalStatus,TransactionID)"+
"values(@AppMonth,@AppYear,@MemberID,@LoanCategoryID,@LoanTypeID,@LoanAmount,@StartRepaymentMonth,@StartRepaymentYear,"+
"@LoanDuration,@InterestRate,@InterestAmount,@TotalRepayment,@MonthlyRepayment,@ApprovalStatus,@TransactionID)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Transaction = sqlTrans;
#region Parameters
cmd.Parameters.Add("@AppMonth", SqlDbType.Int);
cmd.Parameters["@AppMonth"].Value = appMonth;
cmd.Parameters.Add("@AppYear", SqlDbType.Int);
cmd.Parameters["@AppYear"].Value = appYear;
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@LoanCategoryID", SqlDbType.Int);
cmd.Parameters["@LoanCategoryID"].Value = cboLoanCategory.SelectedValue.ToString();
cmd.Parameters.Add("@LoanTypeID", SqlDbType.Int);
cmd.Parameters["@LoanTypeID"].Value = cboLoanType.SelectedValue.ToString();
cmd.Parameters.Add("@LoanAmount", SqlDbType.Decimal);
cmd.Parameters["@LoanAmount"].Value = txtAmount.Text;
cmd.Parameters.Add("@StartRepaymentMonth", SqlDbType.Decimal);
cmd.Parameters["@StartRepaymentMonth"].Value = rePay_StartMonth;
cmd.Parameters.Add("@StartRepaymentYear", SqlDbType.Decimal);
cmd.Parameters["@StartRepaymentYear"].Value = rePay_StartYear;
cmd.Parameters.Add("@LoanDuration", SqlDbType.Int);
cmd.Parameters["@LoanDuration"].Value = lblDuration.Text;
cmd.Parameters.Add("@InterestRate", SqlDbType.Decimal);
cmd.Parameters["@InterestRate"].Value = lblInterestRate.Text;
cmd.Parameters.Add("@InterestAmount", SqlDbType.Decimal);
cmd.Parameters["@InterestAmount"].Value = txtInterest.Text;
cmd.Parameters.Add("@TotalRepayment", SqlDbType.Decimal);
cmd.Parameters["@TotalRepayment"].Value = txtTotalRepayment.Text;
cmd.Parameters.Add("@MonthlyRepayment", SqlDbType.Decimal);
cmd.Parameters["@MonthlyRepayment"].Value = txtMonthlyRepayment.Text;
cmd.Parameters.Add("@ApprovalStatus", SqlDbType.NVarChar, 3);
cmd.Parameters["@ApprovalStatus"].Value = "Yes";
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
string strQuery1;
if (dateFinishedPayment != string.Empty)
{
strQuery1 = "Insert into Loans(LoanApplicationID,RepaymentAmount,AmountPaid,OutstandingAmount," +
"PaymentStatus,PaymentFinished,DateFinishedPayment,TransactionID,Remark)values(@LoanApplicationID," +
"@RepaymentAmount,@AmountPaid,@OutstandingAmount,@PaymentStatus,@PaymentFinished,@DateFinishedPayment," +
"@TransactionID,@Remark)";
}
else
{
strQuery1 = "Insert into Loans(LoanApplicationID,RepaymentAmount,AmountPaid,OutstandingAmount," +
"PaymentStatus,PaymentFinished,TransactionID,Remark)values(@LoanApplicationID," +
"@RepaymentAmount,@AmountPaid,@OutstandingAmount,@PaymentStatus,@PaymentFinished," +
"@TransactionID,@Remark)";
}
string strQuery3 = "Select LoanApplicationID from LoanApplication where TransactionID='" + transactionID + "'";
int rowAffected = cmd.ExecuteNonQuery();
//MessageBox.Show(rowAffected.ToString());
if (rowAffected > 0)
{
cmd = new SqlCommand(strQuery3, conn);
cmd.Transaction = sqlTrans;
int loanApplicationID = Convert.ToInt16(cmd.ExecuteScalar());
//MessageBox.Show(loanApplicationID.ToString());
cmd = new SqlCommand(strQuery1, conn);
cmd.Transaction = sqlTrans;
#region parameters strQuery1
cmd.Parameters.Add("@LoanApplicationID", SqlDbType.Int);
cmd.Parameters["@LoanApplicationID"].Value = loanApplicationID;
cmd.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmd.Parameters["@RepaymentAmount"].Value = txtTotalRepayment.Text;
cmd.Parameters.Add("@AmountPaid", SqlDbType.Decimal);
cmd.Parameters["@AmountPaid"].Value = txtAmountPaid.Text;
cmd.Parameters.Add("@OutstandingAmount", SqlDbType.Decimal);
cmd.Parameters["@OutstandingAmount"].Value = txtOutstandingAmt.Text;
cmd.Parameters.Add("@PaymentStatus", SqlDbType.NVarChar, 10);
cmd.Parameters["@PaymentStatus"].Value = paymentStatus;
cmd.Parameters.Add("@PaymentFinished", SqlDbType.NVarChar, 3);
cmd.Parameters["@PaymentFinished"].Value = paymentFinished;
if (dateFinishedPayment != string.Empty)
{
cmd.Parameters.Add("@DateFinishedPayment", SqlDbType.NVarChar, 40);
cmd.Parameters["@DateFinishedPayment"].Value = dateFinishedPayment;
}
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmd.Parameters["@TransactionID"].Value = transactionID;
cmd.Parameters.Add("@Remark", SqlDbType.NVarChar, 1000);
cmd.Parameters["@Remark"].Value = txtRemark.Text;
#endregion
//Execute strQuery1
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
sqlTrans.Commit();
MessageBox.Show("Transaction has been successfully posted.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Information);
ActivityLog.logActivity(userId, "LoansForward", "Added a new Loans Brought Forward record with TransactionID of " + transactionID);
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred! Operation has been aborted.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Close existing form and reopen active form
NewLoanBroughtForward newLoanBroughtForward = new NewLoanBroughtForward(userId);
newLoanBroughtForward.MdiParent = this.ParentForm;
newLoanBroughtForward.Show();
this.Close();
}
else
{
MessageBox.Show("An error has occurred!","Loans",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtTotalRepayment_Leave(object sender, EventArgs e)
{
if (!FieldValidator.isBlank(txtTotalRepayment.Text))
{
txtTotalRepayment.Text = CheckForNumber.formatCurrency2(txtTotalRepayment.Text);
}
else
{
MessageBox.Show("Total Repayment Amount cannot be left blank.","Loans",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
private void txtAmountPaid_Leave(object sender, EventArgs e)
{
if (!FieldValidator.isBlank(txtAmountPaid.Text) && CheckForNumber.isNumeric(txtAmountPaid.Text))
{
decimal totalAmountRepayment = Convert.ToDecimal(txtTotalRepayment.Text);
decimal amountPaid = Convert.ToDecimal(txtAmountPaid.Text);
decimal outstandingAmount;
if (amountPaid > totalAmountRepayment)
{
MessageBox.Show("Sorry, that Amount Paid exceeds the Total Repayment Amount.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtAmountPaid.Text = string.Empty;
}
else
{
txtAmountPaid.Text = CheckForNumber.formatCurrency2(txtAmountPaid.Text);
outstandingAmount = totalAmountRepayment - amountPaid;
txtOutstandingAmt.Text = CheckForNumber.formatCurrency2(outstandingAmount.ToString());
//check outstanding amount and set paymentStatus
if (outstandingAmount == 0)
{
paymentStatus = "PAID";
paymentFinished = "Yes";
dateFinishedPayment = dtPickerPaymentFinished.Value.ToString();
lblPaymentFinishedDate.Visible = true;
dtPickerPaymentFinished.Visible = true;
}
else
{
paymentStatus = "Paying";
paymentFinished = "No";
dateFinishedPayment = string.Empty;
lblPaymentFinishedDate.Visible = false;
dtPickerPaymentFinished.Visible = false;
}
}
}
}
private void txtOutstandingAmt_Leave(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void cboLoanType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboLoanType.SelectedIndex > 0)
{
txtAmount.Enabled = true;
}
else
{
txtAmount.Text = string.Empty;
txtAmount.Enabled = false;
}
}
private void txtInterest_Leave(object sender, EventArgs e)
{
decimal totalRepayment;
decimal monthlyRepayment;
int duration = Convert.ToInt16(lblDuration.Text);
if (txtInterest.Text!=string.Empty && (CheckForNumber.isNumeric(txtInterest.Text)))
{
if (txtAmount.Text!=string.Empty && (CheckForNumber.isNumeric(txtAmount.Text)))
{
totalRepayment = Convert.ToDecimal(txtAmount.Text) + Convert.ToDecimal(txtInterest.Text);
monthlyRepayment = totalRepayment / duration;
txtTotalRepayment.Text = CheckForNumber.formatCurrency2(totalRepayment.ToString());
txtInterest.Text = CheckForNumber.formatCurrency2(txtInterest.Text);
txtMonthlyRepayment.Text = monthlyRepayment.ToString();
}
else
{
MessageBox.Show("Enter a valid Capital to proceed", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Invalid data entry","Loans",MessageBoxButtons.OK,MessageBoxIcon.Error);
txtInterest.Text = string.Empty;
}
}
}
}
<file_sep>/MainApp/MainApp/Savings/EditSavingsForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditSavingsForward : Form
{
int memberID;
string userId;
public EditSavingsForward(string UserID)
{
InitializeComponent();
userId = UserID;
lstVwSavingDetails.View = View.Details;
lstVwSavingDetails.FullRowSelect = true;
lstVwSavingDetails.Columns.Add("SavingsForwardID", 0);
lstVwSavingDetails.Columns.Add("SavingsTypeID", 0);
lstVwSavingDetails.Columns.Add("Savings Acct", 150);
lstVwSavingDetails.Columns.Add("Amount", 100);
lstVwSavingDetails.Columns.Add("Comment", 150);
lstVwSavingDetails.Columns[3].TextAlign = HorizontalAlignment.Right;
lblSavingsID.Text = string.Empty;
lblSavingsForwardID.Text = string.Empty;
}
private void btnFindMember_Click(object sender, EventArgs e)
{
lblSavingsForwardID.Text = string.Empty;
lblSavingsID.Text = string.Empty;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo, LastName + ' ' + FirstName + ' ' + MiddleName as FullName, Photo from Members " +
"where FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = Convert.ToInt16(reader["MemberID"].ToString());
lblMemberProfile.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
//display member photo
string paths = PhotoPath.getPath();
if (reader["Photo"].ToString() == string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
picMember.Visible = true;
lblMemberProfile.Visible = true;
grpBoxSavingsInfo.Enabled = true;
loadDataSetSavingsForward();
}
else
{
MessageBox.Show("Sorry, there is no Member with that File No.", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadDataSetSavingsForward()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.Month, sf.Year, sf.Amount, sf.TransactionID, sf.Date from Savings sf " +
"left join MonthByName m on sf.Month=m.MonthID " +
"where MemberID=" + memberID + " and sf.SavingSource='SavingsForward' order by savingsID desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dtGrdVwSavings.DataSource = null;
dtGrdVwSavings.Columns.Clear();
dtGrdVwSavings.Rows.Clear();
dtGrdVwSavings.Refresh();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdVwSavings.DataSource = dt;
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwSavings.Columns["Year"].Width = 60;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dtGrdVwSavings.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "View Details";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void dtGrdVwSavings_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string savingsAcct;
decimal savingsTotal = 0;
btnUpdate.Enabled = true;
//MessageBox.Show(e.ColumnIndex.ToString());
if (e.ColumnIndex == 5)
{
string transactionID = dtGrdVwSavings.Rows[e.RowIndex].Cells[3].Value.ToString();
grpBoxDetails.Text = "Savings Details [" + transactionID + "]";
lblSavingsID.Text = transactionID;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsForwardID, SavingsTypeID, Amount, Comment from SavingsForward where TransactionID='" + transactionID + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
lstVwSavingDetails.Items.Clear();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if ((reader["SavingsTypeID"].ToString()) == "99")
{
savingsAcct = "Shares Savings";
}
else
{
savingsAcct = getSavingsAcctName(reader["SavingsTypeID"].ToString());
}
string[] row = { reader["SavingsForwardID"].ToString(), reader["SavingsTypeID"].ToString(), savingsAcct, CheckForNumber.formatCurrency2(reader["Amount"].ToString()), reader["Comment"].ToString() };
ListViewItem item = new ListViewItem(row);
lstVwSavingDetails.Items.Add(item);
savingsTotal = savingsTotal + Convert.ToDecimal(reader["Amount"].ToString());
}
}
lblSavingsTotal.Text = CheckForNumber.formatCurrency2(savingsTotal.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private string getSavingsAcctName(string savingsTypeID)
{
SqlConnection conn2 = ConnectDB.GetConnection();
string strQuery = "Select SavingsName from SavingsType where SavingsTypeID=" + savingsTypeID;
SqlCommand cmd2 = new SqlCommand(strQuery, conn2);
conn2.Open();
SqlDataReader reader2 = cmd2.ExecuteReader();
reader2.Read();
string savingsTypeName = reader2["SavingsName"].ToString();
return savingsTypeName;
}
private void lstVwSavingDetails_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstVwSavingDetails.SelectedItems.Count > 0)
{
//MessageBox.Show(lstVwSavingDetails.SelectedItems[0].SubItems[3].Text.ToString());
string savingsTypeID = lstVwSavingDetails.SelectedItems[0].SubItems[1].Text.ToString();
cboSavingsType.SelectedValue = Convert.ToInt16(savingsTypeID);
txtComment.Text = lstVwSavingDetails.SelectedItems[0].SubItems[4].Text.ToString();
txtAmount.Text = lstVwSavingDetails.SelectedItems[0].SubItems[3].Text.ToString();
lblSavingsForwardID.Text = lstVwSavingDetails.SelectedItems[0].SubItems[0].Text.ToString();
btnChange.Enabled = true;
}
else
{
cboSavingsType.SelectedIndex = 0;
txtAmount.Text = string.Empty;
txtComment.Text = string.Empty;
btnChange.Enabled = false;
}
}
private void EditSavingsForward_Load(object sender, EventArgs e)
{
loadSavingsType();
}
private void loadSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsTypeID, SavingsName from SavingsType";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds,"SavingsType");
DataTable dt = ds.Tables["SavingsType"];
cboSavingsType.DisplayMember = "SavingsName";
cboSavingsType.ValueMember = "SavingsTypeID";
cboSavingsType.DataSource = dt;
DataRow row = dt.NewRow();
row["SavingsName"] = "Shares Savings";
row["SavingsTypeID"] = 99;
dt.Rows.InsertAt(row, 0);
row = dt.NewRow();
row["SavingsName"] = "";
row["SavingsTypeID"] = 0;
dt.Rows.InsertAt(row, 0);
cboSavingsType.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnChange_Click(object sender, EventArgs e)
{
if (lstVwSavingDetails.SelectedItems.Count > 0)
{
lstVwSavingDetails.SelectedItems[0].SubItems[1].Text = cboSavingsType.SelectedValue.ToString();
lstVwSavingDetails.SelectedItems[0].SubItems[2].Text = cboSavingsType.Text;
lstVwSavingDetails.SelectedItems[0].SubItems[3].Text = txtAmount.Text;
lstVwSavingDetails.SelectedItems[0].SubItems[4].Text = txtComment.Text;
calculateSavingsTotal();
}
else
{
MessageBox.Show("Select a Savings Account Type to maake an Update", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void calculateSavingsTotal()
{
decimal savingsTotal = 0;
if (lstVwSavingDetails.Items.Count > 0)
{
for (int i = 0; i < lstVwSavingDetails.Items.Count; i++)
{
//MessageBox.Show(lstVwSavingDetails.Items[i].SubItems[2].Text.ToString());
savingsTotal = savingsTotal + Convert.ToDecimal(lstVwSavingDetails.Items[i].SubItems[3].Text.ToString());
}
lblSavingsTotal.Text = CheckForNumber.formatCurrency2(savingsTotal.ToString());
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lblSavingsID.Text != string.Empty)
{
DialogResult res = MessageBox.Show("Do you wish to Update this record?", "Savings", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
UpdateSavings();
}
}
else
{
MessageBox.Show("No record has been selected to effect an Update.","Savings",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
private void UpdateSavings()
{
int rowAffected = 0;
bool errorflag = false;
int savingsTypeID = 0;
int savingsForwardID = 0;
string temp = string.Empty;
decimal amount = 0;
string comment = string.Empty;
string strQuery = string.Empty;
SqlConnection conn = ConnectDB.GetConnection();
strQuery = "Update Savings set Amount=@Amount where TransactionID=@TransactionID";
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = Convert.ToDecimal(lblSavingsTotal.Text);
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 100);
cmd.Parameters["@TransactionID"].Value = lblSavingsID.Text;
cmd.Transaction = sqlTrans;
try
{
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
for (int i = 0; i < lstVwSavingDetails.Items.Count; i++)
{
strQuery = "Update SavingsForward set SavingsTypeID=@SavingsTypeID,Amount=@Amount,Comment=@Comment where SavingsForwardID=@SavingsForwardID" +
" and TransactionID=@TransactionID";
cmd.CommandText = strQuery;
#region cmd parameters
savingsForwardID = Convert.ToInt16(lstVwSavingDetails.Items[i].SubItems[0].Text.ToString());
savingsTypeID = Convert.ToInt16(lstVwSavingDetails.Items[i].SubItems[1].Text.ToString());
temp = lstVwSavingDetails.Items[i].SubItems[3].Text.ToString();
amount = Convert.ToDecimal(temp);
comment = lstVwSavingDetails.Items[i].SubItems[4].Text.ToString();
cmd.Parameters.Clear();
//MessageBox.Show("Savings TypeID - " + savingsTypeID.ToString() + " - " + amount.ToString());
cmd.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmd.Parameters["@SavingsTypeID"].Value = savingsTypeID;
cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = amount;
cmd.Parameters.Add("@Comment", SqlDbType.NVarChar, 400);
cmd.Parameters["@Comment"].Value = comment;
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 400);
cmd.Parameters["@TransactionID"].Value = lblSavingsID.Text;
cmd.Parameters.Add("@SavingsForwardID", SqlDbType.Int);
cmd.Parameters["@SavingsForwardID"].Value = savingsForwardID;
#endregion
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected == 0)
{
errorflag = true;
}
}
}
else
{
errorflag = true;
}
//check if there was no error and commit, if there is error rollback
if (errorflag == false)
{
sqlTrans.Commit();
ActivityLog.logActivity(userId, "SavingsForward", "Update Savings Record " + lblSavingsID.Text);
MessageBox.Show("Savings has been successfully Updated", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error occurred! Update has been cancelled.", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//reset view
loadDataSetSavingsForward();
lstVwSavingDetails.Items.Clear();
cboSavingsType.SelectedIndex = 0;
txtAmount.Text = string.Empty;
txtComment.Text = string.Empty;
lblSavingsTotal.Text = "0.00";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Deductions/PostDeductions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class PostDeductions : Form
{
int memberID;
decimal totalSavings;
decimal monthlyLoanRepayment;
int numOfRows;
int errorflag = 0;
string repaymentLoanType;
bool servicingLoan = false;
bool loanMoreThanSavings = false;
string userId;
public PostDeductions(string UserID)
{
InitializeComponent();
userId = UserID;
//LstDeduction Properties
lstDeductions.View = View.Details;
lstDeductions.FullRowSelect = true;
//LstDeductions Columns
lstDeductions.Columns.Add("SN", 60);
lstDeductions.Columns.Add("MemberID", 0);
lstDeductions.Columns.Add("File No", 80);
lstDeductions.Columns.Add("Name", 200);
lstDeductions.Columns.Add("Savings", 150);
lstDeductions.Columns.Add("Loans", 150);
lstDeductions.Columns.Add("Total", 200);
lstDeductions.Columns.Add("Action", 100);
//LstDeductions Alignment
lstDeductions.Columns[4].TextAlign = HorizontalAlignment.Right;
lstDeductions.Columns[5].TextAlign = HorizontalAlignment.Right;
lstDeductions.Columns[6].TextAlign = HorizontalAlignment.Right;
//lstViewDeductionList
lstVwDeductionList.View = View.Details;
lstVwDeductionList.FullRowSelect = true;
lstVwDeductionList.Columns.Add("Month",75);
lstVwDeductionList.Columns.Add("Year",40);
//populate cboMonth and cboYear
populateCboMonth();
populateCboYear();
//get previous deduction dates
getPreviousDeductionDate();
getDeductionList();
}
private void populateCboMonth()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MonthID,Month from MonthByName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "MonthByName");
DataTable dt = ds.Tables["MonthByName"];
cboMonth.DataSource = dt;
cboMonth.DisplayMember = "Month";
cboMonth.ValueMember = "MonthID";
/*
DataRow row = dt.NewRow();
row["Month"] = "Select Month";
dt.Rows.InsertAt(row, 0);
* */
cboMonth.DataSource = dt;
DateTime dtTime = DateTime.Now;
int thisMonth = dtTime.Month;
cboMonth.SelectedValue = thisMonth;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void populateCboYear()
{
DateTime myDate = DateTime.Now;
int thisYear = myDate.Year;
int startYear = 1990;
int countforward = 40;
int loop = 0;
while (loop <= countforward)
{
cboYear.Items.Add(startYear++);
loop++;
}
cboYear.SelectedItem = thisYear;
}
private void PostDeductions_Load(object sender, EventArgs e)
{
decimal loanMonthlyRepayment;
int memberID;
int counter;
decimal totalDeduction;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as Name, " +
"SUM(s.Amount) as Amount from Members m inner join MemberSavingsTypeAcct s on m.MemberID=s.MemberID group by m.MemberID,m.FileNo,m.Title,m.FirstName,m.LastName,m.MiddleName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
counter = 0;
while (reader.Read())
{
counter++;
memberID = Convert.ToInt32(reader["MemberID"].ToString());
//Total Monthly Savings
totalSavings = Convert.ToDecimal(reader["Amount"]);
//check for loan records
loanMonthlyRepayment = getMonthlyLoan(memberID);
//calculate monthly total deduction using the total savings plus monthly loan repayment
totalDeduction = loanMonthlyRepayment + totalSavings;
//add data to the lstDeductions
String[] row = {counter.ToString(),reader["MemberID"].ToString(), reader["FileNo"].ToString(),
reader["Name"].ToString(),CheckForNumber.formatCurrency2(totalSavings.ToString()),
CheckForNumber.formatCurrency2(loanMonthlyRepayment.ToString()), CheckForNumber.formatCurrency(totalDeduction.ToString())};
ListViewItem item = new ListViewItem(row);
lstDeductions.Items.Add(item);
}
reader.Close();
lblRecordNo.Text = "No. of Records: " + counter.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Post Deductions: - " + ex.Message);
}
finally
{
conn.Close();
}
}
private decimal getMonthlyLoan(int memberID)
{
decimal monthlyRepayment = 0;
SqlConnection conn2 = ConnectDB.GetConnection();
string strQuery = "Select a.MonthlyRepayment, l.OutstandingAmount, t.Type as LoanType from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID = l.LoanApplicationID " +
"inner join LoanType t on a.LoanTypeID=t.LoanTypeID where a.MemberID=@MemberID and l.OutstandingAmount<>0";
SqlCommand cmdLoan = new SqlCommand(strQuery, conn2);
cmdLoan.Parameters.Add("@MemberID", SqlDbType.Int);
cmdLoan.Parameters["@MemberID"].Value = memberID;
try
{
conn2.Open();
SqlDataReader loanReader = cmdLoan.ExecuteReader();
int recFound = loanReader.Cast<object>().Count();
//MessageBox.Show(recFound.ToString());
loanReader.Close();
SqlDataReader readerGetLoanInfo = cmdLoan.ExecuteReader(CommandBehavior.SingleRow);
if (readerGetLoanInfo.HasRows)
{
if (readerGetLoanInfo.Read())
{
monthlyRepayment = Convert.ToDecimal(readerGetLoanInfo["MonthlyRepayment"]);
repaymentLoanType = readerGetLoanInfo["LoanType"].ToString();
servicingLoan = true;
//MessageBox.Show("Monthly Loan Repayment: " + readerGetLoanInfo["MonthlyRepayment"].ToString() +
// "\nLoan Type: " + repaymentLoanType);
//Check if monthlyRepayment is greater than Monthly savings, if it is deposit (zero - nothing)
//in members savings, otherwise deposit balance from loan into savings
if (monthlyRepayment >= totalSavings)
{
totalSavings = 0;
loanMoreThanSavings = true;
}
else
{
totalSavings = totalSavings - monthlyRepayment;
}
}
}
readerGetLoanInfo.Close();
}
catch (Exception ex)
{
MessageBox.Show("getLoanTotal: - " + ex.Message);
}
finally
{
conn2.Close();
}
return monthlyRepayment;
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void lstDeductions_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstDeductions.SelectedItems.Count != 0)
{
string memberID = lstDeductions.SelectedItems[0].SubItems[1].Text;
getSavingsInfo(memberID);
getLoansInfo(memberID);
}
}
//get selected listview member savings
private void getSavingsInfo(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string sqlQuery = "Select Remark as [Savings Type],Amount as Total from MemberSavingsTypeAcct where MemberID=@MemberID";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.Add("@MemberID", SqlDbType.NVarChar, 20);
cmd.Parameters["@MemberID"].Value = memberID;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
datGrdSavings.DataSource = null;
datGrdSavings.DataSource = dt;
datGrdSavings.Columns["Total"].DefaultCellStyle.Format = "N2";
datGrdSavings.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
//get loans of selected listview
private void getLoansInfo(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string sqlQuery = "Select a.MonthlyRepayment,l.RepaymentAmount,l.AmountPaid,l.OutstandingAmount from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID = l.LoanApplicationID where a.MemberID=@MemberID and l.OutstandingAmount<>0";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.Add("@MemberID", SqlDbType.NVarChar, 20);
cmd.Parameters["@MemberID"].Value = memberID;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
datGrdLoans.DataSource = null;
datGrdLoans.DataSource = dt;
datGrdLoans.Columns["MonthlyRepayment"].HeaderText = "Monthly Repayment";
datGrdLoans.Columns["RepaymentAmount"].HeaderText = "Repayment Amount";
datGrdLoans.Columns["AmountPaid"].HeaderText = "Amount Paid";
datGrdLoans.Columns["OutstandingAmount"].HeaderText = "Outstanding Amount";
datGrdLoans.Columns["MonthlyRepayment"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["RepaymentAmount"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["AmountPaid"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["OutstandingAmount"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["MonthlyRepayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdLoans.Columns["RepaymentAmount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdLoans.Columns["AmountPaid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdLoans.Columns["OutstandingAmount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnPostDeduction_Click(object sender, EventArgs e)
{
int selMonth = (int)cboMonth.SelectedValue;
int selYear = Convert.ToInt16(cboYear.Text);
bool isAlreadyPosted = checkIfAlreadyPosted(selMonth, selYear);
if (isAlreadyPosted == false)
{
DialogResult res = MessageBox.Show("Do you want to execute posting for the selected Month and Year? " +
"Please be sure about this because this process is not reversible", "Deduction Info", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
executeDeduction();
}
}
else
{
MessageBox.Show("Posting for " + cboMonth.Text + " " + cboYear.Text + " has already been executed", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//MessageBox.Show(lstDeductions.Items.Count.ToString());
}
//check if that posting had been done for that month and year
private bool checkIfAlreadyPosted(int month, int year)
{
int recFound = 0;
bool result;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "select count(*) from DeductionDates where Month=@Month and Year=@Year";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Month", SqlDbType.Int);
cmd.Parameters["@Month"].Value = month;
cmd.Parameters.Add("@Year", SqlDbType.Int);
cmd.Parameters["@Year"].Value = year;
try
{
conn.Open();
recFound = (int)cmd.ExecuteScalar();
//MessageBox.Show(recFound.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
if (recFound == 0) { result = false; } else { result = true; }
return result;
}
private void executeDeduction()
{
int numOfRecords = lstDeductions.Items.Count;
int currentRecord;
SqlConnection conn = ConnectDB.GetConnection();
SqlTransaction sqlTrans = null;
SqlCommand cmd;
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
cmd = conn.CreateCommand();
cmd.Transaction = sqlTrans;
int selectedMonth = Convert.ToInt16(cboMonth.SelectedValue);
int selectedYear = Convert.ToInt16(cboYear.Text);
#region loop through records
//loop through records
for (currentRecord = 0; currentRecord < numOfRecords; currentRecord++)
{
cmd.Parameters.Clear();
memberID = Convert.ToInt16(lstDeductions.Items[currentRecord].SubItems[1].Text);
decimal monthlyLoanRepayment = Convert.ToDecimal(lstDeductions.Items[currentRecord].SubItems[5].Text);
decimal lstAllSavingsDeduction = Convert.ToDecimal(lstDeductions.Items[currentRecord].SubItems[4].Text);
decimal lstAllLoansDeduction = Convert.ToDecimal(lstDeductions.Items[currentRecord].SubItems[5].Text);
decimal lstTotalDeductions = Convert.ToDecimal(lstDeductions.Items[currentRecord].SubItems[6].Text);
totalSavings = Convert.ToDecimal(lstDeductions.Items[currentRecord].SubItems[4].Text);
string transactionID = "DED" + DateTime.Now.ToString("ddMMyyhhmmss");
Deduction newPosting = new Deduction();
string postSavingsStatus = newPosting.postSavings(conn, cmd, sqlTrans, memberID, transactionID, totalSavings, numOfRows, errorflag, selectedMonth, selectedYear);
//MessageBox.Show("Post Savings Status: " + postSavingsStatus);
string postLoansStatus = newPosting.postLoans(conn, cmd, sqlTrans, memberID, transactionID, currentRecord, selectedMonth, selectedYear, numOfRows, errorflag, monthlyLoanRepayment);
//MessageBox.Show("PostLoan Status: " + postLoansStatus);
string recordDeductionStatus = newPosting.recordDeduction(cmd, memberID, transactionID, currentRecord, selectedMonth, selectedYear, lstAllSavingsDeduction, lstAllLoansDeduction, lstTotalDeductions, numOfRows, errorflag);
//MessageBox.Show("Record Deductions status: " + recordDeductionStatus);
string recordDeductionDetailsStatus = newPosting.recordDeductionDetails(cmd, memberID, transactionID, currentRecord, numOfRows, errorflag, lstAllSavingsDeduction, lstAllLoansDeduction, repaymentLoanType, servicingLoan, loanMoreThanSavings);
//MessageBox.Show("Record Deduction Detail Status: " + recordDeductionDetailsStatus);
if (errorflag == 0)
{
//MessageBox.Show("Posted");
//lstDeductions.Items[currentRecord].SubItems[7].Text = "Posted";
}
}
//end of for loop
#endregion end of loop
if (errorflag == 0)
{
Deduction newDeductionPosting = new Deduction();
string deductionDateRecord = newDeductionPosting.recordDeductionDate(selectedMonth,selectedYear);
if (deductionDateRecord == "1")
{
sqlTrans.Commit();
MessageBox.Show("Transaction has been Successfully Posted");
getDeductionList();
ActivityLog.logActivity(userId, "Post Deduction - Collective", "Deduction Posting for Month:" + selectedMonth + " " + selectedYear);
}
else
{
sqlTrans.Rollback();
MessageBox.Show("Posting Transaction Failed");
}
}
else
{
sqlTrans.Rollback();
MessageBox.Show("Posting Transaction Failed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}//end of executeDeduction
private void txtAddFileNo_TextChanged(object sender, EventArgs e)
{
if (txtAddFileNo.Text.Length == 0)
{
btnAddDeduction.Enabled = false;
}
else
{
btnAddDeduction.Enabled = true;
}
}
private void btnRemoveDeductions_Click(object sender, EventArgs e)
{
if (lstDeductions.SelectedItems.Count > 0)
{
DialogResult res = MessageBox.Show("Do you really wish to remove the selected record?", "Deduction Info", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
lstDeductions.Items.RemoveAt(lstDeductions.SelectedIndices[0]);
datGrdSavings.DataSource = null;
datGrdLoans.DataSource = null;
}
}
else
{
MessageBox.Show("No record has been selected to be removed from the List.\nPlease select a record to remove from the List", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAddDeduction_Click(object sender, EventArgs e)
{
//check if the fileno is genuine and is not already in the list
//get number of all records
int numOfRecords = lstDeductions.Items.Count - 1;
bool alreadyInList = false;
bool memberExist = false;
string addFileNoDeduction;
decimal monthlyLoanRepayment;
decimal totalDeduction;
int memberID = 0;
string lastRecId;
int nextRecId;
SqlConnection conn = null;
SqlCommand cmd = null;
conn = ConnectDB.GetConnection();
cmd = conn.CreateCommand();
conn.Open();
addFileNoDeduction = txtAddFileNo.Text.Trim().ToUpper();
#region check if member is genuine and exist
string strQuery = "Select MemberID,FileNo from Members where FileNo='" + addFileNoDeduction + "'";
cmd.CommandText = strQuery;
try
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = Convert.ToInt16(reader["MemberID"]);
memberExist = true;
reader.Close();
}
else
{
memberExist = false;
MessageBox.Show("Sorry, No member with that File No", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
#region Check if the FileNo is already in the List if it is a genuine member FileNo
if (memberExist)
{
for (int i = 0; i < numOfRecords; i++)
{
if (addFileNoDeduction == lstDeductions.Items[i].SubItems[2].Text.ToString().ToUpper())
{
alreadyInList = true;
DialogResult res = MessageBox.Show("That Record is Already in the List", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
}
}
#endregion
#region get loan amount for the entered member if it does not exist in the list
if ((memberExist == true) && (alreadyInList == false))
{
//Get member's Savings using memberID
strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as Name, " +
"SUM(s.Amount) as Amount from Members m inner join MemberSavingsTypeAcct s on m.MemberID=s.MemberID where m.MemberID=" + memberID + " group by m.MemberID,m.FileNo,m.Title,m.FirstName,m.LastName,m.MiddleName";
cmd.CommandText = strQuery;
try
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//get the serial id of the last record
lastRecId = lstDeductions.Items[numOfRecords].SubItems[0].Text;
//Add 1 to the last record Id to get the next record id
nextRecId = (Int16.Parse(lastRecId)) + 1;
//check for loan records
monthlyLoanRepayment = getMonthlyLoan(memberID);
//calculate monthly total deduction using the total savings plus monthly loan repayment
totalDeduction = monthlyLoanRepayment + Convert.ToDecimal(reader["Amount"]);
//add data to the lstDeductions
String[] row = {nextRecId.ToString(),reader["MemberID"].ToString(), reader["FileNo"].ToString(),
reader["Name"].ToString(),CheckForNumber.formatCurrency(reader["Amount"].ToString()),
CheckForNumber.formatCurrency2(monthlyLoanRepayment.ToString()), CheckForNumber.formatCurrency(totalDeduction.ToString())};
ListViewItem item = new ListViewItem(row);
lstDeductions.Items.Add(item);
txtAddFileNo.Text = string.Empty;
btnAddDeduction.Enabled = false;
}
reader.Close();
lblRecordNo.Text = "No. of Records: " + lstDeductions.Items.Count.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Last Phase: " + ex.Message);
}
}
#endregion end of if statement
}
private void getPreviousDeductionDate()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionID, m.Month + ' ' + d.Year as DeductionMonthYear, d.DatePosted from Deductions d left join MonthByName m" +
" on d.Month=m.MonthID order by DeductionID desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (reader.HasRows)
{
reader.Read();
lblPreviousPosting.Text = "Previous Deductions: " + reader["DeductionMonthYear"].ToString() + Environment.NewLine + "Posted " + reader["DatePosted"].ToString();
}
else
{
lblPreviousPosting.Text = "No Previous Deductions";
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getDeductionList()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.Month, d.Year from DeductionDates d left join MonthByName m " +
"on m.MonthID=d.Month order by DeductionDateID";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
lstVwDeductionList.Items.Clear();
while(reader.Read())
{
String[] row = {reader["Month"].ToString(), reader["Year"].ToString()};
ListViewItem item = new ListViewItem(row);
lstVwDeductionList.Items.Add(item);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnViewSelectedDeduction_Click(object sender, EventArgs e)
{
string month = string.Empty;
string year = string.Empty;
if (lstVwDeductionList.SelectedItems.Count > 0)
{
month = lstVwDeductionList.SelectedItems[0].SubItems[0].Text.ToString();
year = lstVwDeductionList.SelectedItems[0].SubItems[1].Text.ToString();
#region Date Resolution
switch (month)
{
case "January":
month = "1";
break;
case "Febraury":
month = "2";
break;
case "March":
month = "3";
break;
case "April":
month = "4";
break;
case "May":
month = "5";
break;
case "June":
month = "6";
break;
case "July":
month = "7";
break;
case "August":
month = "8";
break;
case "September":
month = "9";
break;
case "October":
month = "10";
break;
case "November":
month = "11";
break;
case "December":
month = "12";
break;
}
#endregion
ViewDeductions viewDeductions = new ViewDeductions(month,year);
viewDeductions.MdiParent = this.ParentForm;
viewDeductions.Show();
}
else
{
MessageBox.Show("Select a date item to view details.", "Deduction Dates", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnExport_Click(object sender, EventArgs e)
{
ExportData exportSavingsDetails = new ExportData();
//exportSavingsDetails.ExportToExcel(lstDeductions, saveFD);
}
}
}
<file_sep>/MainApp/MainApp/Classes/DateFunction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MainApp
{
public static class DateFunction
{
public static string getMonthByName(int monthInNumber)
{
string monthName = string.Empty;
switch (monthInNumber)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
}
return monthName;
}
public static int getMonthByDate(string monthInName)
{
int monthInNumber = 0;
switch (monthInName)
{
case "January":
monthInNumber = 1;
break;
case "February":
monthInNumber = 2;
break;
case "March":
monthInNumber = 3;
break;
case "April":
monthInNumber = 4;
break;
case "May":
monthInNumber = 5;
break;
case "June":
monthInNumber = 6;
break;
case "July":
monthInNumber = 7;
break;
case "August":
monthInNumber = 8;
break;
case "September":
monthInNumber = 9;
break;
case "October":
monthInNumber = 10;
break;
case "November":
monthInNumber = 11;
break;
case "December":
monthInNumber = 12;
break;
}
return monthInNumber;
}
}
}
<file_sep>/MainApp/MainApp/Loans/ViewLoanDetails.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewLoanDetails : Form
{
private string loanApplicationID;
private string loanID;
public ViewLoanDetails(string loanAppID)
{
InitializeComponent();
this.loanApplicationID = loanAppID;
loanID = string.Empty;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void ViewLoanDetails_Load(object sender, EventArgs e)
{
loadLoan();
loadLoanRepayment();
}
private void loadLoan()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoansID, LoanApplicationID,RepaymentAmount 'Repayment Amount.',AmountPaid 'Amount Paid',OutstandingAmount 'Outstanding Amt.',PaymentStatus 'Payment Status', " +
"PaymentFinished 'Payment Finished',DateFinishedPayment 'Finished Payment',TransactionID 'Trans. ID',Remark,DateCreated 'Date Created' from Loans where LoanApplicationID='" + loanApplicationID + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
dtGrdVwLoans.DataSource = dt;
dtGrdVwLoans.Columns["LoansID"].Visible = false;
dtGrdVwLoans.Columns["LoanApplicationID"].Visible = false;
dtGrdVwLoans.Columns["Repayment Amount."].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Amount Paid"].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Amount Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Finished Payment"].DefaultCellStyle.Format = "D";
dtGrdVwLoans.Columns["Date Created"].DefaultCellStyle.Format = "D";
if (dtGrdVwLoans.Rows.Count > 0)
{
loanID = dtGrdVwLoans.Rows[0].Cells[0].Value.ToString();
//MessageBox.Show(loanID);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadLoanRepayment()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select l.LoanRepaymentID,m.FileNo,m.LastName 'Last Name',m.FirstName 'First Name',m.MiddleName 'Middle Name',l.RepaymentAmount 'Repayment Amt.', " +
"l.PaidAmount 'Paid Amt',l.Outstanding 'Outstanding Amt.',l.PaidCumulative 'Paid Cumulative',l.Excess, " +
"l.Remark,l.RepayTransactID,l.DatePosted 'Date Posted' from LoanRepayment l " +
"left join Members m on l.MemberID=m.MemberID " +
"where l.LoanID=" + loanID + " " +
"order by l.LoanRepaymentID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanRepayment");
DataTable dt = ds.Tables["LoanRepayment"];
dtGrdVwRepayment.DataSource = dt;
dtGrdVwRepayment.Columns["LoanRepaymentID"].Visible = false;
dtGrdVwRepayment.Columns["FileNo"].Width = 80;
dtGrdVwRepayment.Columns["Repayment Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwRepayment.Columns["Repayment Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwRepayment.Columns["Paid Amt"].DefaultCellStyle.Format = "N2";
dtGrdVwRepayment.Columns["Paid Amt"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwRepayment.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwRepayment.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwRepayment.Columns["Paid Cumulative"].DefaultCellStyle.Format = "N2";
dtGrdVwRepayment.Columns["Paid Cumulative"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwRepayment.Columns["Excess"].DefaultCellStyle.Format = "N2";
dtGrdVwRepayment.Columns["Excess"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
lblRecNo.Text = "No.of Records: " + dt.Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Classes/Cl_UnpostDeductions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Data.SqlClient;
namespace MainApp
{
class Cl_UnpostDeductions
{
public string unpostSavingsDeductions(SqlConnection conn, SqlCommand cmd, List<string> selDeductionTransactionDel)
{
int statusFlag = 0;
foreach (string child in selDeductionTransactionDel)
{
cmd.CommandText = "Delete from Savings where SavingSource='Deduction' AND TransactionID='" + child + "'";
statusFlag = cmd.ExecuteNonQuery();
}
return statusFlag.ToString();
}
public string unpostSavingsDeductions(SqlConnection conn, SqlCommand cmd, int memberID, string selDedTransactionId)
{
int statusFlag = 0;
cmd.CommandText = "Delete from Savings where SavingSource='Deduction' AND MemberID=" + memberID + " AND TransactionID='" + selDedTransactionId + "'";
statusFlag = cmd.ExecuteNonQuery();
return statusFlag.ToString();
}
public string unpostLoansDeduction(SqlConnection conn, SqlCommand cmd, List<string> selDeductionTransactionDel)
{
int statusFlag = 0;
foreach (string child in selDeductionTransactionDel)
{
cmd.CommandText = "Delete from LoanRepayment where RepayTransactID='" + child + "'";
statusFlag = cmd.ExecuteNonQuery();
}
return statusFlag.ToString();
}
public string unpostLoansDeduction(SqlConnection conn, SqlCommand cmd, int memberID, string selDedTransactionId)
{
int statusFlag = 0;
cmd.CommandText = "Delete from LoanRepayment where RepayTransactID='" + selDedTransactionId + "' AND MemberID=" + memberID;
statusFlag = cmd.ExecuteNonQuery();
return statusFlag.ToString();
}
public string unpostDeductions(SqlConnection conn, SqlCommand cmd, List<string> selDeductionTransactionDel, string selDelMonth, int selDelYear)
{
int statusFlag = 0;
//int monthInNum = ConvertMonthToNum(selDelMonth);
foreach (string child in selDeductionTransactionDel)
{
cmd.CommandText = "Delete from Deductions where TransactionID='" + child + "'";
statusFlag = cmd.ExecuteNonQuery();
}
return statusFlag.ToString();
}
public string unpostDeductions(SqlConnection conn, SqlCommand cmd, int memberID, string selDedTransactionId, string selDelMonth, int selDelYear)
{
int statusFlag = 0;
int monthInNum = ConvertMonthToNum(selDelMonth);
cmd.CommandText = "Delete from Deductions where TransactionID='" + selDedTransactionId + "' AND MemberID=" + memberID +
" AND Month=" + monthInNum + " AND Year=" + selDelYear;
statusFlag = cmd.ExecuteNonQuery();
return statusFlag.ToString();
}
private int ConvertMonthToNum(string selDelMonth)
{
int monthInNum = 0;
//Convert Month to Number
switch (selDelMonth)
{
case "January":
monthInNum = 1;
break;
case "February":
monthInNum = 2;
break;
case "March":
monthInNum = 3;
break;
case "April":
monthInNum = 4;
break;
case "May":
monthInNum = 5;
break;
case "June":
monthInNum = 6;
break;
case "July":
monthInNum = 7;
break;
case "August":
monthInNum = 8;
break;
case "September":
monthInNum = 9;
break;
case "October":
monthInNum = 10;
break;
case "November":
monthInNum = 11;
break;
case "December":
monthInNum = 12;
break;
}
return monthInNum;
}
public string unpostDeductionDetails(SqlConnection conn, SqlCommand cmd, List<string> selDeductionTransactionDel)
{
int statusFlag = 0;
foreach (string child in selDeductionTransactionDel)
{
cmd.CommandText = "Delete from DeductionDetails where TransactionID='" + child + "'";
statusFlag = cmd.ExecuteNonQuery();
}
return statusFlag.ToString();
}
public string unpostDeductionDetails(SqlConnection conn, SqlCommand cmd, int memberID, string selDedTransactionId)
{
int statusFlag = 0;
cmd.CommandText = "Delete from DeductionDetails where TransactionID='" + selDedTransactionId + "'";
statusFlag = cmd.ExecuteNonQuery();
return statusFlag.ToString();
}
public string unpostDeductionDates(SqlConnection conn, SqlCommand cmd, string selDelMonth, int selDelYear)
{
int statusFlag = 0;
switch (selDelMonth)
{
case "January":
selDelMonth = "1";
break;
case "February":
selDelMonth = "2";
break;
case "March":
selDelMonth = "3";
break;
case "April":
selDelMonth = "4";
break;
case "May":
selDelMonth = "5";
break;
case "June":
selDelMonth = "6";
break;
case "July":
selDelMonth = "7";
break;
case "August":
selDelMonth = "8";
break;
case "September":
selDelMonth = "9";
break;
case "October":
selDelMonth = "10";
break;
case "November":
selDelMonth = "11";
break;
case "December":
selDelMonth = "12";
break;
}
cmd.CommandText = "Delete from DeductionDates where Month='" + selDelMonth + "' and Year='" + selDelYear + "'";
statusFlag = cmd.ExecuteNonQuery();
return statusFlag.ToString();
}
}
}
<file_sep>/MainApp/MainApp/Classes/ActivityLog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace MainApp
{
class ActivityLog
{
public static void logActivity(string UserID, string ActivityType, string Description)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into ActivityLog(UserID,ActivityType,Description)" +
"Values(@UserID,@ActivityType,@Description)";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
#region cmd parameters
cmd.Parameters.Add("@UserID", SqlDbType.Int);
cmd.Parameters["@UserID"].Value = Convert.ToInt16(UserID);
cmd.Parameters.Add("@ActivityType", SqlDbType.NVarChar, 50);
cmd.Parameters["@ActivityType"].Value = ActivityType.ToString();
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 600);
cmd.Parameters["@Description"].Value = Description.ToString();
#endregion
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/ReportForms/FrmGenerateMemberProfileByFileNo.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class FrmGenerateMemberProfileByFileNo : Form
{
public FrmGenerateMemberProfileByFileNo()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
//Check if the member exist
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select count(*) from Members where FileNo=@FileNo";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
cmd.Parameters.Add("@FileNo", SqlDbType.NVarChar, 50);
cmd.Parameters["@FileNo"].Value = txtFileNo.Text;
try
{
conn.Open();
int recordFound = Convert.ToInt16(cmd.ExecuteScalar());
if (recordFound > 0)
{
FrmReportMemberProfile frmReportMemberProfile = new FrmReportMemberProfile(txtFileNo.Text);
frmReportMemberProfile.MdiParent = this.ParentForm;
frmReportMemberProfile.Show();
}
else
{
MessageBox.Show("There's no member with that File No.", "Report Generation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void FrmGenerateMemberProfileByFileNo_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/MainApp/MainApp/Departments/EditDepartment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class EditDepartment : Form
{
private string originalDeptName;
private Hashtable deptDetails;
public EditDepartment()
{
InitializeComponent();
}
private void txtDescription_TextChanged(object sender, EventArgs e)
{
}
private void grpEditDepartment_Enter(object sender, EventArgs e)
{
}
private void EditDepartment_Load(object sender, EventArgs e)
{
loadDepartments();
}
//load Departments
private void loadDepartments()
{
deptDetails = new Hashtable();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentName, Description from Departments";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int countRecords = 0;
lstDepartments.Items.Clear();
if (reader.HasRows)
{
while (reader.Read())
{
deptDetails.Add(reader["DepartmentName"].ToString(), reader["Description"].ToString());
lstDepartments.Items.Add(reader["DepartmentName"].ToString());
countRecords++;
}
}
lblRecordNumber.Text = "No of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
//End of Load Departments
private void selectDept()
{
originalDeptName = lstDepartments.SelectedItem.ToString();
txtDepartmentName.Text = originalDeptName;
txtDescription.Text = deptDetails[originalDeptName].ToString();
}
private void lstDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
selectDept();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentName, Description from Departments where DepartmentName LIKE '%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
lstDepartments.Items.Clear();
deptDetails = new Hashtable();
SqlDataReader reader = cmd.ExecuteReader();
int countRecords = 0;
if (reader.HasRows)
{
while (reader.Read())
{
deptDetails.Add(reader["DepartmentName"].ToString(), reader["Description"].ToString());
lstDepartments.Items.Add(reader["DepartmentName"].ToString());
countRecords++;
}
}
lblRecordNumber.Text = "No of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
lstDepartments.Items.Clear();
loadDepartments();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtDepartmentName.Clear();
txtDescription.Clear();
txtSearch.Clear();
lstDepartments.SelectedIndex = -1;
loadDepartments();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lstDepartments.SelectedIndex != -1)
{
if (txtDepartmentName.Text != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Update Departments set DepartmentName=@DepartmentName, Description=@Description where DepartmentName='" + originalDeptName + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@DepartmentName", SqlDbType.NVarChar, 100);
cmd.Parameters["@DepartmentName"].Value = txtDepartmentName.Text;
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmd.Parameters["@Description"].Value = txtDescription.Text;
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("Record has been successfully updated!");
loadDepartments();
}
else
{
MessageBox.Show("An error has occurred updating department!", "Edit Department", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
txtDepartmentName.Clear();
txtDescription.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("The Department Name is required","Edit Department",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Select a Department to make an Update", "Edit Department", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
<file_sep>/MainApp/MainApp/Members/EditMember.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditMember : Form
{
//Declarations
int memberID;
string photoName = null;
public EditMember()
{
InitializeComponent();
}
private void EditMember_Load(object sender, EventArgs e)
{
//Resize form height
this.Height = 119;
loadStateIntoComboBox();
loadDeparmentsIntoComboBox();
loadBanksIntoComboBox();
}
private void loadStateIntoComboBox()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select StateID, State from States order by State";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "States");
DataTable dt = ds.Tables["States"];
cbo_State.DisplayMember = "State";
cbo_State.ValueMember = "StateID";
cbo_State.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadDeparmentsIntoComboBox()
{
DataSet ds = Departments.GetDepartmentList();
DataTable dt = ds.Tables["Departments"];
cbo_department.DisplayMember = "DepartmentName";
cbo_department.ValueMember = "DepartmentID";
cbo_department.DataSource = dt;
}
private void loadBanksIntoComboBox()
{
DataSet ds = Banks.GetBanks();
DataTable dt = ds.Tables["Banks"];
cbo_Bank.DisplayMember = "BankName";
cbo_Bank.ValueMember = "BankID";
cbo_Bank.DataSource = dt;
}
private void btnFindMember_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.Title, m.FirstName, m.MiddleName, m.LastName, m.Gender, m.Address," +
"m.LGA, m.StateID, s.State, m.Phone, m.Email, m.DepartmentID, d.DepartmentName, m.BankID, b.BankName, m.AccountNo, m.Photo,m.NOKFullName,m.NOKAddress," +
"m.NOKPhone from Members m inner join States s on m.StateID = s.StateID " +
"inner join Departments d on m.DepartmentID = d.DepartmentID " +
"inner join Banks b on m.BankID = b.BankID " +
"where m.FileNo='" + txtFindByFileNo.Text + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
this.Height = 603;
memberID = (int) reader["MemberID"];
photoName = reader["Photo"].ToString();
txt_FileNo.Text = reader["FileNo"].ToString();
txt_Title.Text = reader["Title"].ToString();
txt_FirstName.Text = reader["FirstName"].ToString();
txt_MiddleName.Text = reader["MiddleName"].ToString();
txt_LastName.Text = reader["LastName"].ToString();
string gender = reader["Gender"].ToString();
if (gender == "M") { rad_Male.Checked = true; } else { rad_Female.Checked = true; }
txt_Address.Text = reader["Address"].ToString();
txt_LGA.Text = reader["LGA"].ToString();
cbo_State.SelectedValue =(int) reader["StateID"];
txt_Phone.Text = reader["Phone"].ToString();
txt_Email.Text = reader["Email"].ToString();
cbo_department.SelectedValue = (int) reader["DepartmentID"];
cbo_Bank.SelectedValue = (int)reader["BankID"];
txt_AccountNo.Text = reader["AccountNo"].ToString();
txt_NOKName.Text = reader["NOKFullName"].ToString();
txt_NOKAddress.Text = reader["NOKAddress"].ToString();
txt_NOKPhone.Text = reader["NOKPhone"].ToString();
if (reader["Photo"].ToString() != string.Empty)
{
//Load User picture
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
btnEnableEditing.Enabled = true;
}
else
{
MessageBox.Show("Sorry, there is no record with that File No.", "Record Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cbo_State_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnEnableEditing_Click(object sender, EventArgs e)
{
txt_FileNo.ReadOnly = !(txt_FileNo.ReadOnly);
txt_Title.ReadOnly = !(txt_Title.ReadOnly);
txt_FirstName.ReadOnly = !(txt_FirstName.ReadOnly);
txt_MiddleName.ReadOnly = !(txt_MiddleName.ReadOnly);
txt_LastName.ReadOnly = !(txt_LastName.ReadOnly);
rad_Male.Enabled = !(rad_Male.Enabled);
rad_Female.Enabled = !(rad_Female.Enabled);
txt_Address.ReadOnly = !(txt_Address.ReadOnly);
txt_LGA.ReadOnly = !(txt_LGA.ReadOnly);
cbo_State.Enabled = !(cbo_State.Enabled);
txt_Phone.ReadOnly = !(txt_Phone.ReadOnly);
txt_Email.ReadOnly = !(txt_Email.ReadOnly);
cbo_department.Enabled = !(cbo_department.Enabled);
cbo_Bank.Enabled = !(cbo_Bank.Enabled);
txt_AccountNo.ReadOnly = !(txt_AccountNo.ReadOnly);
txt_NOKName.ReadOnly = !(txt_NOKName.ReadOnly);
txt_NOKAddress.ReadOnly = !(txt_NOKAddress.ReadOnly);
txt_NOKPhone.ReadOnly = !(txt_NOKPhone.ReadOnly);
btnLoadPic.Enabled = !(btnLoadPic.Enabled);
btnClearPic.Enabled = !(btnClearPic.Enabled);
btnCancel.Enabled = !(btnCancel.Enabled);
btnUpdate.Enabled = !(btnUpdate.Enabled);
if (btnEnableEditing.Text=="Enable Editing")
{
btnEnableEditing.Text = "Disable Editing";
}else
{
btnEnableEditing.Text = "Enable Editing";
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
btnEnableEditing_Click(sender, e);
this.Height = 119;
btnEnableEditing.Enabled = !(btnEnableEditing.Enabled);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you wish to Update Member Information?", "Edit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
#region Edit Member
//check that all fields have been supplied.
bool isAnyFieldBlank = anyBlankField();
//check that the FileNo has not been changed to an assigned FileNo of another member
SqlConnection conn = ConnectDB.GetConnection();
bool isFileNoAlreadyAssigned = fileNoAlreadyAssigned(memberID, conn);
//MessageBox.Show("isAnyFieldBlank " + isAnyFieldBlank + " - isFileNoAlreadyAssigned - " + isFileNoAlreadyAssigned);
if ((isAnyFieldBlank == false) && (isFileNoAlreadyAssigned == false))
{
string strUpdate = "Update Members set FileNo=@FileNo, FirstName=@FirstName, MiddleName=@MiddleName, LastName=@LastName," +
" Gender=@Gender, Address=@Address, LGA=@LGA, StateID=@StateID, Phone=@Phone, Email=@Email, DepartmentID=@DepartmentID," +
" BankID=@BankID, AccountNo=@AccountNo, Photo=@Photo, NOKFullName=@NOKFullName, NOKAddress=@NOKAddress, NOKPhone=@NOKPhone " +
" where MemberID=@MemberID";
SqlCommand cmdUpate = new SqlCommand(strUpdate, conn);
cmdUpate.Parameters.Add("@FileNo", System.Data.SqlDbType.NVarChar, 50, "FileNo");
cmdUpate.Parameters["@FileNo"].Value = txt_FileNo.Text.Trim();
cmdUpate.Parameters.Add("@FirstName", System.Data.SqlDbType.NVarChar, 50, "FirstName");
cmdUpate.Parameters["@FirstName"].Value = txt_FirstName.Text.Trim();
cmdUpate.Parameters.Add("@MiddleName", System.Data.SqlDbType.NVarChar, 50, "MiddleName");
cmdUpate.Parameters["@MiddleName"].Value = txt_MiddleName.Text.Trim();
cmdUpate.Parameters.Add("@LastName", System.Data.SqlDbType.NVarChar, 50, "LastName");
cmdUpate.Parameters["@LastName"].Value = txt_LastName.Text.Trim();
char gender = 'M';
if (rad_Male.Checked)
{
gender = 'M';
}
else if (rad_Female.Checked)
{
gender = 'F';
}
cmdUpate.Parameters.Add("@Gender", System.Data.SqlDbType.Char, 1, "Gender");
cmdUpate.Parameters["@Gender"].Value = gender;
cmdUpate.Parameters.Add("@Address", System.Data.SqlDbType.NVarChar, 100, "Address");
cmdUpate.Parameters["@Address"].Value = txt_Address.Text.Trim();
cmdUpate.Parameters.Add("@LGA", System.Data.SqlDbType.NVarChar, 50, "LGA");
cmdUpate.Parameters["@LGA"].Value = txt_LGA.Text.Trim();
cmdUpate.Parameters.Add("@StateID", System.Data.SqlDbType.Int);
cmdUpate.Parameters["@StateID"].Value = cbo_State.SelectedValue;
cmdUpate.Parameters.Add("@Phone", System.Data.SqlDbType.NVarChar, 50, "Phone");
cmdUpate.Parameters["@Phone"].Value = txt_Phone.Text.Trim();
cmdUpate.Parameters.Add("@Email", System.Data.SqlDbType.NVarChar, 50, "Email");
cmdUpate.Parameters["@Email"].Value = txt_Email.Text.Trim();
cmdUpate.Parameters.Add("@DepartmentID", System.Data.SqlDbType.Int);
cmdUpate.Parameters["@DepartmentID"].Value = cbo_department.SelectedValue;
cmdUpate.Parameters.Add("@BankID", System.Data.SqlDbType.Int);
cmdUpate.Parameters["@BankID"].Value = cbo_Bank.SelectedValue;
cmdUpate.Parameters.Add("@AccountNo", System.Data.SqlDbType.NVarChar, 50);
cmdUpate.Parameters["@AccountNo"].Value = txt_AccountNo.Text.Trim();
cmdUpate.Parameters.Add("@Photo", System.Data.SqlDbType.NVarChar, 100, "Photo");
cmdUpate.Parameters["@Photo"].Value = photoName;
cmdUpate.Parameters.Add("@NOKFullName", System.Data.SqlDbType.NVarChar, 50, "NOKFullName");
cmdUpate.Parameters["@NOKFullName"].Value = txt_NOKName.Text.Trim();
cmdUpate.Parameters.Add("@NOKAddress", System.Data.SqlDbType.NVarChar, 50, "NOKAddress");
cmdUpate.Parameters["@NOKAddress"].Value = txt_NOKAddress.Text.Trim();
cmdUpate.Parameters.Add("@NOKPhone", System.Data.SqlDbType.NVarChar, 50, "Phone");
cmdUpate.Parameters["@NOKPhone"].Value = txt_NOKPhone.Text.Trim();
cmdUpate.Parameters.Add("@MemberID", System.Data.SqlDbType.Int);
cmdUpate.Parameters["@MemberID"].Value = memberID;
try
{
conn.Open();
int rowsAffected = cmdUpate.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Member Record has been successfully Updated.", "Record Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("An Error has Occurred! Update has been aborted.", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("An error has occurred. Update cannot be performed at this time.\nEnsure all entries are accurately supplied.", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
private bool anyBlankField()
{
bool blankFieldExist = false;
string strMessage = string.Empty;
if (FieldValidator.isBlank(txt_Title.Text))
{
strMessage += "Title is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_FileNo.Text))
{
strMessage += "\nFile No. is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_LastName.Text))
{
strMessage += "\nLast Name is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_FirstName.Text))
{
strMessage += "\nFirst Name is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_Address.Text))
{
strMessage += "\nAddress is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_LGA.Text))
{
strMessage += "\nLGA is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_Phone.Text))
{
strMessage += "\nPhone No. is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_NOKName.Text))
{
strMessage += "\nNext of Kin Name is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_NOKAddress.Text))
{
strMessage += "\nNext of Kin Address is required";
blankFieldExist = true;
}
if (FieldValidator.isBlank(txt_NOKPhone.Text))
{
strMessage += "\nNext of Kin Phone No. is required";
blankFieldExist = true;
}
if (strMessage != string.Empty || blankFieldExist == true)
{
MessageBox.Show(strMessage, "An Error has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return blankFieldExist;
}
private bool fileNoAlreadyAssigned(int memberID, SqlConnection conn)
{
bool result = false;
string strQuery = "Select MemberID, Title, LastName, FirstName, FileNo from Members where MemberID!=@MemberID and FileNo=@FileNo";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@MemberID", System.Data.SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@FileNo", System.Data.SqlDbType.NVarChar, 50);
cmd.Parameters["@FileNo"].Value = txt_FileNo.Text.Trim();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Members");
DataTable dt = ds.Tables["Members"];
int recordFound = dt.Rows.Count;
if (recordFound>0)
{
foreach (DataRow row in dt.Rows)
{
string name = row["Title"].ToString() + ' ' + row["LastName"].ToString() + ' ' + row["FirstName"].ToString();
MessageBox.Show("The File No. " + row["FileNo"].ToString() + " is assigned to " + name, "FileNo. Already Exist", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
result = true;
}
else
{
result = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return result;
}
private void btnClearPic_Click(object sender, EventArgs e)
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
//picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
photoName = null;
}
private void btnLoadPic_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "C:\\";
open.Filter = "Image Files(*.jpg)|*.jpg|All Files(*.*)|*.*";
open.FilterIndex = 1;
if (open.ShowDialog() == DialogResult.OK)
{
if (open.CheckFileExists)
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
string correctFileName = System.IO.Path.GetFileName(open.FileName);
string fileSuffix = DateTime.Now.ToString("dd_MM_yy_hh_mm_ss");
try
{
photoName = "userphoto" + fileSuffix + ".jpg";
System.IO.File.Copy(open.FileName, paths + "\\photos\\" + photoName);
picMember.Image = Image.FromFile(paths + "\\photos\\" + photoName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
}
}
private void txt_LastName_Leave(object sender, EventArgs e)
{
txt_LastName.Text = txt_LastName.Text.ToUpper();
}
}
}
<file_sep>/MainApp/MainApp/Classes/CheckForNumber.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MainApp
{
public static class CheckForNumber
{
public static bool isNumeric(string strValue)
{
decimal n;
bool result = decimal.TryParse(strValue, out n);
return result;
}
public static string formatCurrency(string strValue)
{
string result = string.Format("{0:#,#.00}", Math.Round(Convert.ToDecimal(strValue),2));
return result;
}
public static string formatCurrency2(string strValue)
{
string result = string.Format("{0:0,0.00}", Math.Round(Convert.ToDecimal(strValue),2));
return result;
}
}
}
<file_sep>/MainApp/MainApp/Contributions/ViewContributions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewContributions : Form
{
SqlConnection conn;
SqlCommand cmd, cmdTotal;
SqlDataAdapter da;
DataSet ds;
DataTable dt;
string totalContributionOfDataSet = null;
public ViewContributions()
{
InitializeComponent();
}
private void ViewContributions_Load(object sender, EventArgs e)
{
loadAllContributions();
loadMonthIntoComboBox();
loadYearIntoComboBox();
loadPaymentModeIntoComboBox();
loadBanksIntoComboBox();
}
private void loadAllContributions()
{
selectQueryMethod();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds,"Contributions");
dt = ds.Tables["Contributions"];
datGrdVContributions.DataSource = dt;
datGrdVContributions.Columns[1].Width = 200;
datGrdVContributions.Columns[3].DefaultCellStyle.Format = "N2";
datGrdVContributions.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
lblRecordNo.Text = "No. of Records: " + dt.Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
displayTotalOfDataSet();
}
private void displayTotalOfDataSet()
{
SqlConnection conn = ConnectDB.GetConnection();
cmdTotal = new SqlCommand(totalContributionOfDataSet, conn);
try
{
conn.Open();
SqlDataReader reader = cmdTotal.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
lblTotalAmountOfDataSet.Text = "Total: " + CheckForNumber.formatCurrency2(reader["TotalAmount"].ToString());
}
else
{
lblTotalAmountOfDataSet.Text = "Total: 0.0";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadMonthIntoComboBox()
{
conn = ConnectDB.GetConnection();
string strQuery = "Select MonthID, Month from MonthByName";
cmd = new SqlCommand(strQuery, conn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Months");
DataTable dt = ds.Tables["Months"];
cboMonth.DisplayMember = "Month";
cboMonth.ValueMember = "MonthID";
cboFromMonth.DisplayMember = "Month";
cboFromMonth.ValueMember = "MonthID";
DataRow row = dt.NewRow();
row["Month"] = "--Select--";
dt.Rows.InsertAt(row, 0);
cboMonth.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadYearIntoComboBox()
{
conn = ConnectDB.GetConnection();
string strQuery = "Select distinct year from savings order by year";
cmd = new SqlCommand(strQuery, conn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Year");
DataTable dt = ds.Tables["Year"];
cboYear.DisplayMember = "year";
cboYear.ValueMember = "year";
DataRow row = dt.NewRow();
row["year"] = "--Select--";
dt.Rows.InsertAt(row, 0);
cboYear.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadPaymentModeIntoComboBox()
{
conn = ConnectDB.GetConnection();
string strQuery = "select PaymentModeID, PaymentMode from PaymentMode";
cmd = new SqlCommand(strQuery, conn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "PaymentMode");
DataTable dt = ds.Tables["PaymentMode"];
cboPaymentMode.DisplayMember = "PaymentMode";
cboPaymentMode.ValueMember = "PaymentModeID";
DataRow row = dt.NewRow();
row["PaymentMode"] = "--Select--";
dt.Rows.InsertAt(row, 0);
cboPaymentMode.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadBanksIntoComboBox()
{
conn = ConnectDB.GetConnection();
string strQuery = "Select BankID, BankName from Banks order by BankName";
cmd = new SqlCommand(strQuery, conn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Banks");
DataTable dt = ds.Tables["Banks"];
cboBanks.DisplayMember = "BankName";
cboBanks.ValueMember = "BankID";
DataRow row = dt.NewRow();
row["BankName"] = "--Select--";
dt.Rows.InsertAt(row, 0);
cboBanks.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private SqlCommand selectQueryMethod()
{
conn = ConnectDB.GetConnection();
string strQuery = "Select m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as [Full Name], " +
"mst.Remark [Account],s.Amount, d.Month, s.Year, p.PaymentMode [Payment Mode], c.OtherPayment [Other Payment], " +
"b.BankName [Bank], c.TellerNo [Teller No.], c.Comment, c.TransactionID, s.Date " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join Members m on s.MemberID = m.MemberID " +
"left join MonthByName d on s.Month=d.MonthID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join Banks b on c.BankID=b.BankID " +
"left join MemberSavingsTypeAcct mst on c.SavingsAcctID=mst.SavingsTypeID and m.MemberID=mst.MemberID " +
"where s.SavingSource='Contribution' order by s.SavingsID desc";
//Get TotalAmount of DataSet
totalContributionOfDataSet = "Select SUM(s.Amount) as TotalAmount " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join Members m on s.MemberID = m.MemberID " +
"left join MonthByName d on s.Month=d.MonthID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join Banks b on c.BankID=b.BankID where s.SavingSource='Contribution' ";
cmd = new SqlCommand(strQuery, conn);
cmdTotal = new SqlCommand(totalContributionOfDataSet, conn);
return cmd;
}
private SqlCommand selectQueryMethod(string searchCriteria, string sender)
{
//MessageBox.Show(searchCriteria.ToString());
string searchFilter = null;
switch (sender)
{
case "FileNoAndName":
searchFilter = "m.FileNo LIKE '%" + searchCriteria + "%' OR " +
"m.LastName LIKE '%" + searchCriteria + "%' OR " +
"m.MiddleName LIKE '%" + searchCriteria + "%' OR " +
"m.FirstName LIKE '%" + searchCriteria + "%'";
break;
case "Month":
searchFilter = "s.Month='" + searchCriteria + "'";
break;
case "Year":
searchFilter = "s.Year='" + searchCriteria + "'";
break;
case "PaymentMode":
searchFilter = "c.PaymentModeID=" + searchCriteria ;
break;
case "OtherPaymentMode":
searchFilter = "c.OtherPayment LIKE '%" + searchCriteria + "%'";
break;
case "Banks":
searchFilter = "c.BankID='" + searchCriteria + "'";
break;
case "TellerNo":
searchFilter = "c.TellerNo LIKE '%" + searchCriteria + "%'";
break;
case "DateInterval":
searchFilter = searchCriteria;
break;
case "Filter":
searchFilter = searchCriteria;
break;
}
//Configure search string for Total of DataSet
totalContributionOfDataSet = "Select SUM(s.Amount) as TotalAmount " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join Members m on s.MemberID = m.MemberID " +
"left join MonthByName d on s.Month=d.MonthID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join Banks b on c.BankID=b.BankID where s.SavingSource='Contribution' ";
totalContributionOfDataSet = totalContributionOfDataSet + " AND " + searchFilter;
//MessageBox.Show(totalContributionOfDataSet.ToString());
conn = ConnectDB.GetConnection();
string strQuery = "Select m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as [Full Name], " +
"mst.Remark [Account],s.Amount, d.Month, s.Year, p.PaymentMode [Payment Mode], c.OtherPayment [Other Payment], b.BankName [Bank], c.TellerNo [Teller No.], c.Comment, c.TransactionID, s.Date " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join Members m on s.MemberID = m.MemberID " +
"left join MonthByName d on s.Month=d.MonthID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join Banks b on c.BankID=b.BankID " +
"left join MemberSavingsTypeAcct mst on c.SavingsAcctID=mst.SavingsTypeID and m.MemberID=mst.MemberID " +
"where s.SavingSource='Contribution' and " + searchFilter + " order by s.SavingsID desc";
cmd = new SqlCommand(strQuery, conn);
return cmd;
}
private void txtSearchByFileNoAndName_KeyUp(object sender, KeyEventArgs e)
{
if (txtSearchByFileNoAndName.Text != string.Empty)
{
selectQueryMethod(txtSearchByFileNoAndName.Text, "FileNoAndName");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMonth.SelectedIndex != 0)
{
selectQueryMethod(cboMonth.SelectedValue.ToString(), "Month");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboYear.SelectedIndex != 0)
{
selectQueryMethod(cboYear.SelectedValue.ToString(), "Year");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void cboPaymentMode_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPaymentMode.SelectedIndex != 0)
{
selectQueryMethod(cboPaymentMode.SelectedValue.ToString(), "PaymentMode");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void txtOtherPaymentMode_KeyUp(object sender, KeyEventArgs e)
{
if (txtOtherPaymentMode.Text != string.Empty)
{
selectQueryMethod(txtOtherPaymentMode.Text, "OtherPaymentMode");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void displaySearchResult()
{
da = new SqlDataAdapter(cmd);
ds = new DataSet();
datGrdVContributions.DataSource = null;
try
{
conn.Open();
da.Fill(ds, "Contributions");
dt = ds.Tables["Contributions"];
datGrdVContributions.DataSource = dt;
datGrdVContributions.Columns[1].Width = 200;
datGrdVContributions.Columns[3].DefaultCellStyle.Format = "N2";
datGrdVContributions.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
lblRecordNo.Text = "No. of Records: " + dt.Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
//Call Method to display totalAmount of Displayed DataSet
if (dt.Rows.Count != 0)
{
displayTotalOfDataSet();
}
else
{
lblRecordNo.Text = "No. of Records: " + dt.Rows.Count.ToString();
lblTotalAmountOfDataSet.Text = "Total: 0.0";
}
}
private void cboBanks_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboBanks.SelectedIndex != 0)
{
selectQueryMethod(cboBanks.SelectedValue.ToString(), "Banks");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void txtTellerNo_KeyUp(object sender, KeyEventArgs e)
{
if (txtTellerNo.Text != string.Empty)
{
selectQueryMethod(txtTellerNo.Text, "TellerNo");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void btnFilter_Click(object sender, EventArgs e)
{
string searchCriteria = string.Empty;
if (txtSearchByFileNoAndName.Text != string.Empty)
{
searchCriteria += "(m.FileNo LIKE '%" + txtSearchByFileNoAndName.Text + "%' OR " +
"m.LastName LIKE '%" + txtSearchByFileNoAndName.Text + "%' OR " +
"m.MiddleName LIKE '%" + txtSearchByFileNoAndName.Text + "%' OR " +
"m.FirstName LIKE '%" + txtSearchByFileNoAndName.Text + "%') ";
}
if (cboMonth.SelectedIndex != 0)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and " ;
}
searchCriteria += "(s.Month='" + cboMonth.SelectedValue + "')";
}
if (cboYear.SelectedIndex != 0)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
}
searchCriteria += "(s.Year='" + cboYear.SelectedValue + "')";
}
if (cboPaymentMode.SelectedIndex != 0)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
}
searchCriteria += "(c.PaymentModeID=" + cboPaymentMode.SelectedValue + ") ";
}
if (txtOtherPaymentMode.Text != string.Empty)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
}
searchCriteria += "(c.OtherPayment LIKE '%" + txtOtherPaymentMode.Text + "%') ";
}
if (cboBanks.SelectedIndex != 0)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
}
searchCriteria += "(c.BankID='" + cboBanks.SelectedValue.ToString() + "') ";
}
if (txtTellerNo.Text != string.Empty)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
}
searchCriteria += "(c.TellerNo LIKE '%" + txtTellerNo.Text + "%') ";
}
if (searchCriteria != string.Empty)
{
selectQueryMethod(searchCriteria, "Filter");
displaySearchResult();
}
else
{
loadAllContributions();
}
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void btnDatePeriodSearch_Click(object sender, EventArgs e)
{
if (cboFromMonth.Text != string.Empty && cboFromYear.Text != string.Empty && cboToMonth.Text != string.Empty && cboYear.Text != string.Empty)
{
int fromYear = int.Parse(cboFromYear.Text);
int toYear = int.Parse(cboToYear.Text);
int fromMonth = cboFromMonth.SelectedIndex;
int toMonth = cboToMonth.SelectedIndex;
if (fromYear>toYear)
{
MessageBox.Show("Please ensure to select the dates in the proper order", "Contribution", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}else{
string strQuery = "((s.Month between '" + fromMonth + "' and '" + toMonth + "') AND (s.Year between '" + fromYear + "' and '" + toYear + "'))";
selectQueryMethod(strQuery, "DateInterval");
displaySearchResult();
//MessageBox.Show(strQuery.ToString());
}
}
else
{
MessageBox.Show("Please select the Months and Year Period to make this search","Contribution",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
if (dt.Columns.Count > 0)
{
ExportData newExport = new ExportData();
newExport.ExportToExcel(dt, saveFD);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
<file_sep>/MainApp/MainApp/Members/AddMember.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
namespace MainApp
{
public partial class AddMember : Form
{
string photoName = string.Empty;
public AddMember()
{
InitializeComponent();
getStartSavingsMonth();
getStartSavingsYear();
}
private void getStartSavingsMonth()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MonthID,Month from MonthByName";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Months");
DataTable dt = ds.Tables["Months"];
cboStartSavingsMonth.DataSource = dt;
cboStartSavingsMonth.DisplayMember = "Month";
cboStartSavingsMonth.ValueMember = "MonthID";
//select next month
DateTime currentDate = DateTime.Now;
DateTime nextDate = currentDate.AddMonths(1);
int nextMonth = nextDate.Month;
//MessageBox.Show(nextMonth.ToString());
//select the next month
cboStartSavingsMonth.SelectedValue = nextMonth;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getStartSavingsYear()
{
DateTime myDate = DateTime.Now;
int thisYear = myDate.Year;
int startYear = 1990;
int countforward = 40;
int loop = 0;
while (loop <= countforward)
{
cboStartSavingsYear.Items.Add(startYear++);
loop++;
}
cboStartSavingsYear.SelectedItem = thisYear;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void radMale_CheckedChanged(object sender, EventArgs e)
{
}
private void radFemale_CheckedChanged(object sender, EventArgs e)
{
}
private void textBox10_TextChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter_1(object sender, EventArgs e)
{
}
#region Add Members Load Method
private void AddMember_Load(object sender, EventArgs e)
{
txtEntryFee.TextAlign = HorizontalAlignment.Right;
txtRegularSavings.TextAlign = HorizontalAlignment.Right;
txtOtherSavingsAmount.TextAlign = HorizontalAlignment.Right;
//LV Properties
lstVOtherSavings.View = View.Details;
lstVOtherSavings.FullRowSelect = true;
//LV Column Names
lstVOtherSavings.Columns.Add("ID",0);
lstVOtherSavings.Columns.Add("Savings Type", 150);
lstVOtherSavings.Columns.Add("Amount", 150);
// TODO: This line of code loads data into the 'fUNAAB_CTCS.Members' table. You can move, or remove it, as needed.
loadStates();
loadDepartments();
loadBanks();
loadSavingsType();
}
#endregion
#region Load States from Database into State Combo
private void loadStates()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select StateID, State from States order by State";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "States");
DataTable dt = ds.Tables["States"];
DataRow row = dt.NewRow();
row["State"] = "-- Select State --";
dt.Rows.InsertAt(row, 0);
cboState.DisplayMember = "State";
cboState.ValueMember = "StateID";
cboState.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
#region Load Departments from Database
private void loadDepartments()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentID, DepartmentName, Description from Departments order by DepartmentName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Departments");
DataTable dt = ds.Tables["Departments"];
cboDepartment.DisplayMember = "DepartmentName";
cboDepartment.ValueMember = "DepartmentID";
DataRow row = dt.NewRow();
row["DepartmentName"] = "-- Select Department --";
dt.Rows.InsertAt(row, 0);
cboDepartment.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
#region Load Banks from Database
private void loadBanks()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankID, BankName, Description from Banks order by BankName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Banks");
DataTable dt = ds.Tables["Banks"];
cboBank.DisplayMember = "BankName";
cboBank.ValueMember = "BankID";
DataRow row = dt.NewRow();
row["BankName"] = "-- Select Bank --";
dt.Rows.InsertAt(row, 0);
cboBank.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
#region Load Savings Type
private void loadSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsTypeID,SavingsName, Description from SavingsType order by SavingsName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingsType");
DataTable dt = ds.Tables["SavingsType"];
cboOtherSavings.DisplayMember = "SavingsName";
cboOtherSavings.ValueMember = "SavingsTypeID";
DataRow row = dt.NewRow();
row["SavingsName"] = "-- Add Savings Type --";
dt.Rows.InsertAt(row, 0);
cboOtherSavings.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion
#region Add Savings Button Click Event
private void btnAddSavings_Click(object sender, EventArgs e)
{
if (cboOtherSavings.SelectedValue.ToString() != string.Empty)
{
string OtherSavings = cboOtherSavings.Text;
bool savingsTypeAlreadyExist = false;
#region Check to see if Selected Savings Type has been added
//check to see if OtherSavings Amount have been supplied
if (txtOtherSavingsAmount.Text != string.Empty)
{
#region Loop through List View and check if selected cbo item has already been added
//check to see to item has not been added and turn to either true or false
if (lstVOtherSavings.Items.Count != 0)
{
for (int i = 0; i < lstVOtherSavings.Items.Count; i++)
{
//MessageBox.Show(lstVOtherSavings.Items[i].SubItems[1].Text.Trim() + " -- " + cboOtherSavings.Text.Trim());
if (lstVOtherSavings.Items[i].SubItems[1].Text.Trim() == cboOtherSavings.Text.Trim())
{
MessageBox.Show("The Savings Type '" + cboOtherSavings.Text + "' has been added already","Add Savings Type",MessageBoxButtons.OK,MessageBoxIcon.Warning);
savingsTypeAlreadyExist = true;
}
}
}
#endregion
//if SavingsType has not been added already perform addition to ListView
if (savingsTypeAlreadyExist == false)
{
//Add selected cboSavings Item to ListView
addSavingsTypeToListView(cboOtherSavings.SelectedValue.ToString(), cboOtherSavings.Text, txtOtherSavingsAmount.Text);
}
}
else
{
MessageBox.Show("Savings Amount is required to Add a Savings Type","Savings Type",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
#endregion
}
else
{
MessageBox.Show("Please Select a Savings Type and Amount to Add a Savings Type","Savings Type",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
#endregion
#region Method to add Savings Type to List View
private void addSavingsTypeToListView(string ID,string SavingsName,string Amount)
{
string formatAmount = String.Format("{0:0,0.00}", Convert.ToDecimal(Amount));
string[] row = { ID, SavingsName, formatAmount};
ListViewItem item = new ListViewItem(row);
lstVOtherSavings.Items.Add(item);
txtOtherSavingsAmount.Clear();
}
#endregion
private void txtOtherSavingsAmount_TextChanged(object sender, EventArgs e)
{
}
private void txtOtherSavingsAmount_Leave(object sender, EventArgs e)
{
string strValue = txtOtherSavingsAmount.Text.Trim();
if (CheckForNumber.isNumeric(strValue))
{
txtOtherSavingsAmount.Text = CheckForNumber.formatCurrency(txtOtherSavingsAmount.Text);
}
else
{
MessageBox.Show("Value entered for Savings Amount is Invalid", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtOtherSavingsAmount.Clear();
}
}
private void txtRegularSavings_Leave(object sender, EventArgs e)
{
string strValue = txtRegularSavings.Text.Trim();
if (CheckForNumber.isNumeric(strValue))
{
txtRegularSavings.Text = CheckForNumber.formatCurrency(txtRegularSavings.Text);
}
else
{
MessageBox.Show("Value entered for Regular Savings is Invalid", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtRegularSavings.Clear();
}
}
private void btnRemoveSavings_Click(object sender, EventArgs e)
{
if (lstVOtherSavings.SelectedItems.Count != 0)
{
lstVOtherSavings.Items.RemoveAt(lstVOtherSavings.SelectedIndices[0]);
}
else
{
MessageBox.Show("Select a Savings Type to Remove Item","Remove Savings Type",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
private void txtLastName_Leave(object sender, EventArgs e)
{
txtLastName.Text = txtLastName.Text.ToUpper().Trim();
}
private void txtEmail_Leave(object sender, EventArgs e)
{
txtEmail.Text = txtEmail.Text.ToLower().Trim();
}
private void btnLoadPic_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "C:\\";
open.Filter = "Image Files(*.jpg)|*.jpg|All Files(*.*)|*.*";
open.FilterIndex = 1;
if (open.ShowDialog() == DialogResult.OK)
{
if (open.CheckFileExists)
{
string paths = PhotoPath.getPath();
string correctFileName = System.IO.Path.GetFileName(open.FileName);
string fileSuffix = DateTime.Now.ToString("dd_MM_yy_hh_mm_ss");
try
{
photoName = "userphoto" + fileSuffix + ".jpg";
System.IO.File.Copy(open.FileName, paths + "\\photos\\" + photoName);
picMember.Image = Image.FromFile(paths + "\\photos\\" + photoName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
}
}
private void btnClearPic_Click(object sender, EventArgs e)
{
string paths = PhotoPath.getPath();
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
photoName = string.Empty;
}
private void btnSave_Click(object sender, EventArgs e)
{
//Validate Member's information before saving
bool validationSucceed;
validationSucceed = passValidation();
if (validationSucceed)
{
if (!fileNoExist())
{
DialogResult res = MessageBox.Show("Do you really wish to register this person as a member?", "Member Registration", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
registerNewMember();
}
}
else
{
MessageBox.Show("A member with same FileNo Already Exist", "New Member Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
//check if Member with FileNo already Exist
}
//Check if member with same FileNo already exist
#region Check if member with same FileNo already exist
private bool fileNoExist()
{
bool result = true;
SqlConnection conn = ConnectDB.GetConnection();
string strFileNoExist = "Select Count(*) from Members where FileNo=@FileNo";
SqlCommand cmdFileNoExist = new SqlCommand(strFileNoExist, conn);
cmdFileNoExist.Parameters.Add("@FileNo", SqlDbType.NVarChar, 20, "FileNo");
cmdFileNoExist.Parameters["@FileNo"].Value = txtFileNo.Text.Trim();
try
{
conn.Open();
int rowFound = (int) cmdFileNoExist.ExecuteScalar();
if (rowFound > 0)
{
result = true; //record of same FileNo exist
}
else
{
result = false; //No record of same FileNo exist
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return result;
}
#endregion
//End of member check with same FileNo
#region Register New Member Function
private void registerNewMember()
{
//MessageBox.Show(cboState.SelectedValue.ToString());
string title = txtTitle.Text.Trim();
string firstname = txtFirstName.Text.Trim();
string middlename = txtMiddleName.Text.Trim();
string lastname = txtLastName.Text.Trim();
string gender = string.Empty;
if (radMale.Checked)
{
gender = "M";
}else
{
gender = "F";
}
string address = txtAddress.Text.Trim();
string lga = txtLGA.Text.Trim();
string stateID = cboState.SelectedValue.ToString();
string phone = txtPhone.Text.Trim();
string email = txtEmail.Text.Trim();
string fileno = txtFileNo.Text.Trim().ToUpper();
string departmentID = cboDepartment.SelectedValue.ToString();
string bankID = cboBank.SelectedValue.ToString();
string accountNo = txtAccountNo.Text.Trim();
string NOKFullName = txtNOKName.Text.Trim();
string NOKAddress = txtNOKAddress.Text.Trim();
string NOKPhone = txtNOKPhone.Text.Trim();
string EntryFee = txtEntryFee.Text.Trim();
string RegularSavings = txtRegularSavings.Text.Trim();
SqlConnection conn = ConnectDB.GetConnection();
string strAddMember = "Insert into Members(FileNo,Title,FirstName,MiddleName,LastName," +
"Gender,Address,LGA,StateID,Phone,Email,DepartmentID,BankID,AccountNo,Photo,NOKFullName," +
"NOKAddress,NOKPhone,StartSavingsMonth,StartSavingsYear)values(@FileNo,@Title,@FirstName,@MiddleName,@LastName,@Gender,@Address,@LGA," +
"@StateID,@Phone,@Email,@DepartmentID,@BankID,@AccountNo,@Photo,@NOKFullName,@NOKAddress,@NOKPhone,@StartSavingsMonth,@StartSavingsYear)";
SqlCommand cmdAddMember = new SqlCommand(strAddMember, conn);
#region cmdAddMember Parameters
cmdAddMember.Parameters.Add("@FileNo", SqlDbType.NVarChar, 20, "FileNo");
cmdAddMember.Parameters["@FileNo"].Value = fileno;
cmdAddMember.Parameters.Add("@Title", SqlDbType.NVarChar, 20, "@Title");
cmdAddMember.Parameters["@Title"].Value = title;
cmdAddMember.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50, "FirstName");
cmdAddMember.Parameters["@FirstName"].Value = firstname;
cmdAddMember.Parameters.Add("@MiddleName", SqlDbType.NVarChar, 50, "MiddleName");
cmdAddMember.Parameters["@MiddleName"].Value = middlename;
cmdAddMember.Parameters.Add("@LastName", SqlDbType.NVarChar, 50, "LastName");
cmdAddMember.Parameters["@LastName"].Value = lastname;
cmdAddMember.Parameters.Add("@Gender", SqlDbType.NChar, 1, "Gender");
cmdAddMember.Parameters["@Gender"].Value = gender;
cmdAddMember.Parameters.Add("@Address", SqlDbType.NVarChar, 100, "Address");
cmdAddMember.Parameters["@Address"].Value = address;
cmdAddMember.Parameters.Add("@LGA", SqlDbType.NVarChar, 50, "LGA");
cmdAddMember.Parameters["@LGA"].Value = lga;
cmdAddMember.Parameters.Add("@StateID", SqlDbType.Int);
cmdAddMember.Parameters["@StateID"].Value = stateID;
cmdAddMember.Parameters.Add("@Phone", SqlDbType.NVarChar, 50, "Phone");
cmdAddMember.Parameters["@Phone"].Value = phone;
cmdAddMember.Parameters.Add("@Email", SqlDbType.NVarChar, 50, "Email");
cmdAddMember.Parameters["@Email"].Value = email;
cmdAddMember.Parameters.Add("@DepartmentID", SqlDbType.Int);
cmdAddMember.Parameters["@DepartmentID"].Value = departmentID;
cmdAddMember.Parameters.Add("@BankID", SqlDbType.Int);
cmdAddMember.Parameters["@BankID"].Value = bankID;
cmdAddMember.Parameters.Add("@AccountNo", SqlDbType.NVarChar, 50, "AccountNo");
cmdAddMember.Parameters["@AccountNo"].Value = accountNo;
cmdAddMember.Parameters.Add("@Photo", SqlDbType.NVarChar, 200, "Photo");
cmdAddMember.Parameters["@Photo"].Value = photoName;
cmdAddMember.Parameters.Add("@NOKFullName", SqlDbType.NVarChar, 50, "NOKFullName");
cmdAddMember.Parameters["@NOKFullName"].Value = NOKFullName;
cmdAddMember.Parameters.Add("@NOKAddress", SqlDbType.NVarChar, 50, "NOKAddress");
cmdAddMember.Parameters["@NOKAddress"].Value = NOKAddress;
cmdAddMember.Parameters.Add("@NOKPhone", SqlDbType.NVarChar, 30, "NOKPhone");
cmdAddMember.Parameters["@NOKPhone"].Value = NOKPhone;
cmdAddMember.Parameters.Add("@StartSavingsMonth", SqlDbType.Int);
cmdAddMember.Parameters["@StartSavingsMonth"].Value = cboStartSavingsMonth.SelectedValue;
cmdAddMember.Parameters.Add("@StartSavingsYear", SqlDbType.Int);
cmdAddMember.Parameters["@StartSavingsYear"].Value = Convert.ToInt16(cboStartSavingsYear.Text);
#endregion
SqlTransaction sqlTrans = null;
bool DBOperationSuccess = true;
#region Try-Catch for Adding New Member
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
cmdAddMember.Transaction = sqlTrans;
int rowsAffected = cmdAddMember.ExecuteNonQuery();
#region if insertion into Members DBTable Successful
if (rowsAffected > 0)
{
string strRetrieveMemberID = "Select MemberID,FileNo from Members where FileNo=@FileNo";
SqlCommand cmdRetrieveMember = new SqlCommand(strRetrieveMemberID, conn);
cmdRetrieveMember.Parameters.Add("@FileNo", SqlDbType.NVarChar, 20, "FileNo");
cmdRetrieveMember.Parameters["@FileNo"].Value = fileno;
cmdRetrieveMember.Transaction = sqlTrans;
int memberID = (int) cmdRetrieveMember.ExecuteScalar();
//Insert EntranceFee into EntranceFees Table
#region Insert EntranceFee into Entrance Table
string strShares = "Insert into EntranceFees(MemberID,Amount,Remark)values(@MemberID,@Amount,@Remark)";
SqlCommand cmdShares = new SqlCommand(strShares, conn);
cmdShares.Parameters.Add("@MemberID", SqlDbType.Int);
cmdShares.Parameters["@MemberID"].Value = memberID;
cmdShares.Parameters.Add("@Amount", SqlDbType.Decimal);
cmdShares.Parameters["@Amount"].Value = EntryFee;
cmdShares.Parameters.Add("@Remark", SqlDbType.NVarChar, 50, "Remark");
cmdShares.Parameters["@Remark"].Value = "Entrance Fees";
cmdShares.Transaction = sqlTrans;
int rowsAdded = cmdShares.ExecuteNonQuery();
if (rowsAdded == 0) { DBOperationSuccess = false; }
#endregion
//Insert into Regular Savings Table
#region Insert into Regular Savings Table
string strSavingsRegular = "Insert into MemberSavingsTypeAcct(MemberID,SavingsTypeID,Amount,Remark)" +
"values(@MemberID,@SavingsTypeID,@Amount,@Remark)";
SqlCommand cmdSavingsRegular = new SqlCommand(strSavingsRegular, conn);
cmdSavingsRegular.Parameters.Add("@MemberID", SqlDbType.Int);
cmdSavingsRegular.Parameters["@MemberID"].Value = memberID;
cmdSavingsRegular.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmdSavingsRegular.Parameters["@SavingsTypeID"].Value = 99;
cmdSavingsRegular.Parameters.Add("@Amount", SqlDbType.Decimal);
cmdSavingsRegular.Parameters["@Amount"].Value = RegularSavings;
cmdSavingsRegular.Parameters.Add("@Remark", SqlDbType.NVarChar, 50, "Remark");
cmdSavingsRegular.Parameters["@Remark"].Value = "Shares Savings";
cmdSavingsRegular.Transaction = sqlTrans;
int rowsNew = cmdSavingsRegular.ExecuteNonQuery();
if (rowsNew == 0) { DBOperationSuccess = false; }
#endregion
//end of Insertion into Regular Savings
//lstVOtherSavings Function ------
#region lstVOtherSavings Function
if (lstVOtherSavings.Items.Count != 0)
{
for (int i = 0; i < lstVOtherSavings.Items.Count; i++)
{
string savingTypeID = lstVOtherSavings.Items[i].SubItems[0].Text;
Decimal amount = Convert.ToDecimal(lstVOtherSavings.Items[i].SubItems[2].Text);
string remark = lstVOtherSavings.Items[i].SubItems[1].Text;
string strInsertSavingsType = "Insert into MemberSavingsTypeAcct(MemberID,SavingsTypeID,Amount,Remark)values(@MemberID,@SavingsTypeID,@Amount,@Remark)";
SqlCommand cmdInsertSavingsType = new SqlCommand(strInsertSavingsType, conn);
cmdInsertSavingsType.Parameters.Add("@MemberID", SqlDbType.Int);
cmdInsertSavingsType.Parameters["@MemberID"].Value = memberID;
cmdInsertSavingsType.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmdInsertSavingsType.Parameters["@SavingsTypeID"].Value = savingTypeID;
cmdInsertSavingsType.Parameters.Add("@Amount", SqlDbType.Decimal);
cmdInsertSavingsType.Parameters["@Amount"].Value = amount;
cmdInsertSavingsType.Parameters.Add("@Remark", SqlDbType.NVarChar, 50, "Remark");
cmdInsertSavingsType.Parameters["@Remark"].Value = remark;
cmdInsertSavingsType.Transaction = sqlTrans;
int rowsInserted = cmdInsertSavingsType.ExecuteNonQuery();
if (rowsInserted == 0) { DBOperationSuccess = false; }
}
}
#endregion
//end of lstVOtherSavings Function ----
if (DBOperationSuccess == true)
{
sqlTrans.Commit();
MessageBox.Show("New Member has been Successfully Registered", "New Member Registration", MessageBoxButtons.OK, MessageBoxIcon.Information);
clearAllFields();
}
else
{
sqlTrans.Rollback();
}
}
else
{
sqlTrans.Rollback();
}
#endregion
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
sqlTrans.Rollback();
}
finally
{
conn.Close();
}
#endregion
}
#endregion
#region passValidation Function - Validate Field Entries
private bool passValidation()
{
bool validationPassed = true;
string strMessage = null;
if (txtTitle.Text == string.Empty)
{
strMessage += "Title is required";
validationPassed = false;
txtTitle.BackColor = System.Drawing.Color.Yellow;
}
else
{
txtTitle.BackColor = Color.Empty;
}
if (FieldValidator.isBlank(txtFirstName.Text))
{
strMessage += "\nFirst Name is required";
validationPassed = false;
txtFirstName.BackColor = Color.Yellow;
}
else
{
txtFirstName.BackColor = Color.Empty;
}
if (txtLastName.Text == string.Empty)
{
strMessage += "\nLast Name is required";
validationPassed = false;
txtLastName.BackColor = Color.Yellow;
}
else
{
txtLastName.BackColor = Color.Empty;
}
if (!radMale.Checked && !radFemale.Checked)
{
strMessage += "\nGender is required";
validationPassed = false;
radMale.BackColor = Color.Yellow;
radFemale.BackColor = Color.Yellow;
}
else
{
radMale.BackColor = Color.Empty;
radFemale.BackColor = Color.Empty;
}
if (txtPhone.Text == string.Empty)
{
strMessage += "\nPhone No. is required";
validationPassed = false;
txtPhone.BackColor = Color.Yellow;
}
else
{
txtPhone.BackColor = Color.White;
}
if (cboState.Text == "-- Select State --")
{
strMessage += "\nSelect a State";
validationPassed = false;
cboState.BackColor = Color.Yellow;
}
else
{
cboState.BackColor = Color.White;
}
if (txtFileNo.Text == string.Empty)
{
strMessage += "\nFile No. is required";
validationPassed = false;
txtFileNo.BackColor = Color.Yellow;
}
else
{
txtFileNo.BackColor = Color.White;
}
if (cboDepartment.Text == "-- Select Department --")
{
strMessage += "\nDepartment is required";
validationPassed = false;
cboDepartment.BackColor = Color.Yellow;
}
else
{
cboDepartment.BackColor = Color.White;
}
if (FieldValidator.isBlank(txtNOKName.Text))
{
strMessage += "\nNext of Kin Name is required";
validationPassed = false;
txtNOKName.BackColor = Color.Yellow;
}
else
{
txtNOKName.BackColor = Color.White;
}
if (FieldValidator.isBlank(txtNOKPhone.Text))
{
strMessage += "\nNext of Kin Phone No. is required";
validationPassed = false;
txtNOKPhone.BackColor = Color.Yellow;
}
else
{
txtNOKPhone.BackColor = Color.Empty;
}
if (FieldValidator.isBlank(txtEntryFee.Text))
{
strMessage += "\nEntry Fee Amount is required";
validationPassed = false;
txtEntryFee.BackColor = Color.Yellow;
}
else
{
txtEntryFee.BackColor = Color.White;
}
if (FieldValidator.isBlank(txtRegularSavings.Text))
{
strMessage += "\nRegular Savings Amount is required";
validationPassed = false;
txtRegularSavings.BackColor = Color.Yellow;
}
else
{
txtRegularSavings.BackColor = Color.White;
}
if (strMessage != null)
{
MessageBox.Show(strMessage, "New Member Validation - From Validator", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return validationPassed;
}
#endregion
private void cboState_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void clearAllFields()
{
txtTitle.Clear();
txtFirstName.Clear();
txtMiddleName.Clear();
txtLastName.Clear();
radMale.Checked = false;
radFemale.Checked = false;
txtAddress.Clear();
txtLGA.Clear();
cboState.SelectedIndex = 0;
txtPhone.Clear();
txtEmail.Clear();
txtFileNo.Clear();
cboDepartment.SelectedIndex = 0;
cboBank.SelectedIndex = 0;
txtAccountNo.Clear();
txtNOKName.Clear();
txtNOKAddress.Clear();
txtNOKPhone.Clear();
txtEntryFee.Clear();
txtRegularSavings.Clear();
cboOtherSavings.SelectedIndex = 0;
txtOtherSavingsAmount.Clear();
lstVOtherSavings.Items.Clear();
btnClearPic_Click(null, null);
}
private void txtRegularSavings_TextChanged(object sender, EventArgs e)
{
}
private void txtEntryFee_Leave(object sender, EventArgs e)
{
string strValue = txtEntryFee.Text.Trim();
if (CheckForNumber.isNumeric(strValue))
{
txtEntryFee.Text = CheckForNumber.formatCurrency(txtEntryFee.Text);
}
else
{
MessageBox.Show("Value entered for Entrance Fee is Invalid", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtEntryFee.Clear();
}
}
private void txtFileNo_Leave(object sender, EventArgs e)
{
txtFileNo.Text = txtFileNo.Text.ToUpper();
}
}
}
<file_sep>/MainApp/MainApp/Deductions/ViewDeductionDetails.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewDeductionDetails : Form
{
string selDeductionId;
public ViewDeductionDetails(string selectedDeductionID)
{
InitializeComponent();
this.selDeductionId = selectedDeductionID;
}
private void ViewDeductionDetails_Load(object sender, EventArgs e)
{
getDeductions();
getDeductionDetails();
}
private void getDeductions()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted 'Date Posted', d.DeductionID from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month " +
"where d.DeductionID='" + selDeductionId + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Deductions");
DataTable dt = ds.Tables["Deductions"];
dtGrdDeductions.DataSource = dt;
dtGrdDeductions.Columns[0].Visible = false;
dtGrdDeductions.Columns[1].HeaderText = "File No.";
dtGrdDeductions.Columns["Full Name"].Width = 200;
dtGrdDeductions.Columns["Savings"].DefaultCellStyle.Format = "N2";
dtGrdDeductions.Columns["Loans"].DefaultCellStyle.Format = "N2";
dtGrdDeductions.Columns["Total"].DefaultCellStyle.Format = "N2";
dtGrdDeductions.Columns["Savings"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdDeductions.Columns["Loans"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdDeductions.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdDeductions.Columns["DeductionID"].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getDeductionDetails()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DeductionType, Amount, TransactionID, DatePosted 'Date Posted' from DeductionDetails " +
"where DeductionID='" + selDeductionId + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "DeductionDetails");
DataTable dt = ds.Tables["DeductionDetails"];
dtGrdDedDetails.DataSource = dt;
dtGrdDedDetails.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdDedDetails.Columns["DeductionType"].Width = 200;
dtGrdDedDetails.Columns["TransactionID"].Width = 150;
dtGrdDedDetails.Columns["TransactionID"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdDedDetails.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdDedDetails.Columns["Date Posted"].Width = 200;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/ReportsUI/FrmReportMemberProfile.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MainApp
{
public partial class FrmReportMemberProfile : Form
{
private string fileNo;
public FrmReportMemberProfile(string FileNo)
{
InitializeComponent();
fileNo = FileNo;
}
private void FrmReportMemberProfile_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DatasetMembers.Members' table. You can move, or remove it, as needed.
this.MembersTableAdapter.FillByMemberFileNo(DatasetMembers.Members, fileNo);
this.reportViewer1.LocalReport.EnableExternalImages = true;
this.reportViewer1.RefreshReport();
}
}
}
<file_sep>/MainApp/MainApp/Savings/DeleteSavingsForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class DeleteSavingsForward : Form
{
int memberID;
public DeleteSavingsForward()
{
InitializeComponent();
lstVwSavingDetails.View = View.Details;
lstVwSavingDetails.FullRowSelect = true;
lstVwSavingDetails.Columns.Add("SavingsForwardID", 0);
lstVwSavingDetails.Columns.Add("SavingsTypeID", 0);
lstVwSavingDetails.Columns.Add("Savings Acct", 150);
lstVwSavingDetails.Columns.Add("Amount", 100);
lstVwSavingDetails.Columns.Add("Comment", 150);
lstVwSavingDetails.Columns[3].TextAlign = HorizontalAlignment.Right;
}
private void btnFindMember_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo, LastName + ' ' + FirstName + ' ' + MiddleName as FullName, Photo from Members " +
"where FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = Convert.ToInt16(reader["MemberID"].ToString());
lblMemberProfile.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
//display member photo
string paths = PhotoPath.getPath();
if (reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
picMember.Visible = true;
lblMemberProfile.Visible = true;
grpBoxSavingsInfo.Enabled = true;
loadDataSetSavingsForward();
lstVwSavingDetails.Items.Clear();
}
else
{
MessageBox.Show("Sorry, there is no Member with that File No.", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadDataSetSavingsForward()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.Month, sf.Year, sf.Amount, sf.TransactionID, sf.Date from Savings sf " +
"left join MonthByName m on sf.Month=m.MonthID " +
"where MemberID=" + memberID + " and sf.SavingSource='SavingsForward' order by savingsID desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dtGrdVwSavings.DataSource = null;
dtGrdVwSavings.Columns.Clear();
dtGrdVwSavings.Rows.Clear();
dtGrdVwSavings.Refresh();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdVwSavings.DataSource = dt;
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwSavings.Columns["Year"].Width = 60;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dtGrdVwSavings.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "View Details";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
btn = new DataGridViewButtonColumn();
dtGrdVwSavings.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Delete";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
lblRecordNo.Text = "No. of Records: " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void DeleteSavingsForward_Load(object sender, EventArgs e)
{
}
private void dtGrdVwSavings_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string savingsAcct;
decimal savingsTotal = 0;
//MessageBox.Show(e.ColumnIndex.ToString());
#region View Record
if (e.ColumnIndex == 5)
{
string transactionID = dtGrdVwSavings.Rows[e.RowIndex].Cells[3].Value.ToString();
grpBoxDetails.Text = "Savings Details [" + transactionID + "]";
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsForwardID, SavingsTypeID, Amount, Comment from SavingsForward where TransactionID='" + transactionID + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
lstVwSavingDetails.Items.Clear();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if ((reader["SavingsTypeID"].ToString()) == "99")
{
savingsAcct = "Shares Savings";
}
else
{
savingsAcct = getSavingsAcctName(reader["SavingsTypeID"].ToString());
}
string[] row = { reader["SavingsForwardID"].ToString(), reader["SavingsTypeID"].ToString(), savingsAcct, CheckForNumber.formatCurrency2(reader["Amount"].ToString()), reader["Comment"].ToString() };
ListViewItem item = new ListViewItem(row);
lstVwSavingDetails.Items.Add(item);
savingsTotal = savingsTotal + Convert.ToDecimal(reader["Amount"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
#endregion end View Record
#region Delete Record
if (e.ColumnIndex == 6)
{
DialogResult res = MessageBox.Show("Do you wish to Delete the Selected Record?","Savings",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
SqlConnection conn = ConnectDB.GetConnection();
string transactionID = dtGrdVwSavings.Rows[e.RowIndex].Cells[3].Value.ToString();
string strQuery = "Delete from Savings where transactionID='" + transactionID + "'";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("Record has been deleted","Savings",MessageBoxButtons.OK);
loadDataSetSavingsForward();
//clear data items in listView
lstVwSavingDetails.Items.Clear();
}
else
{
MessageBox.Show("An error occurred. Record not deletee", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}finally{
conn.Close();
}
}
}
#endregion end Delete Record
}
private string getSavingsAcctName(string savingsTypeID)
{
SqlConnection conn2 = ConnectDB.GetConnection();
string strQuery = "Select SavingsName from SavingsType where SavingsTypeID=" + savingsTypeID;
SqlCommand cmd2 = new SqlCommand(strQuery, conn2);
conn2.Open();
SqlDataReader reader2 = cmd2.ExecuteReader();
reader2.Read();
string savingsTypeName = reader2["SavingsName"].ToString();
return savingsTypeName;
}
}
}
<file_sep>/MainApp/MainApp/Departments/DeleteDepartment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class DeleteDepartment : Form
{
Hashtable depts;
public DeleteDepartment()
{
InitializeComponent();
}
private void DeleteDepartment_Load(object sender, EventArgs e)
{
loadDepartments();
}
private void loadDepartments()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentName,Description from Departments";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
depts = new Hashtable();
SqlDataReader reader = cmd.ExecuteReader();
int countRecords = 0;
lstDepartment.Items.Clear();
while (reader.Read())
{
depts.Add(reader["DepartmentName"].ToString(), reader["Description"].ToString());
lstDepartment.Items.Add(reader["DepartmentName"].ToString());
countRecords++;
}
lblRecord.Text = "No. of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void lstDepartment_SelectedIndexChanged(object sender, EventArgs e)
{
txtDescription.Text = depts[lstDepartment.SelectedItem].ToString();
}
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentName, Description from Departments where DepartmentName LIKE '%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
depts = new Hashtable();
SqlDataReader reader = cmd.ExecuteReader();
int countRecords = 0;
lstDepartment.Items.Clear();
while (reader.Read())
{
depts.Add(reader["DepartmentName"].ToString(), reader["Description"].ToString());
lstDepartment.Items.Add(reader["DepartmentName"].ToString());
countRecords++;
}
lblRecord.Text = "No of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void DeleteDept()
{
string selectedDept = lstDepartment.SelectedItem.ToString();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Delete from Departments where DepartmentName='" + selectedDept + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Department '" + selectedDept + "' has been successfully deleted ", "Delete Department", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadDepartments();
txtDescription.Clear();
txtSearch.Clear();
}
else
{
MessageBox.Show("An error has occurred trying to delete Department '" + selectedDept + "'!", "Delete Department", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnDeleteDepartment_Click(object sender, EventArgs e)
{
if (lstDepartment.SelectedIndex != -1)
{
DialogResult result = MessageBox.Show("Do you wish to delete Department '" + lstDepartment.SelectedItem + "' ? ", "Delete Department", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
DeleteDept();
}
}
else
{
MessageBox.Show("No Department has been selected for Deletion","Delete Department",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
private void btnAll_Click(object sender, EventArgs e)
{
loadDepartments();
}
}
}
<file_sep>/MainApp/MainApp/ReportsUI/FrmReportMembers.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MainApp
{
public partial class FrmReportMembers : Form
{
public FrmReportMembers()
{
InitializeComponent();
}
private void FrmReportMembers_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DatasetMembers.Members' table. You can move, or remove it, as needed.
this.MembersTableAdapter.Fill(this.DatasetMembers.Members);
this.reportMembers.RefreshReport();
}
}
}
<file_sep>/MainApp/MainApp/Login.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select UserId, Username, Password, Lastname, Firstname from Users where Username=@Username and Password=@Password";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
cmd.Parameters.Add("@Username", SqlDbType.NVarChar, 50);
cmd.Parameters["@Username"].Value = txtUsername.Text.Trim();
cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50);
cmd.Parameters["@Password"].Value = txtPassword.Text.Trim();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
MainApp mainApp = new MainApp(reader["UserId"].ToString(),reader["LastName"].ToString(),reader["FirstName"].ToString());
mainApp.Show();
this.Hide();
}
else
{
MessageBox.Show("Authorised User Login Credentials", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Deductions/PostDeduction_Individual.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class PostDeduction_Individual : Form
{
int memberID;
decimal totalSavings;
decimal monthlyLoanRepayment;
int numOfRows;
int errorflag = 0;
string repaymentLoanType;
bool servicingLoan = false;
bool loanMoreThanSavings = false;
string UserId;
public PostDeduction_Individual(string UserID)
{
InitializeComponent();
UserId = UserID;
//LstDeduction Properties
lstMonthlyDeductions.View = View.Details;
lstMonthlyDeductions.FullRowSelect = true;
//LstDeductions Columns
lstMonthlyDeductions.Columns.Add("SN", 40);
lstMonthlyDeductions.Columns.Add("MemberID", 0);
lstMonthlyDeductions.Columns.Add("File No", 80);
lstMonthlyDeductions.Columns.Add("Name", 250);
lstMonthlyDeductions.Columns.Add("Savings", 120);
lstMonthlyDeductions.Columns.Add("Loans", 120);
lstMonthlyDeductions.Columns.Add("Total", 150);
lstMonthlyDeductions.Columns.Add("Status", 100);
//LstDeductions Alignment
lstMonthlyDeductions.Columns[4].TextAlign = HorizontalAlignment.Right;
lstMonthlyDeductions.Columns[5].TextAlign = HorizontalAlignment.Right;
lstMonthlyDeductions.Columns[6].TextAlign = HorizontalAlignment.Right;
lstMonthlyDeductions.Columns[7].TextAlign = HorizontalAlignment.Right;
//populate cboMonth and cboYear
populateCboMonth();
populateCboYear();
//lstVwSavings Properties
lstVwSavings.View = View.Details;
lstVwSavings.FullRowSelect = true;
//lstVwSavings Columns
lstVwSavings.Columns.Add("TypeID", 0);
lstVwSavings.Columns.Add("Type", 100);
lstVwSavings.Columns.Add("Amount", 100);
//lstVwSavings Alignment
lstVwSavings.Columns[2].TextAlign = HorizontalAlignment.Right;
//lstVwLoans Properties
lstVwLoans.View = View.Details;
lstVwLoans.FullRowSelect = true;
//lstVwLoans Columns
lstVwLoans.Columns.Add("Monthly Repay",100);
lstVwLoans.Columns.Add("Loan Repayment",100);
lstVwLoans.Columns.Add("Amount Paid",100);
lstVwLoans.Columns.Add("Outstanding",100);
lstVwLoans.Columns.Add("Loan type", 100);
lstVwLoans.Columns.Add("LoanTypeID", 50);
//lstVwLoans Alignment
lstVwLoans.Columns[0].TextAlign = HorizontalAlignment.Right;
lstVwLoans.Columns[1].TextAlign = HorizontalAlignment.Right;
lstVwLoans.Columns[2].TextAlign = HorizontalAlignment.Right;
lstVwLoans.Columns[3].TextAlign = HorizontalAlignment.Right;
}
private void populateCboMonth()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MonthID,Month from MonthByName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "MonthByName");
DataTable dt = ds.Tables["MonthByName"];
cboMonth.DataSource = dt;
cboMonth.DisplayMember = "Month";
cboMonth.ValueMember = "MonthID";
/*
DataRow row = dt.NewRow();
row["Month"] = "Select Month";
dt.Rows.InsertAt(row, 0);
* */
cboMonth.DataSource = dt;
DateTime dtTime = DateTime.Now;
int thisMonth = dtTime.Month;
cboMonth.SelectedValue = thisMonth;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void populateCboYear()
{
DateTime myDate = DateTime.Now;
int thisYear = myDate.Year;
int startYear = 1990;
int countforward = 40;
int loop = 0;
while (loop <= countforward)
{
cboYear.Items.Add(startYear++);
loop++;
}
cboYear.SelectedItem = thisYear;
}
private void getPreviousDeductionDate(int memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionID, m.Month + ' ' + d.Year as DeductionMonthYear from Deductions d left join MonthByName m" +
" on d.Month=m.MonthID where d.MemberID=" + memberID + " order by DeductionID desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (reader.HasRows)
{
reader.Read();
lblPreviousPosting.Text = "Previous Deduction : " + reader["DeductionMonthYear"].ToString();
}
else
{
lblPreviousPosting.Text = "No Previous Deductions";
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtFindByFileNo_TextChanged(object sender, EventArgs e)
{
if (txtFindByFileNo.Text.Length != 0)
{
btnFindMember.Enabled = true;
}
else
{
btnFindMember.Enabled = false;
}
}
private void btnFindMember_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo, LastName + ' ' + FirstName + ' ' + MiddleName as Fullname, Photo from Members where FileNo='" + txtFindByFileNo.Text + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
lstMonthlyDeductions.Items.Clear();
if (reader.HasRows)
{
reader.Read();
memberID = Convert.ToInt16(reader["MemberID"]);
memberPersonalInfo.Text = reader["Fullname"].ToString() + "\n" + reader["FileNo"].ToString();
if (reader["Photo"].ToString() != null || reader["Photo"].ToString() != string.Empty)
{
memberPic.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
memberPic.Visible = true;
memberPersonalInfo.Visible = true;
getMonthlyDeductionsInfo(memberID);
getMemberPreviousDeductions(memberID);
getPreviousDeductionDate(memberID);
btnPostDeduction.Enabled = true;
//Display Savings and Loan information
//lstMonthlyDeductions_SelectedIndexChanged(sender, e);
string selectedMemberID = lstMonthlyDeductions.Items[0].SubItems[1].Text;
getSavingsInfo(selectedMemberID);
getLoansInfo(selectedMemberID);
}
else
{
memberPic.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
MessageBox.Show("Sorry, there is no member with such File No.", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFindByFileNo_TextChanged(sender, e);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Member Search - " + ex.Message);
}
finally
{
}
}
private void getMonthlyDeductionsInfo(int memberID)
{
decimal loanMonthlyRepayment;
int counter;
decimal totalDeduction;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as Name, " +
"SUM(s.Amount) as Amount from Members m inner join MemberSavingsTypeAcct s on m.MemberID=s.MemberID where m.MemberID=" + memberID + " group by m.MemberID,m.FileNo,m.Title,m.FirstName,m.LastName,m.MiddleName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
counter = 0;
while (reader.Read())
{
counter++;
memberID = Convert.ToInt32(reader["MemberID"].ToString());
//check for loan records
loanMonthlyRepayment = getMonthlyLoan(memberID);
//calculate monthly total deduction using the total savings plus monthly loan repayment
totalDeduction = loanMonthlyRepayment + Convert.ToDecimal(reader["Amount"]);
//add data to the lstDeductions
String[] row = {counter.ToString(),reader["MemberID"].ToString(), reader["FileNo"].ToString(),
reader["Name"].ToString(),CheckForNumber.formatCurrency(reader["Amount"].ToString()),
CheckForNumber.formatCurrency2(loanMonthlyRepayment.ToString()), CheckForNumber.formatCurrency(totalDeduction.ToString())};
ListViewItem item = new ListViewItem(row);
lstMonthlyDeductions.Items.Clear();
lstMonthlyDeductions.Items.Add(item);
}
reader.Close();
//lblRecordNo.Text = "No. of Records: " + counter.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Post Deductions: - " + ex.Message);
}
finally
{
conn.Close();
}
}
private decimal getMonthlyLoan(int memberID)
{
decimal monthlyRepayment = 0;
SqlConnection conn2 = ConnectDB.GetConnection();
string strQuery = "Select a.MonthlyRepayment, l.OutstandingAmount, t.Type as LoanType from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID = l.LoanApplicationID " +
"inner join LoanType t on a.LoanTypeID=t.LoanTypeID where a.MemberID=@MemberID and l.OutstandingAmount<>0";
SqlCommand cmdLoan = new SqlCommand(strQuery, conn2);
cmdLoan.Parameters.Add("@MemberID", SqlDbType.Int);
cmdLoan.Parameters["@MemberID"].Value = memberID;
try
{
conn2.Open();
SqlDataReader loanReader = cmdLoan.ExecuteReader();
int recFound = loanReader.Cast<object>().Count();
//MessageBox.Show("Loan Servicing found: " + recFound.ToString());
loanReader.Close();
SqlDataReader readerGetLoanInfo = cmdLoan.ExecuteReader(CommandBehavior.SingleRow);
if (readerGetLoanInfo.HasRows)
{
if (readerGetLoanInfo.Read())
{
monthlyRepayment = Convert.ToDecimal(readerGetLoanInfo["MonthlyRepayment"]);
repaymentLoanType = readerGetLoanInfo["LoanType"].ToString();
//MessageBox.Show("Monthly Loan Repayment: " + readerGetLoanInfo["MonthlyRepayment"].ToString() + "\nLoan Type: " + repaymentLoanType);
}
}
readerGetLoanInfo.Close();
}
catch (Exception ex)
{
MessageBox.Show("getLoanTotal: - " + ex.Message);
}
finally
{
conn2.Close();
}
return monthlyRepayment;
}
private void getMemberPreviousDeductions(int memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionID, m.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted from Deductions d "+
"left join MonthByName m on d.Month=m.MonthID where MemberID=" + memberID + " order by d.DeductionID Desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Deductions");
DataTable dt = ds.Tables["Deductions"];
dtGridVPreviousDeductions.DataSource = dt;
dtGridVPreviousDeductions.Columns["DeductionID"].HeaderText = "ID";
dtGridVPreviousDeductions.Columns["DeductionID"].Width = 50;
dtGridVPreviousDeductions.Columns["TransactionID"].HeaderText = "Transact. ID";
dtGridVPreviousDeductions.Columns["DatePosted"].HeaderText = "Date Posted";
dtGridVPreviousDeductions.Columns["Savings"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGridVPreviousDeductions.Columns["Loans"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGridVPreviousDeductions.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGridVPreviousDeductions.Columns["Savings"].DefaultCellStyle.Format = "N2";
dtGridVPreviousDeductions.Columns["Loans"].DefaultCellStyle.Format = "N2";
dtGridVPreviousDeductions.Columns["Total"].DefaultCellStyle.Format = "N2";
lblPrevDeductionsCount.Text = "No. of Records: " + ds.Tables["Deductions"].Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnPostDeduction_Click(object sender, EventArgs e)
{
int selMonth = (int)cboMonth.SelectedValue;
int selYear = Convert.ToInt16(cboYear.Text);
int selMemberID = memberID;
bool isAlreadyPosted = checkIfAlreadyPosted(selMonth, selYear, selMemberID);
if (isAlreadyPosted == false)
{
DialogResult res = MessageBox.Show("Do you wish to Execute Posting for the selected Member, Month and Year? " +
"Please be sure about this because this process is not reversible", "Deduction Info", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
executeDeduction();
}
}
else
{
MessageBox.Show("Posting for " + cboMonth.Text + " " + cboYear.Text + " has already been executed", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//check if that posting had been done for that month and year
private bool checkIfAlreadyPosted(int month, int year, int selMember)
{
int recFound = 0;
bool result;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "select count(*) from Deductions where Month=@Month and Year=@Year and MemberID=@selMemberID";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Month", SqlDbType.Int);
cmd.Parameters["@Month"].Value = month;
cmd.Parameters.Add("@Year", SqlDbType.Int);
cmd.Parameters["@Year"].Value = year;
cmd.Parameters.Add("@selMemberID", SqlDbType.Int);
cmd.Parameters["@selMemberID"].Value = selMember;
try
{
conn.Open();
recFound = (int)cmd.ExecuteScalar();
//MessageBox.Show(recFound.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
if (recFound == 0) { result = false; } else { result = true; }
return result;
}
private void executeDeduction()
{
int numOfRecords = lstMonthlyDeductions.Items.Count;
int currentRecord;
SqlConnection conn = ConnectDB.GetConnection();
SqlTransaction sqlTrans = null;
SqlCommand cmd;
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
cmd = conn.CreateCommand();
cmd.Transaction = sqlTrans;
int selectedMonth = Convert.ToInt16(cboMonth.SelectedValue);
int selectedYear = Convert.ToInt16(cboYear.Text);
#region loop through records
//loop through records
for (currentRecord = 0; currentRecord < numOfRecords; currentRecord++)
{
cmd.Parameters.Clear();
memberID = Convert.ToInt16(lstMonthlyDeductions.Items[currentRecord].SubItems[1].Text);
decimal monthlyLoanRepayment = Convert.ToDecimal(lstMonthlyDeductions.Items[currentRecord].SubItems[5].Text);
decimal lstAllSavingsDeduction = Convert.ToDecimal(lstMonthlyDeductions.Items[currentRecord].SubItems[4].Text);
decimal lstAllLoansDeduction = Convert.ToDecimal(lstMonthlyDeductions.Items[currentRecord].SubItems[5].Text);
decimal lstTotalDeductions = Convert.ToDecimal(lstMonthlyDeductions.Items[currentRecord].SubItems[6].Text);
string transactionID = "DED" + DateTime.Now.ToString("ddMMyyhhmmss");
totalSavings = Convert.ToDecimal(lblTotalSavings.Text);
Deduction newPosting = new Deduction();
string postSavingsStatus = newPosting.postSavings(conn, cmd, sqlTrans, memberID, transactionID, lstAllSavingsDeduction, numOfRows, errorflag, selectedMonth, selectedYear);
//MessageBox.Show("Post Savings Status: " + postSavingsStatus);
string postLoansStatus = newPosting.postLoans(conn, cmd, sqlTrans, memberID, transactionID, currentRecord, selectedMonth, selectedYear, numOfRows, errorflag, monthlyLoanRepayment);
//MessageBox.Show("PostLoan Status: " + postLoansStatus);
string recordDeductionStatus = newPosting.recordDeduction(cmd, memberID, transactionID, currentRecord, selectedMonth, selectedYear, lstAllSavingsDeduction, lstAllLoansDeduction, lstTotalDeductions, numOfRows, errorflag);
//MessageBox.Show("Record Deductions status: " + recordDeductionStatus);
//string recordDeductionDetailsStatus = newPosting.recordDeductionDetails(cmd, memberID, transactionID, currentRecord, numOfRows, errorflag, lstAllSavingsDeduction, lstAllLoansDeduction, repaymentLoanType, servicingLoan, loanMoreThanSavings);
//MessageBox.Show("Record Deduction Detail Status: " + recordDeductionDetailsStatus);
int recordDeductionDetailStatus = recordDeductionDetails(cmd,memberID,transactionID,errorflag,numOfRows);
//MessageBox.Show(recordDeductionDetailStatus.ToString());
}
//end of for loop
#endregion end of loop
if (errorflag==0)
{
sqlTrans.Commit();
MessageBox.Show("Member Deduction has been successfully posted.","Deduction Info",MessageBoxButtons.OK,MessageBoxIcon.Information);
getMonthlyDeductionsInfo(memberID);
getMemberPreviousDeductions(memberID);
getPreviousDeductionDate(memberID);
//Display Savings and Loan information
//lstMonthlyDeductions_SelectedIndexChanged(sender, e);
string selectedMemberID = lstMonthlyDeductions.Items[0].SubItems[1].Text;
getSavingsInfo(selectedMemberID);
getLoansInfo(selectedMemberID);
txtChangeSavingsAmt.Text = string.Empty;
txtChangeLoanAmount.Text = string.Empty;
ActivityLog.logActivity(UserId, "Posting Deduction - Individual", "Deduction Posting for MemberID:" + memberID + " for Month:" + selectedMonth + " " + selectedYear);
}
else
{
sqlTrans.Rollback();
MessageBox.Show("Deduction Transaction failed and is aborted!","Deduction Info",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private int recordDeductionDetails(SqlCommand cmd,int memberID, string transactionID, int errorflag, int numOfRows)
{
//MessageBox.Show(lstVwSavings.Items.Count.ToString());
string strQuery = "Select DeductionID,TransactionID from Deductions where TransactionID=@TransactionID";
cmd.CommandText = strQuery;
#region cmd parameters
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int deductionID = (int)reader["DeductionID"];
reader.Close();
//Insert Savings into DeductionsDetails
int savingDeductionDetailStatus = SavingsDeductionDetails(cmd, transactionID, ref errorflag, ref numOfRows, ref strQuery, deductionID);
//Insert Loans into DeductionsDetails
int loanDeductionDetailStatus = LoansDeductionDetails(cmd, transactionID, ref errorflag, ref numOfRows, deductionID);
return numOfRows;
}
private int LoansDeductionDetails(SqlCommand cmd, string transactionID, ref int errorflag, ref int numOfRows, int deductionID)
{
string strQuery = "Insert into DeductionDetails(DeductionID,DeductionType,SavingsTypeID,Amount,Remarks,TransactionID)Values" +
"(@DeductionID,@DeductionType,@SavingsTypeID,@Amount,@Remarks,@TransactionID)";
cmd.CommandText = strQuery;
string deductionType = string.Empty;
decimal deductionAmount = 0;
string loanTypeID = string.Empty;
if (lstVwLoans.Items.Count != 0)
{
for (int i = 0; i < lstVwLoans.Items.Count; i++)
{
deductionType = lstVwLoans.Items[i].SubItems[4].Text;
deductionAmount = Convert.ToDecimal(lstMonthlyDeductions.Items[i].SubItems[5].Text);
loanTypeID = lstVwLoans.Items[i].SubItems[5].Text;
#region cmd parameters
cmd.Parameters["@DeductionID"].Value = deductionID;
cmd.Parameters["@DeductionType"].Value = deductionType;
cmd.Parameters["@SavingsTypeID"].Value = loanTypeID;
cmd.Parameters["@Amount"].Value = deductionAmount;
cmd.Parameters["@Remarks"].Value = string.Empty;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
}
}
return numOfRows;
}
private int SavingsDeductionDetails(SqlCommand cmd, string transactionID, ref int errorflag, ref int numOfRows, ref string strQuery, int deductionID)
{
strQuery = "Insert into DeductionDetails(DeductionID,DeductionType,SavingsTypeID,Amount,Remarks,TransactionID)Values" +
"(@DeductionID,@DeductionType,@SavingsTypeID,@Amount,@Remarks,@TransactionID)";
cmd.CommandText = strQuery;
cmd.Parameters.Add("@DeductionID", SqlDbType.Int);
cmd.Parameters.Add("@DeductionType", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("@SavingsTypeID", SqlDbType.NVarChar, 10);
//cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters.Add("@Remarks", SqlDbType.NVarChar, 400);
//cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
string deductionType = string.Empty;
decimal deductionAmount = 0;
string savingTypeID = string.Empty;
if (lstVwSavings.Items.Count != 0)
{
for (int i = 0; i < lstVwSavings.Items.Count; i++)
{
//lstVwSavings.Items[i].SubItems[0].Text + " - " + lstVwSavings.Items[i].SubItems[1].Text);
deductionType = lstVwSavings.Items[i].SubItems[1].Text;
deductionAmount = Convert.ToDecimal(lstVwSavings.Items[i].SubItems[2].Text);
savingTypeID = lstVwSavings.Items[i].SubItems[0].Text;
#region cmd parameters
cmd.Parameters["@DeductionID"].Value = deductionID;
cmd.Parameters["@DeductionType"].Value = deductionType;
cmd.Parameters["@SavingsTypeID"].Value = savingTypeID;
cmd.Parameters["@Amount"].Value = deductionAmount;
cmd.Parameters["@Remarks"].Value = string.Empty;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
}
}
return numOfRows;
}
private void lstMonthlyDeductions_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstMonthlyDeductions.SelectedItems.Count != 0)
{
string memberID = lstMonthlyDeductions.SelectedItems[0].SubItems[1].Text;
getSavingsInfo(memberID);
getLoansInfo(memberID);
}
}//end of executeDeduction
private void getSavingsInfo(string memberID)
{
decimal calTotalSavings = 0;
SqlConnection conn = ConnectDB.GetConnection();
string sqlQuery = "Select SavingsTypeID,Remark,Amount from MemberSavingsTypeAcct where MemberID=@MemberID";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.Add("@MemberID", SqlDbType.NVarChar, 20);
cmd.Parameters["@MemberID"].Value = memberID;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
lstVwSavings.Items.Clear();
if (reader.HasRows)
{
while (reader.Read())
{
calTotalSavings += Convert.ToDecimal(reader["Amount"]);
string[] row = { reader["SavingsTypeID"].ToString(), reader["Remark"].ToString(), CheckForNumber.formatCurrency2(reader["Amount"].ToString()) };
ListViewItem item = new ListViewItem(row);
lstVwSavings.Items.Add(item);
}
lblTotalSavings.Text = CheckForNumber.formatCurrency2(calTotalSavings.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Get Savings Info - " + ex.Message);
}
finally
{
conn.Close();
}
}
private void getLoansInfo(string memberID)
{
//decimal loanMonthlyPayment = 0;
//get loan amount
decimal serviceLoanAmount = Convert.ToDecimal(lstMonthlyDeductions.Items[0].SubItems[5].Text);
if (serviceLoanAmount > 0)
{
SqlConnection conn = ConnectDB.GetConnection();
string sqlQuery = "Select a.MonthlyRepayment,l.RepaymentAmount,l.AmountPaid,l.OutstandingAmount, lt.Type, lt.LoanTypeID from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID = l.LoanApplicationID " +
"inner join LoanType lt on a.LoanTypeID=lt.LoanTypeID " +
"where a.MemberID=@MemberID and l.OutstandingAmount<>0";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.Add("@MemberID", SqlDbType.NVarChar, 20);
cmd.Parameters["@MemberID"].Value = memberID;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
lstVwLoans.Items.Clear();
if (reader.HasRows)
{
reader.Read();
string[] row = {CheckForNumber.formatCurrency2(reader["MonthlyRepayment"].ToString()),CheckForNumber.formatCurrency2(reader["RepaymentAmount"].ToString()),CheckForNumber.formatCurrency2(reader["AmountPaid"].ToString()),CheckForNumber.formatCurrency2(reader["OutstandingAmount"].ToString()),reader["Type"].ToString(), reader["LoanTypeID"].ToString()};
ListViewItem item = new ListViewItem(row);
lstVwLoans.Items.Add(item);
lblTotalLoans.Text = CheckForNumber.formatCurrency2(reader["MonthlyRepayment"].ToString());
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Get Loans Info: - " + ex.Message);
}
finally
{
conn.Close();
}
}
}
private void lstVwSavings_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstVwSavings.SelectedItems.Count != 0)
{
txtChangeSavingsAmt.Text = lstVwSavings.SelectedItems[0].SubItems[2].Text;
txtChangeSavingsAmt.Enabled = true;
}
}
private void txtChangeSavingsAmt_TextChanged(object sender, EventArgs e)
{
if ((lstVwSavings.SelectedItems.Count != 0) && (txtChangeSavingsAmt.Text != string.Empty))
{
btnChangeSavingsAmt.Enabled = true;
}
}
private void btnChangeSavingsAmt_Click(object sender, EventArgs e)
{
decimal new_SavingsAmount;
decimal totalSavingsRecalculated = 0;
if (lstVwSavings.SelectedItems.Count > 0 && txtChangeSavingsAmt.Text != string.Empty)
{
int lstCountItem = lstVwSavings.Items.Count;
if (Decimal.TryParse(txtChangeSavingsAmt.Text, out new_SavingsAmount))
{
lstVwSavings.SelectedItems[0].SubItems[2].Text = CheckForNumber.formatCurrency2(txtChangeSavingsAmt.Text);
for (int i = 0; i < lstCountItem; i++)
{
totalSavingsRecalculated += Convert.ToDecimal(lstVwSavings.Items[i].SubItems[2].Text);
}
lblTotalSavings.Text = CheckForNumber.formatCurrency2(totalSavingsRecalculated.ToString());
}
else
{
MessageBox.Show("The Amount entered is invalid", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Select an a Savings Type and Supply an Amount", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void lstVwLoans_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstVwLoans.Items.Count != 0)
{
txtChangeLoanAmount.Enabled = true;
btnChangeLoanAmt.Enabled = true;
txtChangeLoanAmount.Text = lstVwLoans.SelectedItems[0].SubItems[0].Text;
}
}
private void btnChangeLoanAmt_Click(object sender, EventArgs e)
{
decimal new_LoansAmt;
decimal new_totalAmt;
if (lstVwLoans.SelectedItems.Count > 0 && txtChangeLoanAmount.Text != string.Empty)
{
if (decimal.TryParse(txtChangeLoanAmount.Text, out new_LoansAmt))
{
if (Convert.ToDecimal(txtChangeLoanAmount.Text) > 0)
{
lstMonthlyDeductions.Items[0].SubItems[5].Text = CheckForNumber.formatCurrency2(txtChangeLoanAmount.Text);
new_totalAmt = Convert.ToDecimal(lstMonthlyDeductions.Items[0].SubItems[4].Text) + Convert.ToDecimal(lstMonthlyDeductions.Items[0].SubItems[5].Text);
lstMonthlyDeductions.Items[0].SubItems[6].Text = CheckForNumber.formatCurrency2(new_totalAmt.ToString());
}
else
{
MessageBox.Show("The Amount entered is invalid", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("The Amount entered is invalid", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Select a Loan and Supply a new Loan Amount", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void btnApplyChanges_Click(object sender, EventArgs e)
{
decimal new_LoansAmt = 0;
//decimal new_totalAmt;
lstMonthlyDeductions.Items[0].SubItems[4].Text = lblTotalSavings.Text;
if (txtChangeLoanAmount.Text == string.Empty)
{
lstMonthlyDeductions.Items[0].SubItems[5].Text = lblTotalLoans.Text;
new_LoansAmt = Convert.ToDecimal(lblTotalLoans.Text);
}
else
{
if (decimal.TryParse(txtChangeLoanAmount.Text, out new_LoansAmt))
{
if (Convert.ToDecimal(txtChangeLoanAmount.Text) > 0)
{
lstMonthlyDeductions.Items[0].SubItems[5].Text = CheckForNumber.formatCurrency2(txtChangeLoanAmount.Text);
new_LoansAmt = Convert.ToDecimal(txtChangeLoanAmount.Text);
}
else
{
MessageBox.Show("The new Loan Amount entered is invalid", "Deduction Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
lstMonthlyDeductions.Items[0].SubItems[5].Text = lblTotalLoans.Text;
new_LoansAmt = Convert.ToDecimal(lblTotalLoans.Text);
}
}
}
lstMonthlyDeductions.Items[0].SubItems[6].Text = CheckForNumber.formatCurrency2(Convert.ToString(Convert.ToDecimal(lblTotalSavings.Text) + new_LoansAmt));
}
private void PostDeduction_Individual_Load(object sender, EventArgs e)
{
}
private void txtChangeSavingsAmt_Leave(object sender, EventArgs e)
{
if (!FieldValidator.isBlank(txtChangeSavingsAmt.Text) && CheckForNumber.isNumeric(txtChangeSavingsAmt.Text))
{
txtChangeSavingsAmt.Text = CheckForNumber.formatCurrency2(txtChangeSavingsAmt.Text);
}
}
private void txtChangeLoanAmount_Leave(object sender, EventArgs e)
{
if (!FieldValidator.isBlank(txtChangeLoanAmount.Text) && CheckForNumber.isNumeric(txtChangeLoanAmount.Text))
{
txtChangeLoanAmount.Text = CheckForNumber.formatCurrency2(txtChangeLoanAmount.Text);
}
}
}
}
<file_sep>/MainApp/MainApp/Loans/LoanApplication.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class LoanApplication : Form
{
SqlConnection conn = ConnectDB.GetConnection();
string paths = PhotoPath.getPath();
private string userId;
private string memberID;
public LoanApplication(string UserID)
{
InitializeComponent();
userId = UserID;
}
private void LoanApplication_Load(object sender, EventArgs e)
{
DateTime appDate = DateTime.Now;
lblAppMonthYear.Text = "Loan Application for " + appDate.ToString("MMMM, yyyy");
//MessageBox.Show(DateFunction.getMonthByName(appDate.Month));
cboMonth.Text = DateFunction.getMonthByName(appDate.Month);
cboYear.Text = appDate.Year.ToString();
loadMemberFileNoIntoCboFileNo();
loadLoanCategoryIntoCboCategory();
txtLoanDuration.TextAlign = HorizontalAlignment.Right;
txtLoanInterestRate.TextAlign = HorizontalAlignment.Right;
txtAmount.TextAlign = HorizontalAlignment.Right;
txtInterestAmount.TextAlign = HorizontalAlignment.Right;
txtTotalRepaymentAmount.TextAlign = HorizontalAlignment.Right;
txtMonthRepayment.TextAlign = HorizontalAlignment.Right;
lblSuretyMemberID_1.Text = string.Empty;
lblSuretyMemberID_2.Text = string.Empty;
lblSuretyMemberID_3.Text = string.Empty;
lblSurety1.Text = string.Empty;
lblSurety2.Text = string.Empty;
lblWitness.Text = string.Empty;
}
private void loadMemberFileNoIntoCboFileNo()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo from Members order by FileNo";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "FileNo");
DataTable dt = ds.Tables["FileNo"];
DataRow row = dt.NewRow();
row["FileNo"] = "-- Select a File No. --";
dt.Rows.InsertAt(row, 0);
cboFileNo.DisplayMember = "FileNo";
cboFileNo.ValueMember = "MemberID";
cboFileNo.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadLoanCategoryIntoCboCategory()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanCategoryID, Name from LoanCategory";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds,"LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
DataRow row = dt.NewRow();
row["Name"] = "-- Select a Loan Category --";
dt.Rows.InsertAt(row, 0);
cboCategory.DisplayMember = "Name";
cboCategory.ValueMember = "LoanCategoryID";
cboCategory.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboYear.Text != string.Empty)
{
lblAppMonthYear.Text = "Loan Application for " + cboMonth.Text + ", " + cboYear.Text;
}
else
{
lblAppMonthYear.Text = "Loan Application for " + cboMonth.Text;
}
}
private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMonth.Text != string.Empty)
{
lblAppMonthYear.Text = "Loan Application for " + cboMonth.Text + ", " + cboYear.Text;
}
else
{
lblAppMonthYear.Text = "Loan Application for " + cboYear.Text;
}
}
private void cboFileNo_Leave(object sender, EventArgs e)
{
retrieveMemberProfileByFileNo();
}
private void retrieveMemberProfileByFileNo()
{
if (cboFileNo.Text != "-- Select a File No. --")
{
#region retrieveMemberProfile
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID,Title,FileNo,FirstName,MiddleName,LastName,Photo from Members " +
"where FileNo='" + cboFileNo.Text.Trim() + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
lblMemberProfile.Visible = true;
lblMemberProfile.Text = reader["Title"].ToString() + " " + reader["LastName"].ToString() + " " + reader["FirstName"].ToString() + " " + reader["MiddleName"].ToString().Substring(0) + ".";
memberID = reader["MemberID"].ToString();
if ( reader["Photo"].ToString()!=null && reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "//photos//profile_img.png");
}
}
}
else
{
MessageBox.Show("Sorry, no record with that File No. [" + cboFileNo.Text + "] exist.", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
picMember.Image = Image.FromFile(paths + "//photos//profile_img.png");
lblMemberProfile.Text = string.Empty;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion end of retrieveMemberProfile
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
lblMemberProfile.Text = string.Empty;
lblMemberProfile.Visible = false;
} //end of if (--Select a File No. --)
}
private void cboFileNo_SelectedIndexChanged(object sender, EventArgs e)
{
retrieveMemberProfileByFileNo();
}
private void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCategory.Text != "-- Select a Loan Category --")
{
//retrieve LoanType Based on the selected LoanCategory
#region retrieveLoanType
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID,LoanCategoryID,Type from LoanType where LoanCategoryID=" + (Convert.ToInt16(cboCategory.SelectedValue));
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanType");
DataTable dt = ds.Tables["LoanType"];
DataRow row = dt.NewRow();
row["Type"] = "-- Select a Loan Type --";
dt.Rows.InsertAt(row, 0);
cboType.DisplayMember = "Type";
cboType.ValueMember = "LoanTypeID";
cboType.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Loan Category");
}
finally
{
conn.Close();
}
#endregion
}
else
{
//cboType.Items.Clear();
}
}
private void cboType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboType.Text != "-- Select a Loan Type --")
{
txtAmount.Enabled = true;
txtFormFee.Enabled = true;
#region retrieveLoanDetails
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID,Duration,InterestRate from LoanType where LoanTypeID=" + cboType.SelectedValue;
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
txtLoanDuration.Text = reader["Duration"].ToString();
txtLoanInterestRate.Text = reader["InterestRate"].ToString();
DateTime currentDate = DateTime.Now;
DateTime nextMonthStartRepayment = currentDate.AddMonths(0);
DateTime endOfRepayment = nextMonthStartRepayment.AddMonths(Convert.ToInt16(txtLoanDuration.Text));
txtEndRepaymentDate.Text = endOfRepayment.ToString("MMMM yyyy");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Loan Type");
}
finally
{
conn.Close();
}
#endregion
}
else
{
txtAmount.Enabled = false;
txtFormFee.Enabled = false;
}
}
private void txtAmount_TextChanged(object sender, EventArgs e)
{
if (txtAmount.Text != string.Empty)
{
if (CheckForNumber.isNumeric(txtAmount.Text.Trim()) == true)
{
decimal interestAmount = (Convert.ToDecimal(txtAmount.Text)) * ((Convert.ToDecimal(txtLoanInterestRate.Text)) / 100);
txtInterestAmount.Text = CheckForNumber.formatCurrency(interestAmount.ToString());
decimal totalRepaymentAmount = Convert.ToDecimal(txtAmount.Text) + interestAmount;
txtTotalRepaymentAmount.Text = CheckForNumber.formatCurrency(totalRepaymentAmount.ToString());
decimal monthRepayment = totalRepaymentAmount / Convert.ToInt16(txtLoanDuration.Text);
txtMonthRepayment.Text = CheckForNumber.formatCurrency(monthRepayment.ToString());
//enable btnSaveApplication
btnSaveApplication.Enabled = true;
}
else
{
MessageBox.Show("Sorry, Invalid value has been entered for Amount", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
btnSaveApplication.Enabled = false;
}
}
private void chkSurety1_CheckedChanged(object sender, EventArgs e)
{
if (chkSurety1.Checked == true)
{
txtSuretyFileNo1.Enabled = false;
txtSuretyName1.Enabled = true;
picSurety1.Image = Image.FromFile(paths + "//photos//profile_img.png");
txtSuretyFileNo1.Clear();
lblSurety1.Text = string.Empty;
lblSuretyMemberID_1.Text = string.Empty;
}
else
{
txtSuretyFileNo1.Enabled = true;
txtSuretyName1.Enabled = false;
txtSuretyName1.Clear();
}
}
private void chkSurety2_CheckedChanged(object sender, EventArgs e)
{
if (chkSurety2.Checked == true)
{
txtSuretyFileNo2.Enabled = false;
txtSuretyName2.Enabled = true;
picSurety2.Image = Image.FromFile(paths + "//photos//profile_img.png");
txtSuretyFileNo2.Clear();
lblSurety2.Text = string.Empty;
lblSuretyMemberID_2.Text = string.Empty;
}
else
{
txtSuretyFileNo2.Enabled = true;
txtSuretyName2.Enabled = false;
txtSuretyName2.Clear();
}
}
private void chkWitness_CheckedChanged(object sender, EventArgs e)
{
if (chkWitness.Checked == true)
{
txtWitnessFileNo.Enabled = false;
txtWitnessName.Enabled = true;
picWitness.Image = Image.FromFile(paths + "//photos//profile_img.png");
txtWitnessFileNo.Clear();
lblWitness.Text = string.Empty;
lblSuretyMemberID_3.Text = string.Empty;
}
else
{
txtWitnessFileNo.Enabled = true;
txtWitnessName.Enabled = false;
txtWitnessName.Clear();
}
}
private void txtSuretyName1_TextChanged(object sender, EventArgs e)
{
if (txtSuretyName1.Text != string.Empty)
{
lblSurety1.Visible = true;
picSurety1.Visible = true;
lblSurety1.Text = txtSuretyName1.Text.Trim();
}
else
{
lblSurety1.Text = string.Empty;
lblSurety1.Visible = false;
picSurety1.Visible = false;
}
}
private void txtSuretyName2_TextChanged(object sender, EventArgs e)
{
if (txtSuretyName2.Text != string.Empty)
{
lblSurety2.Visible = true;
picSurety2.Visible = true;
lblSurety2.Text = txtSuretyName2.Text.Trim();
}
else
{
lblSurety2.Text = string.Empty;
lblSurety2.Visible = false;
picSurety2.Visible = false;
}
}
private void txtWitnessName_TextChanged(object sender, EventArgs e)
{
if (txtWitnessName.Text != string.Empty)
{
lblWitness.Visible = true;
picWitness.Visible = true;
lblWitness.Text = txtWitnessName.Text.Trim();
}
else
{
lblWitness.Text = string.Empty;
lblWitness.Visible = false;
picWitness.Visible = false;
}
}
private void txtSuretyFileNo1_Leave(object sender, EventArgs e)
{
string strSender = "Surety1";
if (txtSuretyFileNo1.Text != string.Empty)
{
if (txtSuretyFileNo1.Text != cboFileNo.Text && txtSuretyFileNo1.Text != txtSuretyFileNo2.Text && txtSuretyFileNo1.Text != txtWitnessFileNo.Text)
{
getSuretyData(strSender, txtSuretyFileNo1.Text);
}
else
{
MessageBox.Show("Surety cannot be same person as the receipt, surety or witness", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSuretyFileNo1.Text = string.Empty;
}
}
}
private void getSuretyData(string strSender,string memberFileNo)
{
string memberProfile = string.Empty;
string memberID = string.Empty;
string memberPic = string.Empty;
string paths = PhotoPath.getPath();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID,FileNo,Title,LastName,MiddleName,FirstName,Photo from Members where FileNo='" + memberFileNo + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberProfile = reader["Title"].ToString() + " " + reader["LastName"].ToString() + " " + reader["FirstName"].ToString() + " " + reader["MiddleName"].ToString();
memberID = reader["MemberID"].ToString();
memberPic = reader["Photo"].ToString();
switch (strSender)
{
case "Surety1":
lblSurety1.Visible = true;
picSurety1.Visible = true;
lblSurety1.Text = "Surety 1\n" + memberProfile;
lblSuretyMemberID_1.Text = memberID;
if (memberPic != string.Empty)
{
picSurety1.Image = Image.FromFile(paths + "//photos//" + memberPic.ToString());
}
break;
case "Surety2":
lblSurety2.Visible = true;
picSurety2.Visible = true;
lblSurety2.Text = "Surety 2\n" + memberProfile;
lblSuretyMemberID_2.Text = memberID;
if (memberPic != string.Empty)
{
picSurety2.Image = Image.FromFile(paths + "//photos//" + memberPic.ToString());
}
break;
case "Witness":
lblWitness.Visible = true;
picWitness.Visible = true;
lblWitness.Text = "Witness\n" + memberProfile;
lblSuretyMemberID_3.Text = memberID;
if (memberPic != null || memberPic == string.Empty)
{
picWitness.Image = Image.FromFile(paths + "//photos//" + memberPic.ToString());
}
break;
}//end of Switch
}
else
{
MessageBox.Show("Sorry, there is no member with the File No. ["+ memberFileNo +"]", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
switch (strSender)
{
case "Surety1":
txtSuretyFileNo1.Clear();
break;
case "Surety2":
txtSuretyFileNo2.Clear();
break;
case "Witness":
txtWitnessFileNo.Clear();
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtSuretyFileNo2_Leave(object sender, EventArgs e)
{
string strSender = "Surety2";
if (txtSuretyFileNo2.Text != String.Empty)
{
if (txtSuretyFileNo2.Text != cboFileNo.Text && txtSuretyFileNo1.Text != txtSuretyFileNo2.Text && txtSuretyFileNo2.Text != txtWitnessFileNo.Text)
{
getSuretyData(strSender, txtSuretyFileNo2.Text);
}
else
{
MessageBox.Show("Surety cannot be same person as the recipient, surety or witness", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSuretyFileNo2.Text = string.Empty;
}
}
}
private void txtWitnessFileNo_Leave(object sender, EventArgs e)
{
string strSender = "Witness";
if (txtWitnessFileNo.Text != string.Empty)
{
if (txtWitnessFileNo.Text != cboFileNo.Text && txtSuretyFileNo1.Text != txtWitnessFileNo.Text && txtSuretyFileNo2.Text != txtWitnessFileNo.Text)
{
getSuretyData(strSender, txtWitnessFileNo.Text);
}
else
{
MessageBox.Show("Witness cannot be same person as the recipient or surety", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtWitnessFileNo.Text = string.Empty;
}
}
}
private void txtAmount_Leave(object sender, EventArgs e)
{
if (CheckForNumber.isNumeric(txtAmount.Text.Trim()))
{
txtAmount.Text = CheckForNumber.formatCurrency(txtAmount.Text.Trim());
}
}
private void chkStartRepayment_CheckedChanged(object sender, EventArgs e)
{
if (chkStartRepayment.Checked == true)
{
cboStartRepaymentMonth.Enabled = true;
cboStartRepaymentYear.Enabled = true;
}
else
{
cboStartRepaymentMonth.Enabled = false;
cboStartRepaymentYear.Enabled = false;
}
}
private void cboStartRepaymentYear_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboYear.Text != string.Empty)
{
if (Convert.ToInt32(cboStartRepaymentYear.Text) < (Convert.ToInt32(cboYear.Text)))
{
MessageBox.Show("Sorry, the entry is Invalid. It is a Date in the Past.", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
cboStartRepaymentYear.Text = cboYear.Text;
}
}
else
{
MessageBox.Show("Set the Date for the Loan Application", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnSaveApplication_Click(object sender, EventArgs e)
{
bool fieldVerifierSuccess = true;
fieldVerifierSuccess = fieldVerification();
if (fieldVerifierSuccess == true)
{
DialogResult result = MessageBox.Show("Do you confirm this application and wish to save it?", "Loan Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
saveLoanApplication();
}
}
}
private bool fieldVerification()
{
bool verificationStatus = true;
string errMessage = string.Empty;
if (cboFileNo.Text == "-- Select a File No. --")
{
errMessage += "Specify Member Applying for the Loan by entering Member File No.\n";
}
if (cboCategory.Text == "-- Select a Loan Category --")
{
errMessage += "Select a Loan Category and then pick a Loan Type\n";
}
if (cboType.Text == "-- Select a Loan Type --")
{
errMessage += "Select a Loan Type for this application\n";
}
if (txtAmount.Text == string.Empty)
{
errMessage += "No Loan Amount has been specified\n";
}
if (!CheckForNumber.isNumeric(txtAmount.Text))
{
errMessage += "Loan Amount is in invalid format\n";
}
if (txtFormFee.Text == string.Empty || (!CheckForNumber.isNumeric(txtFormFee.Text)))
{
errMessage += "Form Fee is in invalid format\n";
}
if (errMessage != string.Empty)
{
verificationStatus = false;
MessageBox.Show(errMessage, "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return verificationStatus;
}
private void saveLoanApplication()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into LoanApplication(AppMonth,AppYear,MemberID,LoanCategoryID,LoanTypeID," +
"LoanAmount,FormFee,StartRepaymentMonth,StartRepaymentYear,SuretyMemberID1,SuretyMemberID2,WitnessMemberID," +
"NonMemberSurety1,NonMemberSurety2,NonMemberWitness,LoanDuration,InterestRate,InterestAmount," +
"TotalRepayment,MonthlyRepayment,TransactionID)values(@AppMonth,@AppYear,@MemberID,@LoanCategoryID,@LoanTypeID,"+
"@LoanAmount,@FormFee,@StartRepaymentMonth,@StartRepaymentYear,@SuretyMemberID1,@SuretyMemberID2,@WitnessMemberID,"+
"@NonMemberSurety1,@NonMemberSurety2,@NonMemberWitness,@LoanDuration,@InterestRate,@InterestAmount,"+
"@TotalRepayment,@MonthlyRepayment,@TransactionID)";
string transactionID = "LOA" + DateTime.Now.ToString("ddMMyyhhmmss");
SqlCommand cmd = new SqlCommand(strQuery,conn);
#region parameters
cmd.Parameters.Add("@AppMonth", SqlDbType.Int);
cmd.Parameters["@AppMonth"].Value = DateFunction.getMonthByDate(cboMonth.Text);
cmd.Parameters.Add("@AppYear", SqlDbType.Int);
cmd.Parameters["@AppYear"].Value = Convert.ToInt32(cboYear.Text);
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@LoanCategoryID", SqlDbType.Int);
cmd.Parameters["@LoanCategoryID"].Value = Convert.ToInt32(cboCategory.SelectedValue.ToString());
cmd.Parameters.Add("@LoanTypeID", SqlDbType.Int);
cmd.Parameters["@LoanTypeID"].Value = Convert.ToInt32(cboType.SelectedValue.ToString());
cmd.Parameters.Add("@LoanAmount", SqlDbType.Decimal);
cmd.Parameters["@LoanAmount"].Value = Convert.ToDecimal(txtAmount.Text);
cmd.Parameters.Add("@FormFee", SqlDbType.Decimal);
cmd.Parameters["@FormFee"].Value = Convert.ToDecimal(txtFormFee.Text);
int startRepaymentMonth = 0;
int startRepaymentYear = 0;
if ((chkStartRepayment.Checked == true) && (cboStartRepaymentMonth.Text != string.Empty) && (cboStartRepaymentYear.Text != string.Empty))
{
startRepaymentMonth = DateFunction.getMonthByDate(cboStartRepaymentMonth.Text);
startRepaymentYear = Convert.ToInt32(cboStartRepaymentYear.Text);
}
else
{
//DateTime currentDate = DateTime.Now;
//int currentMonth = currentDate.Month;
string strAppDate = cboMonth.Text + " " + cboYear.Text;
DateTime appDate = DateTime.Parse(strAppDate);
DateTime nextMonth = appDate.AddMonths(1);
startRepaymentMonth = nextMonth.Month;
startRepaymentYear = nextMonth.Year;
}
cmd.Parameters.Add("@StartRepaymentMonth", SqlDbType.Int);
cmd.Parameters["@StartRepaymentMonth"].Value = startRepaymentMonth;
cmd.Parameters.Add("@StartRepaymentYear", SqlDbType.Int);
cmd.Parameters["@StartRepaymentYear"].Value = startRepaymentYear;
cmd.Parameters.Add("@SuretyMemberID1", SqlDbType.NVarChar,10);
cmd.Parameters["@SuretyMemberID1"].Value = lblSuretyMemberID_1.Text;
cmd.Parameters.Add("@SuretyMemberID2", SqlDbType.NVarChar,10);
cmd.Parameters["@SuretyMemberID2"].Value = lblSuretyMemberID_2.Text;
cmd.Parameters.Add("@WitnessMemberID", SqlDbType.NVarChar,10);
cmd.Parameters["@WitnessMemberID"].Value = lblSuretyMemberID_3.Text;
cmd.Parameters.Add("@NonMemberSurety1", SqlDbType.NVarChar, 100);
cmd.Parameters["@NonMemberSurety1"].Value = txtSuretyName1.Text;
cmd.Parameters.Add("@NonMemberSurety2", SqlDbType.NVarChar, 100);
cmd.Parameters["@NonMemberSurety2"].Value = txtSuretyName2.Text;
cmd.Parameters.Add("@NonMemberWitness", SqlDbType.NVarChar, 100);
cmd.Parameters["@NonMemberWitness"].Value = txtWitnessName.Text;
cmd.Parameters.Add("@LoanDuration", SqlDbType.Int);
cmd.Parameters["@LoanDuration"].Value = Convert.ToInt32(txtLoanDuration.Text);
cmd.Parameters.Add("@InterestRate", SqlDbType.Decimal);
cmd.Parameters["@InterestRate"].Value = Convert.ToDecimal(txtLoanInterestRate.Text);
cmd.Parameters.Add("@InterestAmount", SqlDbType.Decimal);
cmd.Parameters["@InterestAmount"].Value = Convert.ToDecimal(txtInterestAmount.Text);
cmd.Parameters.Add("@TotalRepayment", SqlDbType.Decimal);
cmd.Parameters["@TotalRepayment"].Value = Convert.ToDecimal(txtTotalRepaymentAmount.Text);
cmd.Parameters.Add("@MonthlyRepayment", SqlDbType.Decimal);
cmd.Parameters["@MonthlyRepayment"].Value = Convert.ToDecimal(txtMonthRepayment.Text);
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("Loan Application has been Successfully saved.", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
clearAllFields();
string ActivityType = "Loan Application";
string Description = "Loan Application of " + cboType.Text + ". Amount: " + txtAmount.Text + " for " + cboFileNo.Text + " with TransactionID: " + transactionID;
ActivityLog.logActivity(userId, ActivityType, Description);
}
else
{
MessageBox.Show("An error has occurred!", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}finally
{
conn.Close();
}
}
private void clearAllFields()
{
DateTime appDate = DateTime.Now;
lblAppMonthYear.Text = "Loan Application for " + appDate.ToString("MMMM, yyyy");
//MessageBox.Show(DateFunction.getMonthByName(appDate.Month));
cboMonth.Text = DateFunction.getMonthByName(appDate.Month);
cboYear.Text = appDate.Year.ToString();
cboFileNo.SelectedIndex = 0;
cboCategory.SelectedIndex = 0;
cboType.Text = string.Empty;
txtAmount.Text = string.Empty;
chkStartRepayment.Checked = false;
cboStartRepaymentMonth.Text = string.Empty;
cboStartRepaymentYear.Text = string.Empty;
txtSuretyFileNo1.Text = string.Empty;
txtSuretyFileNo2.Text = string.Empty;
txtWitnessFileNo.Text = string.Empty;
chkSurety1.Checked = false;
txtSuretyName1.Text = string.Empty;
chkSurety2.Checked = false;
txtSuretyName2.Text = string.Empty;
chkWitness.Checked = false;
txtWitnessName.Text = string.Empty;
picMember.Image = Image.FromFile(paths + "//photos//profile_img.png");
lblMemberProfile.Text = string.Empty;
lblMemberProfile.Visible = false;
txtLoanDuration.Text = string.Empty;
txtLoanInterestRate.Text = string.Empty;
txtInterestAmount.Text = string.Empty;
txtTotalRepaymentAmount.Text = string.Empty;
txtMonthRepayment.Text = string.Empty;
txtEndRepaymentDate.Text = string.Empty;
picSurety1.Image = Image.FromFile(paths + "//photos/profile_img.png");
picSurety1.Visible = false;
lblSurety1.Text = string.Empty;
lblSurety1.Visible = false;
lblSuretyMemberID_1.Text = string.Empty;
lblSuretyMemberID_1.Visible = false;
picSurety2.Image = Image.FromFile(paths + "//photos/profile_img.png");
picSurety2.Visible = false;
lblSurety2.Text = string.Empty;
lblSurety2.Visible = false;
lblSuretyMemberID_2.Text = string.Empty;
lblSuretyMemberID_2.Visible = false;
picWitness.Image = Image.FromFile(paths + "//photos/profile_img.png");
picWitness.Visible = false;
lblWitness.Text = string.Empty;
lblWitness.Visible = false;
lblSuretyMemberID_3.Text = string.Empty;
lblSuretyMemberID_3.Visible = false;
}
private void lblSurety2_Click(object sender, EventArgs e)
{
}
private void txtFormFee_Leave(object sender, EventArgs e)
{
txtFormFee.Text = CheckForNumber.formatCurrency2(txtFormFee.Text);
}
}
}
<file_sep>/MainApp/MainApp/Savings/EditMemberSavings.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditMemberSavings : Form
{
int myselectedmemberID = 0;
public EditMemberSavings()
{
InitializeComponent();
}
private void EditMemberSavings_Load(object sender, EventArgs e)
{
//Setting ListView Properties
lstVSavings.View = View.Details;
lstVSavings.FullRowSelect = true;
//Setting Columns
lstVSavings.Columns.Add("ID", 0);
lstVSavings.Columns.Add("Savings Type", 250);
lstVSavings.Columns.Add("Amount", 200);
lstVSavings.Columns.Add("Date Created", 200);
txtAmount.TextAlign = HorizontalAlignment.Right;
}
private void txtFileNo_TextChanged(object sender, EventArgs e)
{
if (txtFileNo.Text != string.Empty)
{
btnFindMember.Enabled = true;
}
else
{
btnFindMember.Enabled = false;
}
}
private void btnFindMember_Click(object sender, EventArgs e)
{
clearAndSetControls();
decimal totalSavings = 0;
SqlConnection conn = ConnectDB.GetConnection();
/** - Modified about First Meeting
string strSharesQuery = "Select m.MemberID, m.FileNo, s.SharesID, s.Shares, s.DateCreated from Members m " +
"inner join Shares s on m.MemberID=s.MemberID where m.FileNo='" + txtFileNo.Text.Trim() + "'";
* **/
string strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as [FullName], m.Photo, m.DateCreated as RegDateCreated," +
"t.SavingsName, s.SavingsAcctID, s.Amount, s.Remark, s.DateCreated as SavingsDateCreated from Members m left outer join MemberSavingsTypeAcct s on m.MemberID=s.MemberID " +
"left outer join SavingsType t on s.SavingsTypeID=t.SavingsTypeID where m.FileNo='" + txtFileNo.Text.Trim() + "'";
//SqlCommand cmdShares = new SqlCommand(strSharesQuery, conn);
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
lstVSavings.Items.Clear();
/** Modified after first meeting....Shares is type of Savings
SqlDataReader reader = cmdShares.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
string[] row = { reader["SharesID"].ToString(), "Shares", CheckForNumber.formatCurrency(reader["Shares"].ToString()), string.Format("{0:ddd, MMM d, yyyy}", reader["DateCreated"]) };
ListViewItem item = new ListViewItem(row);
lstVSavings.Items.Add(item);
}
}
reader.Close();
* */
int counter = 0;
string paths = PhotoPath.getPath();
//MessageBox.Show(Application.StartupPath.ToString());
//MessageBox.Show(paths.ToString());
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
picMember.Visible = true;
lblMemberProfileInfo.Visible = true;
lblRegistrationDate.Visible = true;
while (reader.Read())
{
string[] row = { reader["SavingsAcctID"].ToString(), reader["Remark"].ToString(), CheckForNumber.formatCurrency(reader["Amount"].ToString()), string.Format("{0:ddd, MMM d, yyyy}", reader["RegDateCreated"]) };
ListViewItem item = new ListViewItem(row);
lstVSavings.Items.Add(item);
counter++;
totalSavings += Convert.ToDecimal(reader["Amount"]);
if (counter == 1)
{
if (reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
lblMemberProfileInfo.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
lblRegistrationDate.Text = "Member since " + string.Format("{0:ddd, MMM d, yyyy}", reader["RegDateCreated"]);
myselectedmemberID = (int)reader["MemberID"];
}
}
}
else
{
clearAndSetControls();
MessageBox.Show("Sorry, Record with File No. [" + txtFileNo.Text + "] is not Found!" , "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
lblRecordNo.Text = "No. of Records: " + counter.ToString();
lblTotalSavings.Text = "Savings Total: " + CheckForNumber.formatCurrency2(totalSavings.ToString());
lblTotalSavings.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void clearAndSetControls()
{
picMember.Visible = false;
lblMemberProfileInfo.Visible = false;
lblRegistrationDate.Visible = false;
txtAmount.Clear();
txtAmount.Enabled = false;
txtComment.Clear();
txtComment.Enabled = false;
txtSavingsType.Clear();
btnUpdate.Enabled = false;
}
private void lstVSavings_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void lstVSavings_Click(object sender, EventArgs e)
{
txtSavingsType.Text = lstVSavings.SelectedItems[0].SubItems[1].Text;
txtAmount.Text = lstVSavings.SelectedItems[0].SubItems[2].Text;
btnUpdate.Enabled = true;
txtAmount.Enabled = true;
txtComment.Enabled = true;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lstVSavings.SelectedItems.Count == 0)
{
MessageBox.Show("Select a Savings Type to Edit Savings Amount", "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (txtAmount.Text == string.Empty)
{
MessageBox.Show("Amount is Required to Effect an Update", "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (CheckForNumber.isNumeric(txtAmount.Text))
{
updateMemberSavings();
}
else
{
MessageBox.Show("Amount Entered is Invalid", "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void txtAmount_TextChanged(object sender, EventArgs e)
{
}
private void txtAmount_Leave(object sender, EventArgs e)
{
txtAmount.Text = CheckForNumber.formatCurrency(txtAmount.Text.Trim());
}
private void updateMemberSavings()
{
SqlConnection conn = ConnectDB.GetConnection();
string savingsType = lstVSavings.SelectedItems[0].SubItems[1].Text;
string savingsID = lstVSavings.SelectedItems[0].SubItems[0].Text;
string amount = txtAmount.Text.Trim();
//string strUpdateShares = "Update Shares set Shares=@Shares where SharesID=@SharesID";
//SqlCommand cmdUpdateShares = new SqlCommand(strUpdateShares, conn);
#region cmd parameters
//cmdUpdateShares.Parameters.Add("@Shares", System.Data.SqlDbType.Decimal);
//cmdUpdateShares.Parameters["@Shares"].Value = amount;
//cmdUpdateShares.Parameters.Add("@SharesID", System.Data.SqlDbType.Int);
//cmdUpdateShares.Parameters["@SharesID"].Value = savingsID;
DateTime dateModified = DateTime.Now;
string strUpdateSavings = "Update MemberSavingsTypeAcct set Amount=@Amount, DateModified=@dateModified where SavingsAcctID=@SavingsAcctID";
SqlCommand cmdUpdateSavings = new SqlCommand(strUpdateSavings, conn);
cmdUpdateSavings.Parameters.Add("@Amount", System.Data.SqlDbType.Decimal);
cmdUpdateSavings.Parameters["@Amount"].Value = amount;
cmdUpdateSavings.Parameters.Add("@SavingsAcctID", System.Data.SqlDbType.Int);
cmdUpdateSavings.Parameters["@SavingsAcctID"].Value = savingsID;
cmdUpdateSavings.Parameters.Add("@dateModified", System.Data.SqlDbType.DateTime);
cmdUpdateSavings.Parameters["@dateModified"].Value = dateModified;
#endregion cmd parameters
try
{
conn.Open();
int rowAffected = 0;
rowAffected = cmdUpdateSavings.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("Savings Account has been Successfully Updated", "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
lstVSavings.SelectedItems[0].SubItems[2].Text = txtAmount.Text.Trim();
txtAmount.Clear();
txtComment.Clear();
txtAmount.Enabled = false;
txtComment.Enabled = false;
btnUpdate.Enabled = false;
lstVSavings.SelectedItems.Clear();
//recalculate totalSavings
decimal totalSavings = 0;
for (int i = 0; i < lstVSavings.Items.Count; i++)
{
totalSavings += Convert.ToDecimal(lstVSavings.Items[i].SubItems[2].Text.ToString());
}
lblTotalSavings.Text = "Savings Total: " + CheckForNumber.formatCurrency2(totalSavings.ToString());
}
else
{
MessageBox.Show("An Error has Occurred Updating Savings", "Edit Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/SavingsType/EditSavingsType.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
public partial class EditSavingsType : Form
{
Hashtable savings;
public EditSavingsType()
{
InitializeComponent();
}
private void EditSavingsType_Load(object sender, EventArgs e)
{
loadSavingsType();
}
private void loadSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsName, Description from SavingsType";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
savings = new Hashtable();
lstSavings.Items.Clear();
int countRecords = 0;
while (reader.Read())
{
lstSavings.Items.Add(reader["SavingsName"].ToString());
savings.Add(reader["SavingsName"].ToString(), reader["Description"].ToString());
countRecords++;
}
lblRecord.Text = "No. of Records: " + countRecords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void lstSavings_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstSavings.SelectedIndex != -1)
{
txtName.Text = lstSavings.SelectedItem.ToString();
txtDescription.Text = savings[lstSavings.SelectedItem].ToString();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lstSavings.SelectedIndex != -1)
{
if (txtName.Text != string.Empty)
{
performEditFunc();
}
else
{
MessageBox.Show("Savings Type Name is required!", "Edit Savings Type", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Select Savings Item to Effect an Edit", "Edit Savings Type", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void performEditFunc()
{
string selSavings = lstSavings.SelectedItem.ToString();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Update SavingsType set SavingsName=@Name, Description=@Description where SavingsName=@selSavings";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "SavingsName");
cmd.Parameters["@Name"].Value = txtName.Text.Trim();
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");
cmd.Parameters["@Description"].Value = txtDescription.Text.Trim();
cmd.Parameters.Add("@selSavings", SqlDbType.NVarChar, 50);
cmd.Parameters["@selsavings"].Value = selSavings;
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected>0)
{
MessageBox.Show("Savings Item '" + selSavings + "' has been successfully updated", "Edit Savings Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
btnCancel_Click(null,null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtName.Clear();
txtDescription.Clear();
loadSavingsType();
}
private void btnAll_Click(object sender, EventArgs e)
{
txtSearch.Clear();
loadSavingsType();
}
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsName, Description from SavingsType where SavingsName LIKE '%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
lstSavings.Items.Clear();
savings = new Hashtable();
int countRecords = 0;
while (reader.Read())
{
lstSavings.Items.Add(reader["SavingsName"].ToString());
savings.Add(reader["SavingsName"].ToString(), reader["Description"].ToString());
countRecords++;
}
lblRecord.Text = "No. of Records: " + countRecords;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Departments/ViewDepartments.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewDepartments : Form
{
public ViewDepartments()
{
InitializeComponent();
}
private void ViewDepartments_Load(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strSelectDept = "Select DepartmentName, Description from Departments";
SqlCommand cmdDept = new SqlCommand(strSelectDept, conn);
SqlDataAdapter da = new SqlDataAdapter(cmdDept);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Departments");
DataTable dt = ds.Tables["Departments"];
dtGrdDept.DataSource = dt;
lblTotalRecord.Text = "No. of Records: " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtSearch_KeyUp(object sender, EventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string searchDeptByName = txtSearch.Text;
if (searchDeptByName != string.Empty)
{
string strQuery = "Select DepartmentName,Description from Departments where DepartmentName LIKE '%" + searchDeptByName + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Departments");
conn.Close();
DataTable dt = ds.Tables["Departments"];
dtGrdDept.DataSource = dt;
dtGrdDept.Update();
dtGrdDept.Refresh();
lblTotalRecord.Text = "No. of Records: " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Department Name is required", "Search Department", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnAll_Click(object sender, EventArgs e)
{
ViewDepartments_Load(sender,e);
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
<file_sep>/MainApp/MainApp/Loans/EditLoansBroughtForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditLoansBroughtForward : Form
{
private string userId;
private string strInterestRate = string.Empty;
private string paymentStatus;
private string paymentFinished;
private string dateFinishedPayment;
string loanApplicationID;
string loanID;
public EditLoansBroughtForward(string UserID)
{
InitializeComponent();
this.userId = UserID;
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void EditLoansBroughtForward_Load(object sender, EventArgs e)
{
loadDataIntoGridView();
loadLoanCategory();
loadLoanType();
}
private void loadLoanCategory()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanCategoryID,Name from LoanCategory where LoanCategoryID in (Select LoanCategoryID from LoanApplication)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cboLoanCategory.DataSource = null;
try
{
conn.Open();
da.Fill(ds, "LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
DataRow row = dt.NewRow();
row["Name"] = "-- Select a Loan Category --";
dt.Rows.InsertAt(row, 0);
cboLoanCategory.DisplayMember = "Name";
cboLoanCategory.ValueMember = "LoanCategoryID";
cboLoanCategory.DataSource = dt;
cboLoanCategory.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadLoanType()
{
if (cboLoanCategory.SelectedIndex > 0)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanCategoryID, LoanTypeID,Type from LoanType where LoanCategoryID=" + cboLoanCategory.SelectedValue;
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanType");
DataTable dt = ds.Tables["LoanType"];
DataRow row = dt.NewRow();
row["Type"] = "-- Select a Loan Type --";
dt.Rows.InsertAt(row, 0);
cboLoanType.DisplayMember = "Type";
cboLoanType.ValueMember = "LoanTypeID";
cboLoanType.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void loadDataIntoGridView()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select l.LoansID,a.LoanApplicationID,m.FileNo,m.Title + ' ' + m.FirstName + ' ' + m.MiddleName + ' ' + m.LastName as 'Full Name'," +
"a.LoanAmount 'Amount', l.RepaymentAmount 'Repayment Amt.',l.AmountPaid 'Amt. Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status',l.PaymentFinished 'Payment Finished',l.DateFinishedPayment 'Finished Paying',l.TransactionID," +
"l.DateCreated 'Date' from LoanApplication a " +
"inner join Loans l on l.LoanApplicationID=a.LoanApplicationID " +
"inner join Members m on a.MemberID=m.MemberID " +
"where l.TransactionID LIKE '%LBF%' " +
"order by l.LoansID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
datGrdVwLoansForward.DataSource = dt;
datGrdVwLoansForward.Columns["LoansID"].Visible = false;
datGrdVwLoansForward.Columns["LoanApplicationID"].Visible = false;
datGrdVwLoansForward.Columns["Repayment Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Repayment Amt."].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Amt. Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Amt. Paid"].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["FileNo"].Width = 50;
datGrdVwLoansForward.Columns["Payment Status"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoansForward.Columns["Payment Finished"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoansForward.Columns["Payment Status"].Width = 80;
datGrdVwLoansForward.Columns["Payment Finished"].Width = 80;
datGrdVwLoansForward.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGrdVwLoansForward.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Select";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void datGrdVwLoansForward_CellClick(object sender, DataGridViewCellEventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
if (e.ColumnIndex == 0)
{
loanApplicationID = datGrdVwLoansForward.Rows[e.RowIndex].Cells[2].Value.ToString();
loanID = datGrdVwLoansForward.Rows[e.RowIndex].Cells[1].Value.ToString();
btnEnableEdit.Enabled = shouldEnableEdit();
string strQuery = "Select a.AppMonth,a.AppYear,a.StartRepaymentMonth,a.StartRepaymentYear,a.LoanCategoryID," +
"a.LoanTypeID,a.LoanAmount,a.InterestAmount,a.TotalRepayment,l.AmountPaid,a.MonthlyRepayment,a.LoanDuration, " +
"a.InterestRate,l.OutstandingAmount,l.PaymentStatus,l.PaymentFinished,l.DateFinishedPayment,l.Remark from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"where a.LoanApplicationID='" + loanApplicationID + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txtAmount.Text = CheckForNumber.formatCurrency2(reader["LoanAmount"].ToString());
txtInterest.Text = CheckForNumber.formatCurrency2(reader["InterestAmount"].ToString());
txtTotalRepayment.Text = CheckForNumber.formatCurrency2(reader["TotalRepayment"].ToString());
txtMonthlyRepayment.Text = CheckForNumber.formatCurrency2(reader["MonthlyRepayment"].ToString());
lblDuration.Text = CheckForNumber.formatCurrency2(reader["LoanDuration"].ToString());
lblInterestRate.Text = CheckForNumber.formatCurrency2(reader["InterestRate"].ToString());
txtAmountPaid.Text = CheckForNumber.formatCurrency2(reader["AmountPaid"].ToString());
txtOutstandingAmt.Text = CheckForNumber.formatCurrency2(reader["OutstandingAmount"].ToString());
txtRemark.Text = reader["Remark"].ToString();
cboLoanCategory.SelectedValue = reader["LoanCategoryID"].ToString();
loadLoanType();
cboLoanType.SelectedValue = reader["LoanTypeID"].ToString();
DateTime loanApplicationDate = new DateTime(Convert.ToInt16(reader["AppYear"].ToString()), Convert.ToInt16(reader["AppMonth"].ToString()), 1);
dtAppDate.Value = loanApplicationDate;
DateTime startRepayment = new DateTime(Convert.ToInt16(reader["StartRepaymentYear"].ToString()),Convert.ToInt16(reader["StartRepaymentMonth"].ToString()), 1);
dtStartRepayment.Value = startRepayment;
if (reader["PaymentFinished"].ToString() == "Yes")
{
dateFinishedPayment = reader["DateFinishedPayment"].ToString();
dtPickerPaymentFinished.Visible = true;
DateTime theFinishedPaymentDate = DateTime.Parse(dateFinishedPayment);
dtPickerPaymentFinished.Value = theFinishedPaymentDate;
}
else
{
dateFinishedPayment = string.Empty;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void btnEnableEdit_Click(object sender, EventArgs e)
{
groupBox2.Enabled = shouldEnableEdit();
}
private Boolean shouldEnableEdit()
{
Boolean resultEdit = false;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select count(*) from LoanRepayment where LoanID=@LoanID";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@LoanID", SqlDbType.Int);
cmd.Parameters["@LoanID"].Value = loanID;
try
{
conn.Open();
int recFound = Convert.ToInt16(cmd.ExecuteScalar());
if (recFound > 0)
{
MessageBox.Show("Selected Record cannot be Edited Since it Repayment has begun.", "Loans BF", MessageBoxButtons.OK, MessageBoxIcon.Information);
resultEdit = false;
groupBox2.Enabled = false;
btnEnableEdit.Enabled = false;
}
else
{
resultEdit = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return resultEdit;
}
private void cboLoanCategory_Leave(object sender, EventArgs e)
{
loadLoanType();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void txtInterest_Leave(object sender, EventArgs e)
{
}
private void txtAmount_Leave(object sender, EventArgs e)
{
if (txtAmount.Text != string.Empty && (CheckForNumber.isNumeric(txtAmount.Text)))
{
if (Convert.ToDecimal(txtAmount.Text) > 0)
{
txtAmountPaid.Enabled = true;
decimal loanAmount = Convert.ToDecimal(txtAmount.Text);
decimal interestRate = Convert.ToDecimal(lblInterestRate.Text);
string strDuration = lblDuration.Text;
decimal duration = decimal.Parse(strDuration);
decimal totalRepayment;
decimal monthlyRepayment;
decimal interestAmount = loanAmount * (interestRate / 100);
txtInterest.Text = CheckForNumber.formatCurrency2(interestAmount.ToString());
totalRepayment = loanAmount + interestAmount;
monthlyRepayment = totalRepayment / duration;
txtTotalRepayment.Text = CheckForNumber.formatCurrency2(totalRepayment.ToString());
txtAmount.Text = CheckForNumber.formatCurrency2(txtAmount.Text);
txtMonthlyRepayment.Text = CheckForNumber.formatCurrency2(monthlyRepayment.ToString());
}
else
{
txtAmountPaid.Enabled = false;
MessageBox.Show("The Amount is required to proceed", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
txtAmountPaid.Text = string.Empty;
txtAmountPaid.Enabled = false;
}
}
private void cboLoanType_Leave(object sender, EventArgs e)
{
}
private void cboLoanType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboLoanType.SelectedIndex == 0)
{
txtAmount.Enabled = false;
}
else
{
txtAmount.Enabled = true;
if (cboLoanType.SelectedIndex > 0)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID, Duration, InterestRate from LoanType " +
"where LoanTypeID=" + cboLoanType.SelectedValue.ToString();
SqlCommand cmd = new SqlCommand(strQuery, conn);
//MessageBox.Show(cboLoanType.SelectedValue.ToString());
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string strDuration = reader["Duration"].ToString();
strInterestRate = reader["InterestRate"].ToString();
string strBoth = strDuration + " Months | " + strInterestRate + "%";
lblDuration.Text = strDuration;
lblInterestRate.Text = strInterestRate;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
//calculate if amount is not empty
if ((txtAmount.Text !=string.Empty) && (CheckForNumber.isNumeric(txtAmount.Text)))
{
txtAmount_Leave(sender,e);
if ((txtAmountPaid.Text != string.Empty) && (CheckForNumber.isNumeric(txtAmountPaid.Text)))
{
txtAmountPaid_Leave(sender, e);
}
else
{
txtAmountPaid.Text = "0";
txtAmountPaid_Leave(sender, e);
}
}
}
}
}
private void txtAmountPaid_Leave(object sender, EventArgs e)
{
if (!FieldValidator.isBlank(txtAmountPaid.Text) && CheckForNumber.isNumeric(txtAmountPaid.Text))
{
decimal totalAmountRepayment = Convert.ToDecimal(txtTotalRepayment.Text);
decimal amountPaid = Convert.ToDecimal(txtAmountPaid.Text);
decimal outstandingAmount;
if (amountPaid > totalAmountRepayment)
{
MessageBox.Show("Sorry, that Amount Paid exceeds the Total Repayment Amount.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtAmountPaid.Text = string.Empty;
}
else
{
txtAmountPaid.Text = CheckForNumber.formatCurrency2(txtAmountPaid.Text);
outstandingAmount = totalAmountRepayment - amountPaid;
txtOutstandingAmt.Text = CheckForNumber.formatCurrency2(outstandingAmount.ToString());
//check outstanding amount and set paymentStatus
if (outstandingAmount == 0)
{
paymentStatus = "PAID";
paymentFinished = "Yes";
dateFinishedPayment = dtPickerPaymentFinished.Value.ToString();
lblPaymentFinishedDate.Visible = true;
dtPickerPaymentFinished.Visible = true;
}
else
{
paymentStatus = "Paying";
paymentFinished = "No";
dateFinishedPayment = string.Empty;
lblPaymentFinishedDate.Visible = false;
dtPickerPaymentFinished.Visible = false;
}
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you wish to update the record?", "Loans BF", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
executeEditLoansBF();
}
}
private void executeEditLoansBF()
{
if (txtAmount.Text != string.Empty && txtInterest.Text != string.Empty && txtTotalRepayment.Text != string.Empty && txtAmountPaid.Text != string.Empty && txtMonthlyRepayment.Text != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
conn.Open();
try
{
SqlTransaction sqlTrans = conn.BeginTransaction();
string QueryLoanApp = "Update LoanApplication set AppMonth=@AppMonth, AppYear=@AppYear,LoanCategoryID=@LoanCategoryID, " +
"LoanTypeID=@LoanTypeID,LoanAmount=@LoanAmount,StartRepaymentMonth=@StartRepaymentMonth,StartRepaymentYear=@StartRepaymentYear," +
"LoanDuration=@LoanDuration,InterestRate=@InterestRate,InterestAmount=@InterestAmount,TotalRepayment=@TotalRepayment, " +
"MonthlyRepayment=@MonthlyRepayment where LoanApplicationID=@LoanApplicationID";
SqlCommand cmd = new SqlCommand(QueryLoanApp, conn);
cmd.Transaction = sqlTrans;
//MessageBox.Show("Application ID: " + loanApplicationID.ToString());
#region parameters
cmd.Parameters.Add("@AppMonth", SqlDbType.Int);
cmd.Parameters["@AppMonth"].Value = dtAppDate.Value.Month.ToString();
cmd.Parameters.Add("@AppYear", SqlDbType.Int);
cmd.Parameters["@AppYear"].Value = dtAppDate.Value.Year.ToString();
cmd.Parameters.Add("@LoanCategoryID", SqlDbType.Int);
cmd.Parameters["@LoanCategoryID"].Value = cboLoanCategory.SelectedValue;
cmd.Parameters.Add("@LoanTypeID", SqlDbType.Int);
cmd.Parameters["@LoanTypeID"].Value = cboLoanType.SelectedValue;
cmd.Parameters.Add("@LoanAmount", SqlDbType.Decimal);
cmd.Parameters["@LoanAmount"].Value = txtAmount.Text;
cmd.Parameters.Add("@StartRepaymentMonth", SqlDbType.Int);
cmd.Parameters["@StartRepaymentMonth"].Value = dtStartRepayment.Value.Month.ToString();
cmd.Parameters.Add("@StartRepaymentYear", SqlDbType.Int);
cmd.Parameters["@StartRepaymentYear"].Value = dtStartRepayment.Value.Year.ToString();
cmd.Parameters.Add("@LoanDuration", SqlDbType.Int);
cmd.Parameters["@LoanDuration"].Value = lblDuration.Text;
cmd.Parameters.Add("@InterestRate", SqlDbType.Decimal);
cmd.Parameters["@InterestRate"].Value = lblInterestRate.Text;
cmd.Parameters.Add("@InterestAmount", SqlDbType.Decimal);
cmd.Parameters["@InterestAmount"].Value = txtInterest.Text;
cmd.Parameters.Add("@TotalRepayment", SqlDbType.Decimal);
cmd.Parameters["@TotalRepayment"].Value = txtTotalRepayment.Text;
cmd.Parameters.Add("@MonthlyRepayment", SqlDbType.Decimal);
cmd.Parameters["@MonthlyRepayment"].Value = txtMonthlyRepayment.Text;
cmd.Parameters.Add("@LoanApplicationID", SqlDbType.Int);
cmd.Parameters["@LoanApplicationID"].Value = loanApplicationID;
#endregion
int rowAffected_QueryLoanApp = cmd.ExecuteNonQuery();
MessageBox.Show("QueryLoanApp: " + rowAffected_QueryLoanApp.ToString());
string QueryLoans;
if (dateFinishedPayment != string.Empty)
{
QueryLoans = "Update Loans set RepaymentAmount=@RepaymentAmount,AmountPaid=@AmountPaid,OutstandingAmount=@OutstandingAmount, " +
"PaymentStatus=@PaymentStatus,PaymentFinished=@PaymentFinished,DateFinishedPayment=@DateFinishedPayment,Remark=@Remark " +
"where LoanApplicationID=@LoanApplicationID";
}
else
{
QueryLoans = "Update Loans set RepaymentAmount=@RepaymentAmount,AmountPaid=@AmountPaid,OutstandingAmount=@OutstandingAmount, " +
"PaymentStatus=@PaymentStatus,PaymentFinished=@PaymentFinished,Remark=@Remark " +
"where LoanApplicationID=@LoanApplicationID";
}
cmd.CommandText = QueryLoans;
//cmd.Transaction = sqlTrans;
#region parameters
cmd.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmd.Parameters["@RepaymentAmount"].Value = txtTotalRepayment.Text;
cmd.Parameters.Add("@AmountPaid", SqlDbType.Decimal);
cmd.Parameters["@AmountPaid"].Value = txtAmountPaid.Text;
cmd.Parameters.Add("@OutstandingAmount", SqlDbType.Decimal);
cmd.Parameters["@OutstandingAmount"].Value = txtOutstandingAmt.Text;
cmd.Parameters.Add("@PaymentStatus", SqlDbType.NVarChar, 10);
cmd.Parameters["@PaymentStatus"].Value = paymentStatus;
cmd.Parameters.Add("@PaymentFinished", SqlDbType.NVarChar, 5);
cmd.Parameters["@PaymentFinished"].Value = paymentFinished;
if (dateFinishedPayment != string.Empty)
{
cmd.Parameters.Add("@DateFinishedPayment", SqlDbType.Date);
cmd.Parameters["@DateFinishedPayment"].Value = DateTime.Parse(dateFinishedPayment);
}
cmd.Parameters.Add("@Remark", SqlDbType.NVarChar, 1000);
cmd.Parameters["@Remark"].Value = txtRemark.Text;
cmd.Parameters["@LoanApplicationID"].Value = loanApplicationID;
#endregion
int rowAffected_QueryLoans = cmd.ExecuteNonQuery();
MessageBox.Show("QueryLoans: " + rowAffected_QueryLoans.ToString());
if ((rowAffected_QueryLoanApp > 0) && (rowAffected_QueryLoans > 0))
{
sqlTrans.Commit();
MessageBox.Show("Record has been successfully edited.", "Loans Forward", MessageBoxButtons.OK, MessageBoxIcon.Information);
ActivityLog.logActivity(userId, "LoansForward", "Edit Loans Brought Forward with LoanApplication ID of " + loanApplicationID);
EditLoansBroughtForward editLoansBroughtForward = new EditLoansBroughtForward(userId);
editLoansBroughtForward.MdiParent = this.ParentForm;
editLoansBroughtForward.Show();
this.Close();
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error occurred editing record.", "Loans Forward", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}//end of if statement check
}
}
}
<file_sep>/MainApp/MainApp/SavingsType/CreateSavingsType.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class CreateSavingsType : Form
{
public CreateSavingsType()
{
InitializeComponent();
}
private void txtName_TextChanged(object sender, EventArgs e)
{
if (txtName.Text != string.Empty)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtName.Text != string.Empty)
{
addType();
loadSavingsRecords();
}
else
{
MessageBox.Show("Savings Type require a Name", "Add Savings Type", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void addType()
{
string typeName = txtName.Text.Trim();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into SavingsType(SavingsName,Description)values(@SavingsName,@Description)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@SavingsName",SqlDbType.NVarChar,50,"SavingsName");
cmd.Parameters["@SavingsName"].Value = txtName.Text.Trim();
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");
cmd.Parameters["@Description"].Value = txtDescription.Text.Trim();
try
{
conn.Open();
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
MessageBox.Show("Savings Type '" + typeName + "' has been successfully created", "Create Savings Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Dispose();
conn.Close();
}
}
private void CreateSavingsType_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'fUNAAB_CTCS.Banks' table. You can move, or remove it, as needed.
loadSavingsRecords();
}
private void loadSavingsRecords()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsName,Description from SavingsType";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingsType");
conn.Close();
DataTable dt = ds.Tables["SavingsType"];
grdSavingsType.DataSource = dt;
grdSavingsType.Columns[0].HeaderText = "Savings Name";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtName.Clear();
txtDescription.Clear();
}
}
}
<file_sep>/MainApp/MainApp/Classes/Departments.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace MainApp
{
public static class Departments
{
public static DataSet GetDepartmentList()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select DepartmentID, DepartmentName, Description from Departments order by DepartmentName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Departments");
}
catch(Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
return ds;
}
}
}
<file_sep>/MainApp/MainApp/Loans/LoanApplicationApproval.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class LoanApplicationApproval : Form
{
//string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
string paths = PhotoPath.getPath();
string strFilter;
public LoanApplicationApproval()
{
InitializeComponent();
}
private void groupBox5_Enter(object sender, EventArgs e)
{
}
private void LoanApplicationApproval_Load(object sender, EventArgs e)
{
this.Height = 378;
loadAllLoanApplications();
txtMemberProfile.TextAlign = HorizontalAlignment.Right;
}
private void loadAllLoanApplications()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select a.LoanApplicationID,mn.Month as [Month],a.AppYear as [Year],m.LastName as [Last Name],m.FirstName as [First Name],m.MiddleName as [Mid. Name]," +
"t.Type as [Loan Type], a.LoanAmount as [Amount],a.TransactionID as [Transaction ID], a.ApprovalStatus as Status, a.DatePosted as [Date] from LoanApplication a " +
"left join Members m on a.MemberID=m.MemberID " +
"left join MonthByName mn on a.AppMonth = mn.MonthID " +
"left join LoanType t on a.LoanTypeID=t.LoanTypeID order by LoanApplicationID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanApplication");
DataTable dt = ds.Tables["LoanApplication"];
if (dt.Rows.Count > 0)
{
datLoanApplicationGridView.DataSource = null;
datLoanApplicationGridView.Columns.Clear();
datLoanApplicationGridView.Rows.Clear();
datLoanApplicationGridView.Refresh();
datLoanApplicationGridView.DataSource = dt;
datLoanApplicationGridView.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datLoanApplicationGridView.Columns["Amount"].DefaultCellStyle.Format = "N2";
datLoanApplicationGridView.Columns["Year"].Width = 70;
datLoanApplicationGridView.Columns["Status"].Width = 70;
datLoanApplicationGridView.Columns["LoanApplicationID"].Visible = false;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datLoanApplicationGridView.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Select Record";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void datLoanApplicationGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
string transactionID = null;
string loanApplicationID = null;
//MessageBox.Show(e.ColumnIndex.ToString());
if (e.ColumnIndex == 0)
{
transactionID = datLoanApplicationGridView.Rows[e.RowIndex].Cells[9].Value.ToString();
loanApplicationID = datLoanApplicationGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
}
else if (e.ColumnIndex ==11)
{
transactionID = datLoanApplicationGridView.Rows[e.RowIndex].Cells[8].Value.ToString();
loanApplicationID = datLoanApplicationGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
}
if ((e.ColumnIndex==0) || (e.ColumnIndex==11))
{
getLoanApplicationDetails(transactionID, loanApplicationID);
datLoanApplicationGridView.Rows[e.RowIndex].Selected = true;
groupBox7.Visible = true;
}
//MessageBox.Show("Transaction ID: " + transactionID + "\nloanApplicationID: " + loanApplicationID);
}
private void getLoanApplicationDetails(string transactionID,string loanApplicationID)
{
txtApplicationID.Text = loanApplicationID;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select mn.Month as [AppMonth],a.AppYear as [AppYear],m.FileNo,m.LastName as [LastName],m.FirstName as [FirstName],m.MiddleName as [MiddleName], m.Photo," +
"c.Name as [LoanCategory],t.Type as [LoanType], a.LoanAmount as [Amount],a.TransactionID as [TransactionID],a.DatePosted as [Date], " +
"a.StartRepaymentMonth, a.StartRepaymentYear,a.SuretyMemberID1,a.SuretyMemberID2," +
"a.WitnessMemberID, a.NonMemberSurety1, a.NonMemberSurety2, a.NonMemberWitness, " +
"a.LoanDuration, a.InterestRate, a.InterestAmount, a.TotalRepayment, a.MonthlyRepayment, a.ApprovalStatus from LoanApplication a " +
"left join Members m on a.MemberID=m.MemberID " +
"left join MonthByName mn on a.AppMonth = mn.MonthID " +
"left join LoanCategory c on a.LoanCategoryID = c.LoanCategoryID " +
"left join LoanType t on a.LoanTypeID=t.LoanTypeID " +
"where TransactionID='" + transactionID + "' order by LoanApplicationID desc";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
txtApplicationDate.Text = reader["AppMonth"].ToString() + " " + reader["AppYear"].ToString();
txtCategory.Text = reader["LoanCategory"].ToString();
txtType.Text = reader["LoanType"].ToString();
txtAmount.Text = CheckForNumber.formatCurrency(reader["Amount"].ToString());
txtRepaymentDate.Text = DateFunction.getMonthByName(Convert.ToInt16(reader["StartRepaymentMonth"].ToString())) + " " + reader["StartRepaymentYear"].ToString();
txtTransactionID.Text = reader["TransactionID"].ToString();
txtDuration.Text = reader["LoanDuration"].ToString();
txtInterestRate.Text = CheckForNumber.formatCurrency(reader["InterestRate"].ToString());
txtInterestAmount.Text = CheckForNumber.formatCurrency(reader["InterestAmount"].ToString());
txtTotalRepayment.Text = CheckForNumber.formatCurrency(reader["TotalRepayment"].ToString());
txtMonthRepayment.Text = CheckForNumber.formatCurrency(reader["MonthlyRepayment"].ToString());
txtMemberProfile.Text = reader["LastName"] + " " + reader["FirstName"] + " " + reader["MiddleName"];
lblMemberFileNo.Text = reader["FileNo"].ToString();
if (reader["Photo"].ToString() == null || reader["Photo"].ToString() == string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
if ((reader["SuretyMemberID1"].ToString() != string.Empty))
{
getSuretyDetails(reader["SuretyMemberID1"].ToString(),"1");
}
else
{
lblSurety1.Text = "Surety 1\n" + reader["NonMemberSurety1"].ToString();
picSurety1.Image = Image.FromFile(paths + "//photos//profile_img.png");
}
if ((reader["SuretyMemberID2"].ToString() != string.Empty))
{
getSuretyDetails(reader["SuretyMemberID2"].ToString(), "2");
}
else
{
lblSurety2.Text = "Surety 2\n" + reader["NonMemberSurety2"].ToString();
picSurety2.Image = Image.FromFile(paths + "//photos//profile_img.png");
}
if ((reader["WitnessMemberID"].ToString() != string.Empty))
{
getSuretyDetails(reader["WitnessMemberID"].ToString(), "3");
}
else
{
lblWitness.Text = "Witness\n" + reader["NonMemberWitness"].ToString();
picWitness.Image = Image.FromFile(paths + "//photos//profile_img.png");
}
//MessageBox.Show(reader["ApprovalStatus"].ToString());
switch (reader["ApprovalStatus"].ToString().Trim())
{
case "":
lblApprovalStatus.Text = "Pending";
lblApprovalStatus.ForeColor = System.Drawing.Color.Black;
radYes.Checked = false;
radNo.Checked = false;
break;
case "Yes":
lblApprovalStatus.Text = "Loan Approved";
lblApprovalStatus.ForeColor = System.Drawing.Color.Green;
radYes.Checked = true;
break;
case "No":
lblApprovalStatus.Text = "Loan Not Approved";
lblApprovalStatus.ForeColor = System.Drawing.Color.Red;
radNo.Checked = true;
break;
}
//check/effect whether to enable or disable approval/disapproval box
DateTime today = DateTime.Now;
DateTime repaymentDate = DateTime.Parse(txtRepaymentDate.Text);
TimeSpan diffBeforeRepayment = today.Subtract(repaymentDate);
int daysBeforeRepayment = (int) diffBeforeRepayment.TotalDays;
if (daysBeforeRepayment >= 0)
{
grpApproval.Enabled = false;
}
else
{
grpApproval.Enabled = true;
}
//check the Application Details Section
this.Height = 591;
}
catch (Exception ex)
{
MessageBox.Show("getLoanApplicationDetails " + ex.Message);
}
finally
{
conn.Close();
}
}
private void getSuretyDetails(string surety, string suretyNo)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LastName + ' ' + FirstName + ' ' + MiddleName as FullName, Photo from Members where MemberID='" + surety + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
string memberPicture = string.Empty;
if (reader["Photo"].ToString() != null || reader["Photo"].ToString() == string.Empty)
{
memberPicture = paths + "//photos//" + reader["Photo"].ToString();
}
switch (suretyNo)
{
case "1":
lblSurety1.Text = "Surety 1\n" + reader["FullName"].ToString();
picSurety1.Image = Image.FromFile(memberPicture);
break;
case "2":
lblSurety2.Text ="Surety 2\n" + reader["FullName"].ToString();
picSurety2.Image = Image.FromFile(memberPicture);
break;
case "3":
lblWitness.Text = "Witness\n" + reader["FullName"].ToString();
picWitness.Image = Image.FromFile(memberPicture);
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnPerformAction_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you wish to perform this operation?", "Loan Application Status", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
if (radYes.Checked)
{
approveLoanOperation();
}
else if (radNo.Checked)
{
cancelLoanApproval();
}
}
}
private void approveLoanOperation()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into Loans(LoanApplicationID,RepaymentAmount,OutstandingAmount,TransactionID)" +
"values(@LoanApplicationID,@RepaymentAmount,@OutstandingAmount,@TransactionID)";
SqlCommand cmdInsert = new SqlCommand(strQuery, conn);
cmdInsert.Parameters.Add("@LoanApplicationID", SqlDbType.NVarChar, 50);
cmdInsert.Parameters["@LoanApplicationID"].Value = txtApplicationID.Text;
cmdInsert.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmdInsert.Parameters["@RepaymentAmount"].Value = Convert.ToDecimal(txtTotalRepayment.Text);
cmdInsert.Parameters.Add("@OutstandingAmount", SqlDbType.Decimal);
cmdInsert.Parameters["@OutstandingAmount"].Value = Convert.ToDecimal(txtTotalRepayment.Text);
cmdInsert.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmdInsert.Parameters["@TransactionID"].Value = txtTransactionID.Text;
string strUpdate = "Update LoanApplication set ApprovalStatus='Yes' where TransactionID='" +
txtTransactionID.Text + "' and LoanApplicationID=" + txtApplicationID.Text;
SqlCommand cmdUpate = new SqlCommand(strUpdate, conn);
SqlTransaction sqlTrans = null;
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
cmdInsert.Transaction = sqlTrans;
int rowsAffected = cmdInsert.ExecuteNonQuery();
if (rowsAffected > 0)
{
rowsAffected = 0;
cmdUpate.Transaction = sqlTrans;
rowsAffected = cmdUpate.ExecuteNonQuery();
if (rowsAffected > 0)
{
sqlTrans.Commit();
MessageBox.Show("The Selected Loan Application has been Approved", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblApprovalStatus.Text = "Loan is Approved";
lblApprovalStatus.ForeColor = System.Drawing.Color.Green;
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("An error has occurred", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
sqlTrans.Rollback();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cancelLoanApproval()
{
SqlConnection conn = ConnectDB.GetConnection();
string strCheck = "Select count(*) from Loans where TransactionID='" +
txtTransactionID.Text + "' and LoanApplicationID=" + txtApplicationID.Text;
SqlCommand cmdCheck = new SqlCommand(strCheck, conn);
string strDelete = "Delete from Loans where TransactionID='" +
txtTransactionID.Text + "' and LoanApplicationID=" + txtApplicationID.Text;
SqlCommand cmdDelete = new SqlCommand(strDelete, conn);
string strUpdate = "Update LoanApplication set ApprovalStatus='No' where TransactionID='" +
txtTransactionID.Text + "' and LoanApplicationID=" + txtApplicationID.Text;
SqlCommand cmdUpdate = new SqlCommand(strUpdate, conn);
SqlTransaction sqlTrans = null;
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
int rowsAffected;
bool boolOperationSuccess = true;
cmdCheck.Transaction = sqlTrans;
int recFound = (int) cmdCheck.ExecuteScalar();
if (recFound > 0)
{
cmdDelete.Transaction = sqlTrans;
rowsAffected = cmdDelete.ExecuteNonQuery();
if (rowsAffected==0)
{
boolOperationSuccess = false;
}
}
cmdUpdate.Transaction = sqlTrans;
rowsAffected = cmdUpdate.ExecuteNonQuery();
if (rowsAffected == 0)
{
boolOperationSuccess = false;
}
//check and perform the relevant operation
if (boolOperationSuccess == true)
{
sqlTrans.Commit();
MessageBox.Show("The Selected Loan has been Unapproved", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblApprovalStatus.Text = "Loan is Unapproved";
lblApprovalStatus.ForeColor = System.Drawing.Color.Red;
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred!", "Loan Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnOneDateSearch_Click(object sender, EventArgs e)
{
if ((cboSingleMonthSearch.Text != string.Empty) && (cboSingleYearSearch.Text != string.Empty))
{
strFilter = "where AppMonth=" + (cboSingleMonthSearch.SelectedIndex + 1) + " and AppYear=" + cboSingleYearSearch.Text;
}
else if ((cboSingleMonthSearch.Text != string.Empty) && (cboSingleYearSearch.Text == string.Empty))
{
strFilter = "where AppMonth=" + (cboSingleMonthSearch.SelectedIndex + 1);
}
else if ((cboSingleMonthSearch.Text == string.Empty) && (cboSingleYearSearch.Text != string.Empty))
{
strFilter = "where AppYear=" + cboSingleYearSearch.Text;
}
performSearchQuery(strFilter);
}
private void performSearchQuery(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select a.LoanApplicationID,mn.Month as [Month],a.AppYear as [Year],m.LastName as [Last Name],m.FirstName as [First Name],m.MiddleName as [Mid. Name]," +
"t.Type as [Loan Type], a.LoanAmount as [Amount],a.TransactionID as [Transaction ID], a.ApprovalStatus as Status, a.DatePosted as [Date] from LoanApplication a " +
"left join Members m on a.MemberID=m.MemberID " +
"left join MonthByName mn on a.AppMonth = mn.MonthID " +
"left join LoanType t on a.LoanTypeID=t.LoanTypeID " + strFilter + " order by LoanApplicationID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datLoanApplicationGridView.DataSource = null;
datLoanApplicationGridView.Columns.Clear();
datLoanApplicationGridView.Rows.Clear();
datLoanApplicationGridView.Refresh();
try
{
conn.Open();
da.Fill(ds, "LoanApplication");
DataTable dt = ds.Tables["LoanApplication"];
if (dt.Rows.Count > 0)
{
datLoanApplicationGridView.DataSource = dt;
datLoanApplicationGridView.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datLoanApplicationGridView.Columns["Amount"].DefaultCellStyle.Format = "N2";
datLoanApplicationGridView.Columns["LoanApplicationID"].Visible = false;
datLoanApplicationGridView.Columns["Year"].Width = 70;
datLoanApplicationGridView.Columns["Status"].Width = 70;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datLoanApplicationGridView.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Select Record";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnBetweenDateSearch_Click(object sender, EventArgs e)
{
if (cboFromMonth.Text!=string.Empty && cboFromYear.Text != string.Empty && cboToMonth.Text!=string.Empty && cboToYear.Text!=string.Empty)
{
int fromYear = Convert.ToInt16(cboFromYear.Text);
int toYear = Convert.ToInt16(cboToYear.Text);
if (toYear >= fromYear)
{
strFilter = "where AppMonth between " + (cboFromMonth.SelectedIndex + 1) + " and " + (cboToMonth.SelectedIndex + 1) +
" or AppYear between " + cboFromYear.Text + " and " + cboToYear.Text;
performSearchQuery(strFilter);
}
else
{
MessageBox.Show("Select the Dates in the proper order.", "Loan Application Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}else{
MessageBox.Show("Ensure to pick the Dates for the period to perform this search", "Loan Application Status", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnFileNoSearch_Click(object sender, EventArgs e)
{
if (txtFileNoSearch.Text != string.Empty)
{
string memberID = null;
//Check if the FileNo is genuine and exist. If it exist then retrieve the MemberID
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID,FileNo from Members where FileNo=@FileNo";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
cmd.Parameters.Add("@FileNo", SqlDbType.NVarChar,50);
cmd.Parameters["@FileNo"].Value = txtFileNoSearch.Text.Trim();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = reader["MemberID"].ToString();
strFilter = " where a.MemberID=" + memberID;
performSearchQuery(strFilter);
}
else
{
MessageBox.Show("Sorry, there is no Member with that File No.","Loan Application Status",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Enter Member File No. to make this Search", "Loan Application Status", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnTransactionIDSearch_Click(object sender, EventArgs e)
{
if (txtTransactionIDSearch.Text != string.Empty)
{
strFilter = "where a.TransactionID = '" + txtTransactionIDSearch.Text.Trim() + "'";
performSearchQuery(strFilter);
}
else
{
MessageBox.Show("Transaction ID must be supplied to perform\nthis search operation", "Loan Application Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStatusSearch_Click(object sender, EventArgs e)
{
if (cboStatus.Text != string.Empty)
{
if (cboStatus.SelectedIndex == 0)
{
strFilter = "where a.ApprovalStatus is NULL";
}
else if (cboStatus.SelectedIndex == 1)
{
strFilter = "where a.ApprovalStatus='Yes'";
}
else if (cboStatus.SelectedIndex == 2)
{
strFilter = "where a.ApprovalStatus='No'";
}
performSearchQuery(strFilter);
}
else
{
MessageBox.Show("Select a Status option to proceed with the search", "Loan Application Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void datLoanApplicationGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
<file_sep>/MainApp/MainApp/Withdrawal/DeleteWithdrawal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class DeleteWithdrawal : Form
{
private string UserId;
private string savingsID;
private string savingsType;
private string withdrawalAmt;
private string fileNo_Surname;
private string param_savingsType;
public DeleteWithdrawal(string userId)
{
InitializeComponent();
this.UserId = userId;
}
private void DeleteWithdrawal_Load(object sender, EventArgs e)
{
fileNo_Surname = string.Empty;
param_savingsType = string.Empty;
loadWithdrawals(fileNo_Surname,param_savingsType);
BuildTempSavingsAcctType.Create();
loadSavingsType();
}
private void loadSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string sqlQuery = "Select SavingsTypeID,SavingsName from TempSavingsAcctType";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try{
conn.Open();
da.Fill(ds, "TempSavingsAcctType");
DataTable dt = ds.Tables["TempSavingsAcctType"];
DataRow row = dt.NewRow();
row["SavingsName"] = "";
dt.Rows.InsertAt(row, 0);
cboSavingsType.DisplayMember = "SavingsName";
cboSavingsType.ValueMember = "SavingsTypeID";
cboSavingsType.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally{
conn.Close();
}
}
private void loadWithdrawals(string fileNo_Surname, string param_savingsType)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = null;
if (fileNo_Surname == string.Empty && param_savingsType == string.Empty)
{
strQuery = "Select sw.SavingsWithdrawalID 'ID',sw.SavingsID, m.FileNo 'File No.', m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as 'Full Name', " +
"st.SavingsName 'Account Type', sw.Amount, sw.WithdrawAmount 'Withdrawal Amt.', sw.Balance, s.TransactionID 'Transaction ID', s.Date " +
"from SavingsWithdrawal sw left join Savings s on s.SavingsID=sw.SavingsID " +
"left join Members m on m.MemberID=s.MemberID " +
"left join TempSavingsAcctType st on st.SavingsTypeID =sw.SavingsTypeID " +
"order by sw.SavingsWithdrawalID desc";
}
else if (fileNo_Surname != string.Empty && param_savingsType == string.Empty)
{
strQuery = "Select sw.SavingsWithdrawalID 'ID',sw.SavingsID, m.FileNo 'File No.', m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as 'Full Name', " +
"st.SavingsName 'Account Type', sw.Amount, sw.WithdrawAmount 'Withdrawal Amt.', sw.Balance, s.TransactionID 'Transaction ID', s.Date " +
"from SavingsWithdrawal sw left join Savings s on s.SavingsID=sw.SavingsID " +
"left join Members m on m.MemberID=s.MemberID " +
"left join TempSavingsAcctType st on st.SavingsTypeID =sw.SavingsTypeID " +
"where m.FileNo LIKE '%" + fileNo_Surname + "%' OR m.LastName LIKE '%" + fileNo_Surname + "%' " +
"order by sw.SavingsWithdrawalID desc";
}
else if (fileNo_Surname == string.Empty && param_savingsType != string.Empty)
{
strQuery = "Select sw.SavingsWithdrawalID 'ID',sw.SavingsID, m.FileNo 'File No.', m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as 'Full Name', " +
"st.SavingsName 'Account Type', sw.Amount, sw.WithdrawAmount 'Withdrawal Amt.', sw.Balance, s.TransactionID 'Transaction ID', s.Date " +
"from SavingsWithdrawal sw left join Savings s on s.SavingsID=sw.SavingsID " +
"left join Members m on m.MemberID=s.MemberID " +
"left join TempSavingsAcctType st on st.SavingsTypeID =sw.SavingsTypeID " +
"where sw.SavingsTypeID=" + param_savingsType + " " +
"order by sw.SavingsWithdrawalID desc";
}
else if (fileNo_Surname != string.Empty && param_savingsType != string.Empty)
{
strQuery = "Select sw.SavingsWithdrawalID 'ID',sw.SavingsID, m.FileNo 'File No.', m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as 'Full Name', " +
"st.SavingsName 'Account Type', sw.Amount, sw.WithdrawAmount 'Withdrawal Amt.', sw.Balance, s.TransactionID 'Transaction ID', s.Date " +
"from SavingsWithdrawal sw left join Savings s on s.SavingsID=sw.SavingsID " +
"left join Members m on m.MemberID=s.MemberID " +
"left join TempSavingsAcctType st on st.SavingsTypeID =sw.SavingsTypeID " +
"where sw.SavingsTypeID=" + param_savingsType + " " +
"And m.FileNo LIKE '%" + fileNo_Surname + "%' OR m.LastName LIKE '%" + fileNo_Surname + "%' " +
"order by sw.SavingsWithdrawalID desc";
}
//MessageBox.Show(strQuery);
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingsWithdrawal");
DataTable dt = ds.Tables["SavingsWithdrawal"];
dtGrdVwWithdrawal.DataSource = dt;
dtGrdVwWithdrawal.Columns["ID"].Width = 60;
dtGrdVwWithdrawal.Columns["Full Name"].Width = 200;
dtGrdVwWithdrawal.Columns["Account Type"].Width = 120;
dtGrdVwWithdrawal.Columns["Transaction ID"].Width = 120;
dtGrdVwWithdrawal.Columns["Withdrawal Amt."].Width = 120;
dtGrdVwWithdrawal.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwWithdrawal.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwWithdrawal.Columns["Withdrawal Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwWithdrawal.Columns["Withdrawal Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwWithdrawal.Columns["Balance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwWithdrawal.Columns["Balance"].DefaultCellStyle.Format = "N2";
dtGrdVwWithdrawal.Columns["SavingsID"].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (dtGrdVwWithdrawal.SelectedRows.Count > 0)
{
savingsID = dtGrdVwWithdrawal.SelectedRows[0].Cells[1].Value.ToString();
savingsType = dtGrdVwWithdrawal.SelectedRows[0].Cells[4].Value.ToString();
withdrawalAmt = dtGrdVwWithdrawal.SelectedRows[0].Cells[6].Value.ToString();
DialogResult res = MessageBox.Show("Do you wish to delete the selected record? savingsType ", "Withdrawal", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
ExecuteDeleteOps(savingsID);
}
}
else
{
MessageBox.Show("Select the Record you wish to Delete", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ExecuteDeleteOps(string savingsID)
{
SqlConnection conn = ConnectDB.GetConnection();
try
{
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = sqlTrans;
string strQuery1 = "Delete from SavingsWithdrawal where savingsID='" + savingsID + "'";
string strQuery2 = "Delete from Savings where savingsID='" + savingsID + "'";
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery1;
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
cmd.CommandText = strQuery2;
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
sqlTrans.Commit();
MessageBox.Show("The Selected Record has been deleted.", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Information);
string logMessage = "Withdrawal Record DELETED with Savings ID: " + savingsID + ", Savings Type: " + savingsType + ", Amount: " + withdrawalAmt;
ActivityLog.logActivity(UserId,"Withdrawal",logMessage);
DeleteWithdrawal deleteWithdrawal = new DeleteWithdrawal(UserId);
deleteWithdrawal.MdiParent = this.ParentForm;
deleteWithdrawal.Show();
this.Close();
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error occurred! Operation has been aborted.", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error occurred! Operation has been aborted.", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtFileNo_Surname_Leave(object sender, EventArgs e)
{
if (txtFileNo_Surname.Text != string.Empty)
{
fileNo_Surname = txtFileNo_Surname.Text.Trim();
loadWithdrawals(fileNo_Surname,param_savingsType);
}
}
private void cboSavingsType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSavingsType.SelectedIndex != 0)
{
param_savingsType = cboSavingsType.SelectedValue.ToString();
loadWithdrawals(fileNo_Surname, param_savingsType);
}
}
private void btnFilter_Click(object sender, EventArgs e)
{
fileNo_Surname = string.Empty;
param_savingsType = string.Empty;
if (txtFileNo_Surname.Text != string.Empty)
{
fileNo_Surname = txtFileNo_Surname.Text.Trim();
}
if (cboSavingsType.SelectedIndex != 0)
{
param_savingsType = cboSavingsType.SelectedValue.ToString();
}
if (fileNo_Surname != string.Empty || param_savingsType != string.Empty)
{
loadWithdrawals(fileNo_Surname, param_savingsType);
}
}
}
}
<file_sep>/MainApp/MainApp/Loans/ViewLoanApplication.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewLoanApplication : Form
{
private string strFilter = string.Empty;
private string loanApproval = string.Empty;
DataTable dt;
public ViewLoanApplication(string loanApproval)
{
InitializeComponent();
this.loanApproval = loanApproval;
}
private void ViewLoanApplication_Load(object sender, EventArgs e)
{
loadLoanApplications();
loadCategory();
loadType();
}
private void loadType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanTypeID, Type from LoanType";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanType");
DataTable dt = ds.Tables["LoanType"];
cboType.DisplayMember = "Type";
cboType.ValueMember = "LoanTypeID";
DataRow row = dt.NewRow();
row["Type"] = "";
dt.Rows.InsertAt(row, 0);
cboType.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadCategory()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanCategoryID, Name from LoanCategory";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
cboCategory.DisplayMember = "Name";
cboCategory.ValueMember = "LoanCategoryID";
DataRow row = dt.NewRow();
row["Name"] = "";
dt.Rows.InsertAt(row, 0);
cboCategory.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadLoanApplications()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = string.Empty;
lblAmountPaid.Text = "0";
lblOutstandingAmt.Text = "0";
lblRepaymentStatus.Text = string.Empty;
if (loanApproval == "Yes")
{
//If the loanApplication is Approved (Yes)
switch (strFilter)
{
case "":
strQuery = "Select a.LoanApplicationID, mon.Month 'Month',a.AppYear 'Year',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"lc.Name 'Category', lt.Type, a.LoanAmount 'Loan Amount', a.FormFee 'Form Fee', a.LoanDuration 'Duration',a.InterestRate 'Interest Rate',a.InterestAmount 'Interest Amt.',a.TotalRepayment 'Repayment',a.MonthlyRepayment 'Monthly',a.ApprovalStatus 'Approval', " +
"l.AmountPaid 'Amount Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status', a.TransactionID 'Transact ID',a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Members m on a.MemberID = m.MemberID " +
"left join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"left join MonthByName mon on a.AppMonth = mon.MonthID " +
"left join LoanCategory lc on a.LoanCategoryID = lc.LoanCategoryID " +
"left join LoanType lt on a.LoanTypeID = lt.LoanTypeID " +
"where a.ApprovalStatus='Yes' " +
"order by LoanApplicationID desc ";
break;
default:
strQuery = "Select a.LoanApplicationID, mon.Month 'Month',a.AppYear 'Year',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"lc.Name 'Category', lt.Type, a.LoanAmount 'Loan Amount', a.FormFee 'Form Fee', a.LoanDuration 'Duration',a.InterestRate 'Interest Rate',a.InterestAmount 'Interest Amt.',a.TotalRepayment 'Repayment',a.MonthlyRepayment 'Monthly',a.ApprovalStatus 'Approval', " +
"l.AmountPaid 'Amount Paid', l.OutStandingAmount 'Outstanding Amt.', l.PaymentStatus 'Payment Status', a.TransactionID 'Transact ID',a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Members m on a.MemberID = m.MemberID " +
"left join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"left join MonthByName mon on a.AppMonth = mon.MonthID " +
"left join LoanCategory lc on a.LoanCategoryID = lc.LoanCategoryID " +
"left join LoanType lt on a.LoanTypeID = lt.LoanTypeID " + strFilter +
"where a.ApprovalStatus='Yes' " +
"order by LoanApplicationID desc ";
break;
}
}
else
{
switch (strFilter)
{
case "":
strQuery = "Select a.LoanApplicationID, mon.Month 'Month',a.AppYear 'Year',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"lc.Name 'Category', lt.Type, a.LoanAmount 'Loan Amount', a.FormFee 'Form Fee', a.LoanDuration 'Duration',a.InterestRate 'Interest Rate',a.InterestAmount 'Interest Amt.',a.TotalRepayment 'Repayment',a.MonthlyRepayment 'Monthly',a.ApprovalStatus 'Approval', " +
"l.AmountPaid 'Amount Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status', a.TransactionID 'Transact ID',a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Members m on a.MemberID = m.MemberID " +
"left join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"left join MonthByName mon on a.AppMonth = mon.MonthID " +
"left join LoanCategory lc on a.LoanCategoryID = lc.LoanCategoryID " +
"left join LoanType lt on a.LoanTypeID = lt.LoanTypeID " +
"order by LoanApplicationID desc ";
break;
default:
strQuery = "Select a.LoanApplicationID, mon.Month 'Month',a.AppYear 'Year',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"lc.Name 'Category', lt.Type, a.LoanAmount 'Loan Amount', a.FormFee 'Form Fee', a.LoanDuration 'Duration',a.InterestRate 'Interest Rate',a.InterestAmount 'Interest Amt.',a.TotalRepayment 'Repayment',a.MonthlyRepayment 'Monthly',a.ApprovalStatus 'Approval', " +
"l.AmountPaid 'Amount Paid', l.OutStandingAmount 'Outstanding Amt.', l.PaymentStatus 'Payment Status', a.TransactionID 'Transact ID',a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Members m on a.MemberID = m.MemberID " +
"left join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"left join MonthByName mon on a.AppMonth = mon.MonthID " +
"left join LoanCategory lc on a.LoanCategoryID = lc.LoanCategoryID " +
"left join LoanType lt on a.LoanTypeID = lt.LoanTypeID " + strFilter +
"order by LoanApplicationID desc ";
break;
}
}
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//MessageBox.Show(strQuery);
try
{
conn.Open();
da.Fill(ds, "LoanApplication");
dt = ds.Tables["LoanApplication"];
datGrdVwLoanApplications.DataSource = dt;
datGrdVwLoanApplications.Columns["LoanApplicationID"].Visible = false;
datGrdVwLoanApplications.Columns["Full Name"].Width = 200;
datGrdVwLoanApplications.Columns["Year"].Width = 60;
datGrdVwLoanApplications.Columns["Approval"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoanApplications.Columns["Loan Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Loan Amount"].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Form Fee"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Form Fee"].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Interest Rate"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoanApplications.Columns["Duration"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoanApplications.Columns["Interest Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Interest Amt."].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Repayment"].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Monthly"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Monthly"].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Amount Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Amount Paid"].DefaultCellStyle.Format = "N2";
datGrdVwLoanApplications.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoanApplications.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
lblRecordNo.Text = "No. of Records : " + dt.Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtFileNo_Leave(object sender, EventArgs e)
{
if (txtFileNo.Text != string.Empty)
{
strFilter = " where m.FileNo='" + txtFileNo.Text + "' ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMonth.SelectedIndex != 0)
{
strFilter = " where a.AppMonth=" + cboMonth.SelectedIndex + " ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void datGrdVwLoanApplications_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (datGrdVwLoanApplications.SelectedRows.Count > 0)
{
lblAmountPaid.Text = string.Empty;
lblOutstandingAmt.Text = string.Empty;
lblRepaymentStatus.Text = string.Empty;
//MessageBox.Show(e.ColumnIndex.ToString());
string amountPaid = datGrdVwLoanApplications.SelectedRows[0].Cells[14].Value.ToString();
string outstanding = datGrdVwLoanApplications.SelectedRows[0].Cells[15].Value.ToString();
string repaymentStatus = datGrdVwLoanApplications.SelectedRows[0].Cells[16].Value.ToString();
//MessageBox.Show(amountPaid.ToString());
if (amountPaid != string.Empty)
{
lblAmountPaid.Text = CheckForNumber.formatCurrency2(amountPaid);
}
if (outstanding != string.Empty)
{
lblOutstandingAmt.Text = CheckForNumber.formatCurrency2(outstanding);
}
lblRepaymentStatus.Text = repaymentStatus;
if (amountPaid == string.Empty || outstanding == string.Empty)
{
btnViewDetails.Enabled = false;
}
else
{
btnViewDetails.Enabled = true;
}
}
}
private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboYear.SelectedIndex != 0)
{
strFilter = " where a.AppYear=" + cboYear.Text + " ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCategory.SelectedIndex != 0)
{
strFilter = " where a.LoanCategoryID=" + cboCategory.SelectedValue + " ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void cboType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboType.SelectedIndex != 0)
{
strFilter = " where a.LoanTypeID=" + cboType.SelectedValue + " ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void cboApproval_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboApproval.SelectedIndex != 0 && cboApproval.SelectedIndex != 3)
{
strFilter = " where a.ApprovalStatus='" + cboApproval.Text + "' ";
}
else if (cboApproval.SelectedIndex == 3)
{
strFilter = " where a.ApprovalStatus is NULL ";
}
else if (cboApproval.SelectedIndex == 0)
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void cboPayment_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPayment.SelectedIndex != 0)
{
strFilter = " where l.PaymentStatus='" + cboPayment.Text + "' ";
}
else
{
strFilter = string.Empty;
}
loadLoanApplications();
}
private void btnFilter_Click(object sender, EventArgs e)
{
strFilter = string.Empty;
#region constructing filter
if (txtFileNo.Text != string.Empty)
{
strFilter = " m.FileNo='" + txtFileNo.Text + "' ";
}
if (cboMonth.Text != string.Empty)
{
if (strFilter != string.Empty)
{
strFilter += " AND a.AppMonth=" + cboMonth.SelectedIndex + " ";
}
else
{
strFilter += " a.AppMonth=" + cboMonth.SelectedIndex + " ";
}
}
if (cboYear.Text != string.Empty)
{
if (strFilter != string.Empty)
{
strFilter += " AND a.AppYear=" + cboYear.Text + " ";
}
else
{
strFilter += " a.AppYear=" + cboYear.Text + " ";
}
}
if (cboCategory.Text != string.Empty)
{
if (strFilter != string.Empty)
{
strFilter += " AND a.LoanCategoryID=" + cboCategory.SelectedValue + " ";
}
else
{
strFilter += "a.LoanCategoryID=" + cboCategory.SelectedValue + " ";
}
}
if (cboType.Text != string.Empty)
{
if (strFilter != string.Empty)
{
strFilter += " AND a.LoanTypeID=" + cboType.SelectedValue + " ";
}
else
{
strFilter += " a.LoanTypeID=" + cboType.SelectedValue + " ";
}
}
if (cboPayment.Text != string.Empty)
{
if (strFilter != string.Empty)
{
strFilter += " AND l.PaymentStatus='" + cboPayment.Text + "' ";
}
else
{
strFilter += " l.PaymentStatus='" + cboPayment.Text + "' ";
}
}
if (cboApproval.Text != string.Empty)
{
if (strFilter != string.Empty)
{
if (cboApproval.SelectedIndex == 1 || cboApproval.SelectedIndex == 2)
{
strFilter += "AND a.ApprovalStatus='" + cboApproval.Text + "' ";
}
else
{
strFilter += " AND a.ApprovalStatus is NULL ";
}
}
else
{
if (cboApproval.SelectedIndex == 1 || cboApproval.SelectedIndex == 2)
{
strFilter += " a.ApprovalStatus='" + cboApproval.Text + "' ";
}
else
{
strFilter += " a.ApprovalStatus is NULL ";
}
}
}
#endregion
if (strFilter != string.Empty)
{
strFilter = "where " + strFilter;
}
loadLoanApplications();
}
private void btnReload_Click(object sender, EventArgs e)
{
string loanApproval = string.Empty;
ViewLoanApplication viewLoanApplication = new ViewLoanApplication(loanApproval);
viewLoanApplication.MdiParent = this.ParentForm;
viewLoanApplication.Show();
this.Close();
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
if (dt.Columns.Count > 0)
{
ExportData newExport = new ExportData();
newExport.ExportToExcel(dt, saveFD);
}
else
{
MessageBox.Show("There is no record to save", "View Loans", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnViewDetails_Click(object sender, EventArgs e)
{
if (datGrdVwLoanApplications.SelectedRows.Count > 0)
{
string loanID = datGrdVwLoanApplications.SelectedRows[0].Cells[0].Value.ToString();
ViewLoanDetails viewLoanDetails = new ViewLoanDetails(loanID);
viewLoanDetails.MdiParent = this.ParentForm;
viewLoanDetails.Show();
}
else
{
MessageBox.Show("Select a record to View Details","View Loan",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
}
}
<file_sep>/MainApp/MainApp/FUNAAB_CTCS.cs
namespace MainApp {
public partial class FUNAAB_CTCS {
}
}
<file_sep>/MainApp/MainApp/Settings/CreateLoanType.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class CreateLoanType : Form
{
public CreateLoanType()
{
InitializeComponent();
}
private void CreateLoanType_Load(object sender, EventArgs e)
{
loadLoanCategory();
loadCreatedLoanTypes();
}
private void loadLoanCategory()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "select LoanCategoryID, Name, Description, DateCreated as [Date Created] from LoanCategory";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanCategory");
DataTable dt = ds.Tables["LoanCategory"];
cboCategory.DisplayMember = "Name";
cboCategory.ValueMember = "LoanCategoryID";
DataRow row = dt.NewRow();
row["Name"] = "-- Select a Loan Category --";
dt.Rows.InsertAt(row, 0);
cboCategory.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadCreatedLoanTypes()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select c.Name as [Loan Category], t.Type, t.Duration as [Duration (Months)], t.InterestRate as [Interest Rate (%)], t.Description,t.DateCreated as [Date Created] " +
"from LoanType t left join LoanCategory c on c.LoanCategoryID=t.LoanCategoryID";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "LoanType");
DataTable dt = ds.Tables["LoanType"];
grdLoanType.DataSource = dt;
lblRecord.Text = "No. of Records: " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtName_TextChanged(object sender, EventArgs e)
{
if (txtType.Text != string.Empty)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//MessageBox.Show(cboCategory.SelectedValue.ToString());
if (cboCategory.SelectedValue.ToString() != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into LoanType(LoanCategoryID,Type,Duration,InterestRate,Description)values(@LoanCategoryID,@Type,@Duration,@InterestRate,@Description)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@LoanCategoryID", SqlDbType.Int);
cmd.Parameters["@LoanCategoryID"].Value = cboCategory.SelectedValue;
cmd.Parameters.Add("@Type", SqlDbType.NVarChar,50);
cmd.Parameters["@Type"].Value = txtType.Text.Trim();
cmd.Parameters.Add("@Duration", SqlDbType.NVarChar, 50);
cmd.Parameters["@Duration"].Value = numDuration.Value;
cmd.Parameters.Add("@InterestRate", SqlDbType.Decimal);
cmd.Parameters["@InterestRate"].Value = numInterestRate.Value;
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200);
cmd.Parameters["@Description"].Value = txtDescription.Text.Trim();
try
{
conn.Open();
int rowsAffected = 0;
rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Loan Type [" + txtType.Text + "] has been successfully created.", "Loan Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
clearFields();
loadCreatedLoanTypes();
}
else
{
MessageBox.Show("Sorry, an error has occurred", "Loan Type", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Sorry, Please select a Loan Category to proceed", "Loan Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void clearFields()
{
cboCategory.SelectedIndex = 0;
txtType.Text = string.Empty;
numDuration.Value = 1;
numInterestRate.Value = 0;
txtDescription.Text = string.Empty;
}
private void label4_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/MainApp/MainApp/Loans/PostLoanRepayment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class PostLoanRepayment : Form
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
int countLoanServicing;
int currentServicingLoan;
List<string> loanServicing;
string memberID;
string strFilter;
public PostLoanRepayment()
{
InitializeComponent();
}
private void btnFindLoanByFileNo_Click(object sender, EventArgs e)
{
bool isRecordFound = false;
isRecordFound = MemberAllApprovedLoans();
if (isRecordFound == true)
{
strFilter = "";
MemberRepaymentRecords(strFilter);
}
}
private bool MemberAllApprovedLoans()
{
bool isRecordFound = false;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select l.LoansID as [ID], l.TransactionID as [Transact. ID],m.Title + ' ' + m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as FullName, " +
"a.MemberID,m.photo,a.TotalRepayment as Repayment,l.AmountPaid as [Amt. Paid], l.OutstandingAmount as [Outstanding],a.ApprovalStatus,l.PaymentFinished " +
"from Loans l inner join LoanApplication a on l.TransactionID=a.TransactionID " +
"inner join Members m on a.MemberID=m.MemberID " +
"and a.ApprovalStatus='Yes' " +
"and m.FileNo='" + txtFileNo.Text + "' order by l.LoansID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
if (dt.Rows.Count > 0)
{
datGrdLoans.DataSource = null;
datGrdLoans.Columns.Clear();
datGrdLoans.Rows.Clear();
datGrdLoans.Refresh();
datGrdLoans.DataSource = dt;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGrdLoans.Columns.Add(btn);
btn.HeaderText = "Details";
btn.Text = "View";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
datGrdLoans.Columns["FullName"].Visible = false;
datGrdLoans.Columns["MemberID"].Visible = false;
datGrdLoans.Columns["Photo"].Visible = false;
datGrdLoans.Columns["ApprovalStatus"].Visible = false;
datGrdLoans.Columns["PaymentFinished"].Visible = false;
datGrdLoans.Columns["Id"].Width = 40;
datGrdLoans.Columns["Repayment"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["Amt. Paid"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["Outstanding"].DefaultCellStyle.Format = "N2";
datGrdLoans.Columns["Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdLoans.Columns["Amt. Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdLoans.Columns["Outstanding"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
//retrieve Member Photo
string memberPic = string.Empty;
string fullName = string.Empty;
//MessageBox.Show(datGrdLoans.Rows.Count.ToString());
countLoanServicing = datGrdLoans.Rows.Count;
loanServicing = new List<string>();
//clear List before beginning adding items.
loanServicing.Clear();
foreach (DataRow row in dt.Rows)
{
memberPic = row["Photo"].ToString();
fullName = row["FullName"].ToString();
memberID = row["MemberID"].ToString();
string paymentFinished = row["PaymentFinished"].ToString();
if (paymentFinished == string.Empty || paymentFinished != "Yes")
{
//MessageBox.Show(row["PaymentFinished"].ToString());
loanServicing.Add(row["Id"].ToString() + " - " + row["Transact. ID"].ToString());
}
}
if (memberPic != string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + memberPic);
}
MemberProfileInfo.Text = fullName + "\n" + txtFileNo.Text.ToUpper();
MemberProfileInfo.Visible = true;
//check if member has any loan to service
if (loanServicing.Count == 0)
{
MessageBox.Show("Currently no loan to service","Loan Repayment",MessageBoxButtons.OK,MessageBoxIcon.Information);
grpPostRepayment.Enabled = false;
gBoxServicingLoan.Visible = false;
}
else
{
//Read Out List of Loans Member is to Service
//MessageBox.Show(countLoanServicing.ToString());
grpPostRepayment.Enabled = true;
gBoxServicingLoan.Visible = true;
currentServicingLoan = loanServicing.Count - 1;
txtServicingLoan.Text = loanServicing[currentServicingLoan];
//MessageBox.Show(loanServicing[currentServicingLoan].ToString());
string servicingTransactionID = loanServicing[currentServicingLoan];
servicingTransactionID = servicingTransactionID.Substring(servicingTransactionID.IndexOf("-") + 1).Trim();
//MessageBox.Show(servicingTransactionID.ToString());
string strResult = "Select RepaymentAmount, AmountPaid, OutstandingAmount from Loans where TransactionID='" + servicingTransactionID + "'";
SqlCommand cmdResult = new SqlCommand(strResult, conn);
SqlDataReader reader = cmdResult.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
txtServicingRepaymentAmt.Text = CheckForNumber.formatCurrency(reader["RepaymentAmount"].ToString());
txtServicingAmtPaid.Text = CheckForNumber.formatCurrency(reader["AmountPaid"].ToString());
txtServicingOutstanding.Text = CheckForNumber.formatCurrency(reader["OutstandingAmount"].ToString());
}
}
}
//Record true if the searched Member exist
isRecordFound = true;
}
else
{
MessageBox.Show("Sorry, there is either no member with that File No. or\nThe member does not have Loan Information at the moment.", "Loans", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Record false if Member record does not exist
isRecordFound = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return isRecordFound;
}
private void MemberRepaymentRecords(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select LoanID,TransactionID,RepaymentAmount,PaidAmount,Outstanding,PaidCumulative,Excess,RepayTransactID as [Repayment TransactID],Remark,DatePosted " +
"from LoanRepayment where MemberID=@MemberID " + strFilter + " order by LoanRepaymentID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
SqlDataAdapter adt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adt.Fill(ds, "LoanRepayment");
DataTable dt = ds.Tables["LoanRepayment"];
datGrdRepayments.DataSource = dt;
datGrdRepayments.Columns["LoanID"].Width = 60;
datGrdRepayments.Columns["LoanID"].HeaderText = "ID";
datGrdRepayments.Columns["RepaymentAmount"].HeaderText = "Repayment Amount";
datGrdRepayments.Columns["RepaymentAmount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdRepayments.Columns["RepaymentAmount"].DefaultCellStyle.Format = "N2";
datGrdRepayments.Columns["PaidAmount"].HeaderText = "Paid Amount";
datGrdRepayments.Columns["PaidAmount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdRepayments.Columns["PaidAmount"].DefaultCellStyle.Format = "N2";
datGrdRepayments.Columns["Outstanding"].HeaderText = "Outstanding";
datGrdRepayments.Columns["Outstanding"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdRepayments.Columns["Outstanding"].DefaultCellStyle.Format = "N2";
datGrdRepayments.Columns["PaidCumulative"].HeaderText = "Paid Cumulative";
datGrdRepayments.Columns["PaidCumulative"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdRepayments.Columns["PaidCumulative"].DefaultCellStyle.Format = "N2";
datGrdRepayments.Columns["Excess"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdRepayments.Columns["Excess"].DefaultCellStyle.Format = "N2";
lblNumRepayments.Text = "Number of Records: " + dt.Rows.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void label12_Click(object sender, EventArgs e)
{
}
private void datGrdLoans_CellClick(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.ColumnIndex.ToString());
if (e.ColumnIndex == 10)
{
datGrdLoans.Rows[e.RowIndex].Selected = true;
string transactionID = datGrdLoans.Rows[e.RowIndex].Cells[1].Value.ToString();
string loanID = datGrdLoans.Rows[e.RowIndex].Cells[0].Value.ToString();
strFilter = "and LoanID =" + loanID ;
getSelectedLoanDetail(transactionID);
MemberRepaymentRecords(strFilter);
}
}
private void getSelectedLoanDetail(string transactionID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select l.LoansID as [Id], l.TransactionID as [Transact. ID], " +
"a.TotalRepayment, l.AmountPaid, l.OutstandingAmount, a.ApprovalStatus, " +
"a.StartRepaymentMonth, a.StartRepaymentYear, t.Type, t.Duration, t.InterestRate, a.LoanAmount, a.InterestAmount, a.MonthlyRepayment " +
"from Loans l inner join LoanApplication a on l.TransactionID=a.TransactionID " +
"left join LoanType t on a.LoanTypeID=t.LoanTypeID " +
"where a.ApprovalStatus='Yes' " +
"and a.TransactionID='" + transactionID + "' order by l.LoansID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
//MessageBox.Show(reader["StartRepaymentMonth"].ToString());
txtStartRepayment.Text = DateFunction.getMonthByName(Convert.ToInt32(reader["StartRepaymentMonth"])) + " " + reader["StartRepaymentYear"].ToString();
txtLoanType.Text = reader["Type"].ToString();
txtDuration.Text = reader["Duration"].ToString();
txtInterestRate.Text = reader["InterestRate"].ToString();
txtLoanAmount.Text = CheckForNumber.formatCurrency(reader["LoanAmount"].ToString());
txtRepaymentAmount.Text = CheckForNumber.formatCurrency(reader["TotalRepayment"].ToString());
txtInterestAmount.Text = CheckForNumber.formatCurrency(reader["InterestAmount"].ToString());
txtMonthlyRepayment.Text = CheckForNumber.formatCurrency(reader["MonthlyRepayment"].ToString());
txtAmountPaid.Text = CheckForNumber.formatCurrency(reader["AmountPaid"].ToString());
txtOutstanding.Text = CheckForNumber.formatCurrency(reader["OutstandingAmount"].ToString());
//alignment of controls
txtLoanAmount.TextAlign = HorizontalAlignment.Right;
txtRepaymentAmount.TextAlign = HorizontalAlignment.Right;
txtInterestAmount.TextAlign = HorizontalAlignment.Right;
txtMonthlyRepayment.TextAlign = HorizontalAlignment.Right;
txtAmountPaid.TextAlign = HorizontalAlignment.Right;
txtOutstanding.TextAlign = HorizontalAlignment.Right;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void PostLoanRepayment_Load(object sender, EventArgs e)
{
txtServicingRepaymentAmt.TextAlign = HorizontalAlignment.Right;
txtServicingAmtPaid.TextAlign = HorizontalAlignment.Right;
txtServicingOutstanding.TextAlign = HorizontalAlignment.Right;
}
private void txtPayAmount_Leave(object sender, EventArgs e)
{
if (CheckForNumber.isNumeric(txtPayAmount.Text))
{
txtPayAmount.Text = CheckForNumber.formatCurrency(txtPayAmount.Text);
btnPostRepayment.Enabled = true;
int loanSize = loanServicing.Count - 1;
int loopTimes = 0;
decimal amountToPay;
decimal totalRepaymentAmount;
decimal amountPaidAlready;
decimal outstanding;
decimal newOutstanding;
decimal newAmountPaid;
decimal excess = 0;
string servicingTransactionID = string.Empty;
totalRepaymentAmount = Convert.ToDecimal(txtServicingRepaymentAmt.Text);
amountPaidAlready = Convert.ToDecimal(txtServicingAmtPaid.Text);
amountToPay = Convert.ToDecimal(txtPayAmount.Text);
outstanding = totalRepaymentAmount - amountPaidAlready;
txtExtraFeedback.Text = string.Empty;
txtPaymentStatus.Text = string.Empty;
txtCalAmountPaid.Text = string.Empty;
while (loanSize >= 0)
{
loopTimes++;
if (amountToPay <= outstanding)
{
newAmountPaid = amountToPay + amountPaidAlready;
newOutstanding = totalRepaymentAmount - (newAmountPaid);
if (excess==0)
{
txtCalOutstanding.Text =CheckForNumber.formatCurrency(newOutstanding.ToString());
txtCalAmountPaid.Text = CheckForNumber.formatCurrency(newAmountPaid.ToString());
}
txtExtraFeedback.Text += "\n\n------------------------";
txtExtraFeedback.Text += servicingTransactionID + Environment.NewLine + "Repayment: " + CheckForNumber.formatCurrency(totalRepaymentAmount.ToString()) + Environment.NewLine;
txtExtraFeedback.Text += "Paying: " + CheckForNumber.formatCurrency(amountToPay.ToString()) + Environment.NewLine;
txtExtraFeedback.Text += "Outstanding: " + CheckForNumber.formatCurrency(newOutstanding.ToString()) + Environment.NewLine;
if (newOutstanding == 0)
{
txtPaymentStatus.Text = "Paid";
}
else
{
txtPaymentStatus.Text = "Paying";
}
break;
}
else
{
//newAmountPaid = amountToPay + totalRepaymentAmount;
decimal noteAmountPaid;
noteAmountPaid = amountToPay;
excess = amountToPay - outstanding;
amountToPay = excess;
//MessageBox.Show("Amount Paid: " + totalRepaymentAmount.ToString());
//MessageBox.Show("Excess: " + excess);
txtCalOutstanding.Text = "0.00";
txtCalAmountPaid.Text += totalRepaymentAmount + ", ";
txtPaymentStatus.Text = "Paid";
txtExtraFeedback.Text += "\n\n------------------------";
txtExtraFeedback.Text += servicingTransactionID + Environment.NewLine + "Repayment: " + CheckForNumber.formatCurrency(totalRepaymentAmount.ToString()) + Environment.NewLine;
txtExtraFeedback.Text += "Paying: " + CheckForNumber.formatCurrency(noteAmountPaid.ToString()) + Environment.NewLine;
txtExtraFeedback.Text += "Excess: " + CheckForNumber.formatCurrency(excess.ToString()) + Environment.NewLine;
}
loanSize--;
if (loanSize < 0)
{
if (excess > 0)
{
txtExtraFeedback.Text += "\n\n------------------------";
txtExtraFeedback.Text += "Savings Deposit: " + CheckForNumber.formatCurrency(excess.ToString());
}
break;
}
SqlConnection conn = ConnectDB.GetConnection();
servicingTransactionID = loanServicing[loanSize];
servicingTransactionID = servicingTransactionID.Substring(servicingTransactionID.IndexOf("-") + 1).Trim();
string strQuery2 = "Select RepaymentAmount,OutstandingAmount,AmountPaid from Loans where TransactionID='" + servicingTransactionID + "'";
SqlCommand cmdQuery = new SqlCommand(strQuery2, conn);
conn.Open();
SqlDataReader reader = cmdQuery.ExecuteReader();
reader.Read();
outstanding = Convert.ToDecimal(reader["OutstandingAmount"]);
totalRepaymentAmount = Convert.ToDecimal(reader["RepaymentAmount"]);
amountPaidAlready = Convert.ToDecimal(reader["AmountPaid"]);
}
}
else
{
txtCalAmountPaid.Clear();
txtCalOutstanding.Clear();
}
}
private void btnPostRepayment_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you wish to Post this Loan Repayment?", "Loans", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
#region Execute_Loan_Repayment
//declare and initialize variables
//MessageBox.Show("Member ID: " + memberID);
int loanSize = loanServicing.Count - 1;
#region declaration and initialisation
decimal amountPaying = 0;
decimal savedAmountPaying = 0;
decimal rePayment = 0;
decimal amountPaid = 0;
decimal newAmountPaid = 0;
decimal outstanding = 0;
decimal newOutstanding = 0;
decimal excess = 0;
string loanId;
string loanToService;
string transactionID;
string paymentStatus;
string paymentFinished;
DateTime dateFinishedPayment;
bool disContinueLoop = false;
string strQuery;
string strInsertRepayment;
string strUpdateLoan;
int rowsAffected;
bool dbOperationStatus = true;
#endregion end of declaration and initialisation
SqlConnection conn = ConnectDB.GetConnection();
SqlCommand cmdSelectLoans;
SqlCommand cmdInsertRepayment;
SqlCommand cmdUpdateLoan;
SqlDataReader reader;
SqlTransaction sqlTrans = null;
amountPaying = Convert.ToDecimal(txtPayAmount.Text);
string rePayTransactID = "PAY" + DateTime.Now.ToString("ddMMyyhhmmss");
//MessageBox.Show("RePayTransactID: " + rePayTransactID);
//Execute Loans Servicing
#region while section
while (loanSize >= 0)
{
//MessageBox.Show();
//MessageBox.Show("Loan item: " + loanSize.ToString() + " - " + loanServicing[loanSize]);
loanToService = loanServicing[loanSize];
loanId = loanToService.Substring(0, loanToService.IndexOf("-"));
transactionID = loanToService.Substring(loanToService.IndexOf("-") + 1).Trim();
//MessageBox.Show("Loan ID: " + loanId + " TransactionID: " + transactionID);
//Setup command to retrieve Loan Record
strQuery = "Select RepaymentAmount, AmountPaid, OutstandingAmount from Loans where LoansID='" + loanId +
"' and TransactionID='" + transactionID + "'";
cmdSelectLoans = new SqlCommand(strQuery, conn);
#region try section
try
{
//MessageBox.Show("Connection State: " + conn.State);
if (conn.State != ConnectionState.Open)
{
//MessageBox.Show("Db wasn't opened, it is now..");
conn.Open();
sqlTrans = conn.BeginTransaction();
}
//Execute cmdSelectLoans Command
cmdSelectLoans.Transaction = sqlTrans;
reader = cmdSelectLoans.ExecuteReader();
reader.Read();
rePayment = Convert.ToDecimal(reader["RepaymentAmount"]);
outstanding = Convert.ToDecimal(reader["OutstandingAmount"]);
amountPaid = Convert.ToDecimal(reader["AmountPaid"]);
//MessageBox.Show("Outstanding Loan: " + outstanding);
savedAmountPaying = amountPaying;
if (amountPaying <= outstanding)
{
newOutstanding = outstanding - amountPaying;
newAmountPaid = amountPaying + amountPaid;
excess = 0;
disContinueLoop = true;
}
else
{
excess = amountPaying - outstanding;
newOutstanding = 0;
newAmountPaid = rePayment;
amountPaying = excess;
}
reader.Close(); //close reader for cmdSelectLoans
//MessageBox.Show("New Outstanding: " + newOutstanding + "\nNew Amount Paid: " + newAmountPaid + "\nExcess: " + excess + "\nSaved Amount: " + savedAmountPaying);
//Begin Repayment subroutine
strInsertRepayment = "Insert into LoanRepayment(MemberID,LoanID,TransactionID,RepaymentAmount,PaidAmount,Outstanding,PaidCumulative,Excess,Remark,RepayTransactID)" +
"values(@MemberID,@LoanID,@TransactionID,@RepaymentAmount,@NewAmountPaid,@NewOutstanding,@PaidCumulative,@Excess,@Remark,@RepayTransactID)";
cmdInsertRepayment = new SqlCommand(strInsertRepayment, conn);
#region cmdInsertRepayment parameters
cmdInsertRepayment.Parameters.Add("@MemberID", SqlDbType.Int);
cmdInsertRepayment.Parameters["@MemberID"].Value = memberID;
cmdInsertRepayment.Parameters.Add("@LoanID", SqlDbType.Int);
cmdInsertRepayment.Parameters["@LoanID"].Value = Convert.ToInt32(loanId);
cmdInsertRepayment.Parameters.Add("@TransactionID", SqlDbType.VarChar, 50);
cmdInsertRepayment.Parameters["@TransactionID"].Value = transactionID;
cmdInsertRepayment.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmdInsertRepayment.Parameters["@RepaymentAmount"].Value = rePayment;
cmdInsertRepayment.Parameters.Add("@NewAmountPaid", SqlDbType.Decimal);
cmdInsertRepayment.Parameters["@NewAmountPaid"].Value = savedAmountPaying;
cmdInsertRepayment.Parameters.Add("@NewOutstanding", SqlDbType.Decimal);
cmdInsertRepayment.Parameters["@NewOutstanding"].Value = newOutstanding;
cmdInsertRepayment.Parameters.Add("@PaidCumulative", SqlDbType.Decimal);
cmdInsertRepayment.Parameters["@PaidCumulative"].Value = newAmountPaid;
cmdInsertRepayment.Parameters.Add("@Excess", SqlDbType.Decimal);
cmdInsertRepayment.Parameters["@Excess"].Value = excess;
cmdInsertRepayment.Parameters.Add("@Remark", SqlDbType.NVarChar, 100);
cmdInsertRepayment.Parameters["@Remark"].Value = txtRemark.Text.Trim();
cmdInsertRepayment.Parameters.Add("@RepayTransactID", SqlDbType.NVarChar, 50);
cmdInsertRepayment.Parameters["@RepayTransactID"].Value = rePayTransactID;
#endregion
cmdInsertRepayment.Transaction = sqlTrans;
rowsAffected = cmdInsertRepayment.ExecuteNonQuery();
if (rowsAffected < 1)
{
dbOperationStatus = false;
}
if (dbOperationStatus == false)
{
MessageBox.Show("An error has occurred and Operation has been terminated!", "Loan Repayment", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
else
{
//Begin Loan Update subroutine
strUpdateLoan = "Update Loans set AmountPaid=@NewAmountPaid, OutstandingAmount=@NewOutstandingAmount," +
"PaymentStatus=@PaymentStatus,PaymentFinished=@PaymentFinished,DateFinishedPayment=@DateFinishedPayment " +
"where LoansID=@LoanID and TransactionID=@TransactionID";
if (newOutstanding > 0)
{
//MessageBox.Show("PayStatus: Paying | PaymentFinished: No");
paymentStatus = "Paying";
paymentFinished = "No";
}
else
{
//MessageBox.Show("PayStatus: PAID | PaymentFinished: Yes");
paymentStatus = "PAID";
paymentFinished = "Yes";
}
cmdUpdateLoan = new SqlCommand(strUpdateLoan, conn);
#region cmdUpdateLoan parameters
cmdUpdateLoan.Parameters.Add("@NewAmountPaid", SqlDbType.Decimal);
cmdUpdateLoan.Parameters["@NewAmountPaid"].Value = newAmountPaid;
cmdUpdateLoan.Parameters.Add("@NewOutstandingAmount", SqlDbType.Decimal);
cmdUpdateLoan.Parameters["@NewOutstandingAmount"].Value = newOutstanding;
cmdUpdateLoan.Parameters.Add("@PaymentStatus", SqlDbType.NVarChar, 10);
cmdUpdateLoan.Parameters["@PaymentStatus"].Value = paymentStatus;
cmdUpdateLoan.Parameters.Add("@PaymentFinished", SqlDbType.NVarChar, 5);
cmdUpdateLoan.Parameters["@PaymentFinished"].Value = paymentFinished;
dateFinishedPayment = DateTime.Now;
cmdUpdateLoan.Parameters.Add("@DateFinishedPayment", SqlDbType.Date);
cmdUpdateLoan.Parameters["@DateFinishedPayment"].Value = dateFinishedPayment;
cmdUpdateLoan.Parameters.Add("@LoanID", SqlDbType.Int);
cmdUpdateLoan.Parameters["@LoanID"].Value = Convert.ToInt32(loanId);
cmdUpdateLoan.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmdUpdateLoan.Parameters["@TransactionID"].Value = transactionID;
#endregion
cmdUpdateLoan.Transaction = sqlTrans;
rowsAffected = cmdUpdateLoan.ExecuteNonQuery();
if (rowsAffected != 1)
{
dbOperationStatus = false;
}
}//end of try snippet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion end of try
loanSize--;
if (disContinueLoop == true && excess == 0)
{
break;
}
else if (loanSize < 0 && excess > 0)
{
//MessageBox.Show("Savings deposit: " + excess);
dbOperationStatus = depositExcessInSavings(excess, transactionID, conn, sqlTrans);
}
}
#endregion end of while section
//Close up database connection
if (dbOperationStatus == true)
{
sqlTrans.Commit();
txtServicingAmtPaid.Text = txtCalAmountPaid.Text;
txtServicingOutstanding.Text = txtCalOutstanding.Text;
MessageBox.Show("Repayment Operation is Successful", "Loan Repayment", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred!", "Loan Repayment", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
//MessageBox.Show("After Database Close, Db State: " + conn.State);
#endregion
clearFields();
bool isRecordFound = false;
isRecordFound = MemberAllApprovedLoans();
strFilter = "";
MemberRepaymentRecords(strFilter);
}
}
private void clearFields()
{
txtStartRepayment.Text = string.Empty;
txtLoanType.Text = string.Empty;
txtDuration.Text = string.Empty;
txtInterestRate.Text = string.Empty;
txtLoanAmount.Text = string.Empty;
txtRepaymentAmount.Text = string.Empty;
txtInterestAmount.Text = string.Empty;
txtMonthlyRepayment.Text = string.Empty;
txtAmountPaid.Text = string.Empty;
txtOutstanding.Text = string.Empty;
txtPayAmount.Text = string.Empty;
txtRemark.Text = string.Empty;
txtCalAmountPaid.Text = string.Empty;
txtCalOutstanding.Text = string.Empty;
txtPaymentStatus.Text = string.Empty;
txtExtraFeedback.Text = string.Empty;
}
private void txtPayAmount_TextChanged(object sender, EventArgs e)
{
if (CheckForNumber.isNumeric(txtPayAmount.Text) && (txtPayAmount.Text!=string.Empty))
{
btnPostRepayment.Enabled = true;
}
else
{
btnPostRepayment.Enabled = false;
}
}
private bool depositExcessInSavings(decimal excess, string transactionID, SqlConnection conn, SqlTransaction sqlTrans)
{
string strSavingsInsert = "Insert into Savings(MemberID,SavingSource,Amount,Month,Year,TransactionID)" +
"values(@MemberID,@SavingSource,@Amount,@Month,@Year,@TransactionID)";
SqlCommand cmdSavingsInsert = new SqlCommand(strSavingsInsert, conn);
#region cmdSavingsInsert Parameters
cmdSavingsInsert.Parameters.Add("@MemberID", SqlDbType.Int);
cmdSavingsInsert.Parameters["@MemberID"].Value = memberID;
cmdSavingsInsert.Parameters.Add("@SavingSource", SqlDbType.NVarChar, 40);
cmdSavingsInsert.Parameters["@SavingSource"].Value = "Loan";
cmdSavingsInsert.Parameters.Add("@Amount", SqlDbType.Decimal);
cmdSavingsInsert.Parameters["@Amount"].Value = excess;
DateTime currentDate = DateTime.Now;
int currentMonth = currentDate.Month;
int currentYear = currentDate.Year;
cmdSavingsInsert.Parameters.Add("@Month", SqlDbType.NVarChar, 5);
cmdSavingsInsert.Parameters["@Month"].Value = currentMonth.ToString();
cmdSavingsInsert.Parameters.Add("@Year", SqlDbType.NVarChar, 5);
cmdSavingsInsert.Parameters["@Year"].Value = currentYear.ToString();
cmdSavingsInsert.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 30);
cmdSavingsInsert.Parameters["@TransactionID"].Value = transactionID;
#endregion cmdSavingsInsert
bool operationStatus = true;
try
{
//conn.Open();
cmdSavingsInsert.Transaction = sqlTrans;
int rowAffected = cmdSavingsInsert.ExecuteNonQuery();
if (rowAffected != 1)
{
operationStatus = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return operationStatus;
}
}
}
<file_sep>/MainApp/MainApp/Deductions/ViewDeductions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewDeductions : Form
{
private string month;
private string year;
private string strFilter;
DataTable dt;
public ViewDeductions(string month, string year)
{
InitializeComponent();
this.month = month;
this.year = year;
this.strFilter = string.Empty;
}
private void ViewDeductions_Load(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = string.Empty;
//MessageBox.Show(month + ' ' + year);
if (month != string.Empty && year != string.Empty && strFilter==string.Empty)
{
strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted, d.DeductionID from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month " +
"where d.Month='" + month + "' and d.Year='" + year + "'";
}
else if (month != string.Empty && year != string.Empty && strFilter != string.Empty)
{
strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted, d.DeductionID from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month " +
"where d.Month='" + month + "' and d.Year='" + year + "' " +
"and (m.FileNo LIKE '%" + strFilter + "%' or m.LastName LIKE '%" + strFilter + "%' or m.FirstName LIKE '%" + strFilter + "%')";
}
else if (month == string.Empty && year == string.Empty && strFilter ==string.Empty)
{
strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted, d.DeductionID from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month";
}
else if (month == string.Empty && year == string.Empty && strFilter != string.Empty)
{
strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted, d.DeductionID from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month " +
"and (m.FileNo like '%" + strFilter + "%' or m.LastName LIKE '%" + strFilter + "%' or m.FirstName LIKE '%" + strFilter + "%')";
}
//MessageBox.Show(strQuery);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGrdVwDeductions.DataSource = null;
datGrdVwDeductions.Refresh();
try
{
conn.Open();
da.Fill(ds, "Deductions");
dt = ds.Tables["Deductions"];
datGrdVwDeductions.DataSource = dt;
datGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Format = "N2";
datGrdVwDeductions.Columns["<NAME>"].Width = 250;
datGrdVwDeductions.Columns["MemberID"].Visible = false;
datGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Format = "N2";
datGrdVwDeductions.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Total"].DefaultCellStyle.Format = "N2";
datGrdVwDeductions.Columns["DeductionID"].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
getDeductionMonthIntoCombo();
getDeductionYearIntoCombo();
}
private void getDeductionMonthIntoCombo()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select distinct(d.Month) as id, m.Month as Mon from Deductions d " +
"inner join MonthByName m on d.Month=m.MonthID order by id asc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Month");
DataTable dt = ds.Tables["Month"];
DataRow row = dt.NewRow();
row["Mon"] = "--Select Month--";
dt.Rows.InsertAt(row, 0);
cboMonth.DisplayMember = "Mon";
cboMonth.ValueMember = "id";
cboMonth.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getDeductionYearIntoCombo()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select distinct(Year) as yearField from Deductions";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Year");
DataTable dt = ds.Tables["Year"];
cboYear.DisplayMember = "yearField";
cboYear.ValueMember = "yearField";
cboYear.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text != string.Empty)
{
strFilter = txtSearch.Text;
ViewDeductions_Load(sender, e);
}
}
private void btnDateSearch_Click(object sender, EventArgs e)
{
if (cboMonth.SelectedValue.ToString() != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.LastName + ' ' + m.FirstName as 'Full Name'," +
"Mon.Month, d.Year, d.Savings, d.Loans, d.Total, d.TransactionID, d.DatePosted from Deductions d " +
"inner join Members m on d.MemberID=m.MemberID " +
"inner join MonthByName Mon on Mon.MonthID=d.Month " +
"where d.Month='" + cboMonth.SelectedValue.ToString() + "' and d.Year='" + cboYear.Text + "'";
//MessageBox.Show(strQuery);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGrdVwDeductions.DataSource = null;
datGrdVwDeductions.Refresh();
try
{
conn.Open();
da.Fill(ds, "Deductions");
dt = ds.Tables["Deductions"];
datGrdVwDeductions.DataSource = dt;
datGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Format = "N2";
datGrdVwDeductions.Columns["Full Name"].Width = 250;
datGrdVwDeductions.Columns["MemberID"].Visible = false;
datGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Format = "N2";
datGrdVwDeductions.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwDeductions.Columns["Total"].DefaultCellStyle.Format = "N2";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void btnExportExcel_Click(object sender, EventArgs e)
{
ExportData exportDeductions = new ExportData();
exportDeductions.ExportToExcel(dt, saveFD);
}
private void btnReload_Click(object sender, EventArgs e)
{
ViewDeductions_Load(sender, e);
}
private void btnViewDetails_Click(object sender, EventArgs e)
{
string selectedDeductionID = datGrdVwDeductions.SelectedRows[0].Cells[10].Value.ToString();
ViewDeductionDetails viewDeductionDetails = new ViewDeductionDetails(selectedDeductionID);
viewDeductionDetails.MdiParent = this.ParentForm;
viewDeductionDetails.Show();
}
}
}
<file_sep>/MainApp/MainApp/Withdrawal/MakeWithdrawal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class MakeWithdrawal : Form
{
string memberID = string.Empty;
decimal memberTotalSavingsByType;
private string UserID;
public MakeWithdrawal(string userId)
{
InitializeComponent();
this.UserID = userId;
lstVwSavingsSource.View = View.Details;
lstVwSavingsSource.FullRowSelect = true;
lstVwSavingsSource.Columns.Add("Savings Source", 250);
lstVwSavingsSource.Columns.Add("Amount", 200);
}
private void btnGetMember_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID,m.FileNo,m.Title,m.FirstName,m.LastName,m.MiddleName,m.Photo " +
"from Members m where m.FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
string paths = PhotoPath.getPath();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
picMember.Visible = true;
lblMemberInfo.Visible = true;
lblMemberInfo.Text = reader["Title"].ToString() + ' ' + reader["LastName"].ToString() + ' ' + reader["FirstName"].ToString() + ' ' + reader["MiddleName"].ToString();
if (reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
memberID = reader["MemberID"].ToString();
//getMember Savings Account Types
cboSavingsType.DataSource = null;
getMemberSavingsAccountType(memberID);
getPreviousWithdrawals();
}
}
else
{
lblMemberInfo.Text = string.Empty;
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
picMember.Visible = false;
lblMemberInfo.Visible = false;
MessageBox.Show("There is no record with that FileNo.", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getPreviousWithdrawals()
{
BuildTempSavingsAcctType.Create();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select w.SavingsWithdrawalID 'ID',w.SavingsID 'Savings ID', st.SavingsName 'Savings Type', w.Amount,w.WithdrawAmount 'Withdrawal',w.Balance,w.Date from SavingsWithdrawal w " +
"left join TempSavingsAcctType st on w.SavingsTypeID=st.SavingsTypeID order by w.SavingsWithdrawalID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGrdVwSavings.DataSource = null;
try
{
conn.Open();
da.Fill(ds, "Withdrawal");
DataTable dt = ds.Tables["Withdrawal"];
datGrdVwSavings.DataSource = dt;
datGrdVwSavings.Columns["ID"].Width = 80;
datGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwSavings.Columns["Withdrawal"].DefaultCellStyle.Format = "N2";
datGrdVwSavings.Columns["Withdrawal"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwSavings.Columns["Balance"].DefaultCellStyle.Format = "N2";
datGrdVwSavings.Columns["Balance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getMemberSavingsAccountType(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsTypeID,Remark from MemberSavingsTypeAcct " +
"where MemberID=" + memberID;
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "MemberSavingsTypeAcct");
DataTable dt = ds.Tables["MemberSavingsTypeAcct"];
cboSavingsType.Items.Clear();
DataRow row = dt.NewRow();
row["Remark"] = "-- Select Savings Type --";
dt.Rows.InsertAt(row, 0);
cboSavingsType.DataSource = dt;
cboSavingsType.DisplayMember = "Remark";
cboSavingsType.ValueMember = "SavingsTypeID";
//cboSavingsType
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cboSavingsType_SelectedIndexChanged(object sender, EventArgs e)
{
//MessageBox.Show(cboSavingsType.SelectedIndex.ToString());
lstVwSavingsSource.Items.Clear();
lblAcctAmount.Text = string.Empty;
txtWithdrawAmt.Text = string.Empty;
if (cboSavingsType.SelectedIndex != 0)
{
//Enable btnPose
btnPost.Enabled = true;
//Enable txtWithdrawal control
txtWithdrawAmt.Enabled = true;
int savingsTypeID = Convert.ToInt16(cboSavingsType.SelectedValue);
//MessageBox.Show("Member ID: " + memberID + "\nSavings TypeID: " + savingsTypeID);
SavingsByAcctType memberSavings = new SavingsByAcctType();
#region Member Contributions
decimal contributionsByType = memberSavings.getContributionSavings(memberID, savingsTypeID);
//Add Contributions to ListView
string[] row = { "Contributions", CheckForNumber.formatCurrency2(contributionsByType.ToString()) };
ListViewItem item = new ListViewItem(row);
lstVwSavingsSource.Items.Add(item);
#endregion
#region Member Savings Forward
decimal savingsForwardType = memberSavings.getSavingsForward(memberID, savingsTypeID);
//Add SavingsForward to ListView
string[] row2 = { "Savings Forward", CheckForNumber.formatCurrency2(savingsForwardType.ToString()) };
item = new ListViewItem(row2);
lstVwSavingsSource.Items.Add(item);
#endregion
#region Member Deductions Type
decimal deductionsByType = memberSavings.getDeductionSavings(memberID, savingsTypeID);
//Add Deductions to ListView
string[] row3 = { "Deductions", CheckForNumber.formatCurrency2(deductionsByType.ToString()) };
item = new ListViewItem(row3);
lstVwSavingsSource.Items.Add(item);
#endregion
#region Member Withdrawal
decimal withdrawalByType = memberSavings.getWithdrawalSavings(memberID, savingsTypeID);
//Add Withdrawal to ListView
string[] row4 = { "Withdrawal", CheckForNumber.formatCurrency2("-"+withdrawalByType.ToString()) };
item = new ListViewItem(row4);
lstVwSavingsSource.Items.Add(item);
#endregion
memberTotalSavingsByType = (contributionsByType + savingsForwardType + deductionsByType) - (withdrawalByType);
lblAcctAmount.Text = CheckForNumber.formatCurrency2(memberTotalSavingsByType.ToString());
//MessageBox.Show("Contribution : " + contributionsByType.ToString() + "\nSavings Forward: " + savingsForwardType.ToString() + "\nDeduction: " + deductionsByType.ToString());
if (memberTotalSavingsByType == 0)
{
txtWithdrawAmt.Enabled = false;
btnPost.Enabled = false;
}
else
{
txtWithdrawAmt.Enabled = true;
btnPost.Enabled = true;
}
}
else
{
btnPost.Enabled = false;
txtWithdrawAmt.Enabled = false;
}
}
private void txtWithdrawAmt_TextChanged(object sender, EventArgs e)
{
if (txtWithdrawAmt.Text != string.Empty)
{
if (CheckForNumber.isNumeric(txtWithdrawAmt.Text))
{
decimal withdrawalAmt = Convert.ToDecimal(txtWithdrawAmt.Text);
decimal balance = memberTotalSavingsByType - (withdrawalAmt);
lblAmtBalance.Text = CheckForNumber.formatCurrency2(balance.ToString());
//Enable or disable btn based on balance
if (balance >= 0 && withdrawalAmt>0)
{
btnPost.Enabled = true;
}
else
{
btnPost.Enabled = false;
}
}
else
{
MessageBox.Show("Invalid Amount has been supplied", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
btnPost.Enabled = false;
}
}
private void txtWithdrawAmt_Leave(object sender, EventArgs e)
{
if (txtWithdrawAmt.Text != string.Empty)
{
if (CheckForNumber.isNumeric(txtWithdrawAmt.Text))
{
txtWithdrawAmt.Text = CheckForNumber.formatCurrency2(txtWithdrawAmt.Text);
}
else
{
MessageBox.Show("Invalid Amount has been supplied", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtWithdrawAmt.Text = string.Empty;
}
}
else
{
MessageBox.Show("Amount has not been supplied", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnPost_Click(object sender, EventArgs e)
{
if (CheckForNumber.isNumeric(txtWithdrawAmt.Text) && (Convert.ToDecimal(txtWithdrawAmt.Text) > 0))
{
DialogResult res = MessageBox.Show("Do you wish to post this Transaction?", "Withdrawal", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
#region ExecutePost
string strMonth = dateTimePicker1.Value.Month.ToString();
string strYear = dateTimePicker1.Value.Year.ToString();
string transactionID = "WIT" + DateTime.Now.ToString("ddMMyyhhmmss");
SqlConnection conn = ConnectDB.GetConnection();
conn.Open();
SqlTransaction mySqlTrans = conn.BeginTransaction();
string strInsertSavings = "Insert into Savings(MemberID,SavingSource,Amount,Month,Year,TransactionID)values(@MemberID," +
"@SavingSource,@Amount,@Month,@Year,@TransactionID)";
string strInsertSavingsWithdrawal = "Insert into SavingsWithdrawal(SavingsID,MemberID,SavingsTypeID,Amount," +
"WithdrawAmount,Balance)values(@SavingsID,@MemberID,@SavingsTypeID,@Amount,@WithdrawalAmount,@Balance)";
string strQuery = "Select SavingsID from Savings where TransactionID=@TransactionID";
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = mySqlTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strInsertSavings;
#region cmdParameters
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@SavingSource", SqlDbType.NVarChar, 50);
cmd.Parameters["@SavingSource"].Value = "Withdrawal";
cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = "-" + txtWithdrawAmt.Text;
cmd.Parameters.Add("@Month", SqlDbType.NVarChar, 50);
cmd.Parameters["@Month"].Value = strMonth;
cmd.Parameters.Add("@Year", SqlDbType.NVarChar, 50);
cmd.Parameters["@Year"].Value = strYear;
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 30);
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmdParameters
try
{
int rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
cmd.CommandText = strQuery;
cmd.Parameters["@TransactionID"].Value = transactionID;
int savingsID = Convert.ToInt16(cmd.ExecuteScalar());
cmd.CommandText = strInsertSavingsWithdrawal;
#region cmdParameters - strInsertSavingsWithrawal
cmd.Parameters.Add("@SavingsID", SqlDbType.Int);
cmd.Parameters["@SavingsID"].Value = savingsID;
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmd.Parameters["@SavingsTypeID"].Value = cboSavingsType.SelectedValue;
cmd.Parameters["@Amount"].Value = lblAcctAmount.Text;
cmd.Parameters.Add("@WithdrawalAmount", SqlDbType.Decimal);
cmd.Parameters["@WithdrawalAmount"].Value = txtWithdrawAmt.Text;
cmd.Parameters.Add("@Balance", SqlDbType.Decimal);
cmd.Parameters["@Balance"].Value = lblAmtBalance.Text;
#endregion
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected > 0)
{
mySqlTrans.Commit();
MessageBox.Show("Transaction is Successfully Posted","Withdrawal",MessageBoxButtons.OK,MessageBoxIcon.Information);
string logDescription = cboSavingsType.Text + " withdrawal of " + txtWithdrawAmt.Text +
" from Member with ID " + memberID;
txtWithdrawAmt.Text = string.Empty;
txtWithdrawAmt.Enabled = false;
btnPost.Enabled = false;
getPreviousWithdrawals();
ActivityLog.logActivity(UserID, "Withdrawal", logDescription);
}
else
{
mySqlTrans.Rollback();
MessageBox.Show("An error has occurred!", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
mySqlTrans.Rollback();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion
}
}
else
{
MessageBox.Show("Withdrawal Amount has not been Supplied", "Withdrawal", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void lstVwSavingsSource_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void lstVwSavingsSource_Click(object sender, EventArgs e)
{
if (lstVwSavingsSource.Items.Count > 0)
{
string savingsSource = lstVwSavingsSource.SelectedItems[0].SubItems[0].Text.ToString();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = string.Empty;
SqlCommand cmd = null;
datGrdVwSavings.DataSource = null;
DataTable dt = null;
switch (savingsSource)
{
case "Contributions":
strQuery = "Select c.ContributionID 'ID',pay.PaymentMode,c.OtherPayment,m.Month,s.Year,s.Amount,acct.SavingsName 'Savings Name', " +
"b.BankName 'Bank Name',c.TellerNo 'Teller No.',c.ReceiptNo 'Receipt No.',c.Comment,s.SavingSource 'Saving Source', " +
"s.TransactionID,c.Date from Contributions c " +
"left join Savings s on s.SavingsID=c.SavingsID " +
"left join MonthByName m on s.Month=m.MonthID " +
"left join Banks b on b.BankID=c.BankID " +
"left join PaymentMode pay on pay.PaymentModeID=c.PaymentModeID " +
"left join TempSavingsAcctType acct on acct.SavingsTypeID=c.SavingsAcctID " +
"where s.SavingSource='Contribution' and s.MemberID="+memberID+" and c.SavingsAcctID='" + cboSavingsType.SelectedValue.ToString() + "'";
cmd = new SqlCommand(strQuery, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Savings");
dt = ds.Tables["Savings"];
break;
case "Savings Forward":
strQuery = "Select sf.SavingsForwardID 'ID',mon.Month,sf.year 'Year',st.SavingsName 'Savings Type',sf.Amount,sf.Comment, " +
"sf.TransactionID,sf.DatePosted 'Date Posted' from SavingsForward sf " +
"inner join Savings s on sf.SavingsID=s.SavingsID " +
"left join TempSavingsAcctType st on sf.SavingsTypeID = st.SavingsTypeID " +
"left join MonthByName mon on sf.Month=mon.MonthID " +
"where s.SavingSource='SavingsForward' and s.MemberID=" + memberID + " and sf.SavingsTypeID='" + cboSavingsType.SelectedValue.ToString() + "'";
cmd = new SqlCommand(strQuery, conn);
conn.Open();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "SavingsForward");
dt = ds.Tables["SavingsForward"];
break;
case "Deductions":
strQuery = "Select dd.deductionDetailsID 'ID',st.SavingsName 'Savings Type',mon.Month,s.Year,dd.Amount,dd.Remarks, " +
"dd.TransactionID,dd.DatePosted from DeductionDetails dd " +
"left join Savings s on s.TransactionID=dd.TransactionID " +
"left join TempSavingsAcctType st on st.SavingsTypeID=dd.SavingsTypeID " +
"left join MonthByName mon on mon.MonthID=s.Month " +
"where s.SavingSource='Deduction' and s.MemberID=" + memberID + " and dd.SavingsTypeID='" + cboSavingsType.SelectedValue.ToString() + "'";
cmd = new SqlCommand(strQuery, conn);
conn.Open();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "Deductions");
dt = ds.Tables["Deductions"];
break;
case "Withdrawal":
strQuery = "Select sw.SavingsWithdrawalID 'ID', mon.Month, s.Year, st.SavingsName 'Savings Type', " +
"sw.Amount,sw.WithdrawAmount,sw.Balance, s.TransactionID, s.Date " +
"from SavingsWithdrawal sw " +
"left join TempSavingsAcctType st on st.SavingsTypeID=sw.SavingsTypeID " +
"left join Savings s on sw.SavingsID=s.SavingsID " +
"left join MonthByName mon on mon.MonthID=s.Month ";
cmd = new SqlCommand(strQuery, conn);
conn.Open();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "Withdrawal");
dt = ds.Tables["Withdrawal"];
break;
}
try
{
datGrdVwSavings.DataSource = dt;
datGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwSavings.Columns["ID"].Width = 60;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
}
<file_sep>/MainApp/MainApp/Savings/ViewSavings.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ViewSavings : Form
{
string strFilter = null;
string addFilter = null;
string addFilter2 = null;
DataTable dtSavings;
DataTable dtSavingsDetails;
public ViewSavings()
{
InitializeComponent();
}
private void clearParameters()
{
strFilter = null;
addFilter2 = null;
addFilter = null;
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void ViewSavings_Load(object sender, EventArgs e)
{
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
private void displayAllMembersSavings(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as Fullname, SUM(s.Amount) as Amount " +
"from Members m left join savings s on m.MemberID=s.MemberID " + strFilter +
" group by m.MemberID,m.FileNo,m.Title,m.MiddleName,m.FirstName,m.LastName order by m.FileNo";
//MessageBox.Show(strQuery);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGridViewSavings.DataSource = null;
datGridViewSavings.Columns.Clear();
datGridViewSavings.Rows.Clear();
datGridViewSavings.Refresh();
try
{
conn.Open();
da.Fill(ds, "Savings");
dtSavings = ds.Tables["Savings"];
datGridViewSavings.DataSource = dtSavings;
datGridViewSavings.Columns["MemberID"].Visible = false;
datGridViewSavings.Columns["FileNo"].HeaderText = "File No.";
datGridViewSavings.Columns["Fullname"].HeaderText = "<NAME>";
datGridViewSavings.Columns["Fullname"].Width = 300;
datGridViewSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGridViewSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGridViewSavings.Columns.Add(btn);
btn.HeaderText = "View";
btn.Text = "View Details";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
lblSavingsRecordNo.Text = "No. of Records: " + ds.Tables["Savings"].Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show("Display All Members Savings -- " + ex.Message);
}
finally
{
conn.Close();
}
}
private void displayAllMembersSavingsDetails(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select s.SavingsID, m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as Fullname, " +
"s.SavingSource as Source, s.Amount, d.Month, s.year as Year, s.TransactionID, s.Date from Members m left join Savings s on m.MemberID=s.MemberID " +
"left join MonthByName d on s.Month=d.MonthID " + strFilter +
" order by s.SavingsID desc";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGridSavingsDetails.DataSource = null;
datGridSavingsDetails.Columns.Clear();
datGridSavingsDetails.Rows.Clear();
datGridSavingsDetails.Refresh();
try
{
conn.Open();
da.Fill(ds, "Savings");
dtSavingsDetails = ds.Tables["Savings"];
datGridSavingsDetails.DataSource = dtSavingsDetails;
datGridSavingsDetails.Columns["SavingsID"].Visible = false;
datGridSavingsDetails.Columns["MemberID"].Visible = false;
datGridSavingsDetails.Columns["Fullname"].Width = 200;
datGridSavingsDetails.Columns["FileNo"].Width = 80;
datGridSavingsDetails.Columns["FileNo"].HeaderText = "File No.";
datGridSavingsDetails.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGridSavingsDetails.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
datGridSavingsDetails.Columns["TransactionID"].Width = 150;
datGridSavingsDetails.Columns["Month"].Width = 80;
datGridSavingsDetails.Columns["Year"].Width = 80;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGridSavingsDetails.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "View Details";
btn.Name = "btnDetails";
btn.UseColumnTextForButtonValue = true;
lblSavingsRecordDetail.Text = "No of Records: " + ds.Tables["Savings"].Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getTotalSavings(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SUM(Amount) as Total from Savings " + strFilter;
SqlCommand cmd = new SqlCommand(strQuery, conn);
//MessageBox.Show(strQuery);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
lblTotalSavings.Text = "Total Savings: " + CheckForNumber.formatCurrency2(reader["Total"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show("Total Savings: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void datGridViewSavings_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int memberID;
string theID = null;
string totalSavings = string.Empty;
//MessageBox.Show(e.ColumnIndex.ToString());
if (e.ColumnIndex == 0)
{
theID = datGridViewSavings.Rows[e.RowIndex].Cells[1].Value.ToString();
totalSavings = datGridViewSavings.Rows[e.RowIndex].Cells[4].Value.ToString().Trim();
//MessageBox.Show("ID: " + theID + "total Savings: " + totalSavings);
}
else if (e.ColumnIndex==4)
{
theID = datGridViewSavings.Rows[e.RowIndex].Cells[0].Value.ToString();
totalSavings = datGridViewSavings.Rows[e.RowIndex].Cells[4].Value.ToString().Trim();
//MessageBox.Show("ID: " + theID);
}
//MessageBox.Show(totalSavings.ToString());
if ((e.ColumnIndex == 0 || e.ColumnIndex==4) && totalSavings != string.Empty)
{
//MessageBox.Show(e.ColumnIndex.ToString() + "ID: " + theID);
if (CheckForNumber.isNumeric(theID))
{
memberID = Convert.ToInt16(theID);
strFilter = "where m.MemberID=" + memberID + addFilter;
displayAllMembersSavingsDetails(strFilter);
strFilter = "where MemberID=" + memberID + addFilter2;
getSelectedDetailsTotalSavings(strFilter);
}
}
else
{
MessageBox.Show("There is no Savings yet for the Selected Member", "View Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
datGridSavingsDetails.DataSource = null;
datGridSavingsDetails.Columns.Clear();
datGridSavingsDetails.Rows.Clear();
lblSelectedSavingsTotal.Text = "Total: 0.0";
lblSavingsRecordDetail.Text = "No. of Records: 0";
}
}
private void getSelectedDetailsTotalSavings(string strFilter)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SUM(Amount) as Total from Savings " + strFilter;
SqlCommand cmd = new SqlCommand(strQuery, conn);
//MessageBox.Show(strQuery);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
lblSelectedSavingsTotal.Text = "Total Savings: " + CheckForNumber.formatCurrency2(reader["Total"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show("Total Savings: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void txtFileNoSearch_KeyUp(object sender, KeyEventArgs e)
{
if (txtFileNoSearch.Text != string.Empty)
{
clearParameters();
string memberIDList = string.Empty;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID from Members where FileNo LIKE '%" + txtFileNoSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (memberIDList==string.Empty)
{
memberIDList = reader["MemberID"].ToString();
}
else
{
memberIDList += "," + reader["MemberID"].ToString();
}
}
strFilter = " where m.FileNo LIKE '%" + txtFileNoSearch.Text + "%'";
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
strFilter = " where MemberID in (" + memberIDList + ")";
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
else
{
datGridViewSavings.DataSource = null;
datGridViewSavings.Columns.Clear();
datGridViewSavings.Rows.Clear();
datGridViewSavings.Refresh();
datGridSavingsDetails.DataSource = null;
datGridSavingsDetails.Columns.Clear();
datGridSavingsDetails.Rows.Clear();
datGridSavingsDetails.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void cboSourceSearch_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSourceSearch.SelectedIndex != 0)
{
strFilter = " where s.SavingSource='" + cboSourceSearch.Text + "'";
addFilter = " and s.SavingSource='" + cboSourceSearch.Text + "'";
addFilter2 = " and SavingSource='" + cboSourceSearch.Text + "'";
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
strFilter = " where SavingSource='" + cboSourceSearch.Text + "'";
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
else
{
clearParameters();
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
}
private void cboMonthSearch_SelectedIndexChanged(object sender, EventArgs e)
{
strFilter = " where s.Month='" + (cboMonthSearch.SelectedIndex) + "'";
addFilter = " and s.Month='" + (cboMonthSearch.SelectedIndex) + "'";
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
if (datGridViewSavings.Rows.Count != 0)
{
strFilter = " where Month='" + (cboMonthSearch.SelectedIndex) + "'";
addFilter2 = " and Month='" + (cboMonthSearch.SelectedIndex) + "'";
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
else
{
lblTotalSavings.Text = "Total Savings: 0";
lblSelectedSavingsTotal.Text = "Total Savings: 0";
}
}
private void cboYearSearch_SelectedIndexChanged(object sender, EventArgs e)
{
//MessageBox.Show(cboYearSearch.Text.ToString());
//int val;
//bool result = int.TryParse(cboYearSearch.Text, out val);
//MessageBox.Show(result.ToString());
strFilter = " where s.Year='" + cboYearSearch.Text.Trim() + "' ";
addFilter = " and s.Year='" + cboYearSearch.Text.Trim() + "' ";
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
if (datGridViewSavings.Rows.Count != 0)
{
strFilter = " where Year='" + cboYearSearch.Text.Trim() + "' ";
addFilter2 = " and Year='" + cboYearSearch.Text.Trim() + "' ";
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
else
{
lblTotalSavings.Text = "Total Savings: 0";
lblSelectedSavingsTotal.Text = "Total Savings: 0";
}
}
private void btnFilter_Click(object sender, EventArgs e)
{
string searchCriteria = string.Empty;
string searchCriteriaTotal = string.Empty;
if (txtFileNoSearch.Text != string.Empty)
{
searchCriteria = " m.FileNo LIKE '%" + txtFileNoSearch.Text + "%'";
searchCriteriaTotal = " MemberID in (" + getMemberSearchListByFileNo() + ") ";
}
if (cboSourceSearch.Text != string.Empty)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
searchCriteriaTotal += " and ";
}
searchCriteria += " s.SavingSource='" + cboSourceSearch.Text + "'";
searchCriteriaTotal += " SavingSource='" + cboSourceSearch.Text + "'";
}
if (cboMonthSearch.Text != string.Empty)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
searchCriteriaTotal += " and ";
}
searchCriteria += " s.Month='" + cboMonthSearch.SelectedIndex + "'";
searchCriteriaTotal += " Month='" + cboMonthSearch.SelectedIndex + "'";
}
if (cboYearSearch.Text != string.Empty)
{
if (searchCriteria != string.Empty)
{
searchCriteria += " and ";
searchCriteriaTotal += " and ";
}
searchCriteria += "s.Year='" + cboYearSearch.Text + "'";
searchCriteriaTotal += " Year='" + cboYearSearch.Text + "'";
}
if (searchCriteria != string.Empty)
{
searchCriteria = " where " + searchCriteria + " ";
searchCriteriaTotal = "where " + searchCriteriaTotal + " ";
displayAllMembersSavings(searchCriteria);
displayAllMembersSavingsDetails(searchCriteria);
getTotalSavings(searchCriteriaTotal);
getSelectedDetailsTotalSavings(searchCriteriaTotal);
}
}
private void btnReset_Click(object sender, EventArgs e)
{
strFilter = string.Empty;
ViewSavings_Load(sender, e);
}
private string getMemberSearchListByFileNo()
{
string memberIDList = string.Empty;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID from Members where FileNo LIKE '%" + txtFileNoSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (memberIDList == string.Empty)
{
memberIDList = reader["MemberID"].ToString();
}
else
{
memberIDList += "," + reader["MemberID"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return memberIDList;
}
private void btnDateFilter_Click(object sender, EventArgs e)
{
if ((cboFromMonthSearch.Text != string.Empty) && (cboFromYearSearch.Text != string.Empty) && (cboToMonthSearch.Text != string.Empty) && (cboToYearSearch.Text != string.Empty))
{
int toYear = Convert.ToInt16(cboToYearSearch.Text);
int fromYear = Convert.ToInt16(cboFromYearSearch.Text);
MessageBox.Show(cboToMonthSearch.SelectedIndex.ToString());
if (toYear > fromYear)
{
strFilter = " where s.Month between " + cboFromMonthSearch.SelectedIndex + " and " + cboToMonthSearch.SelectedIndex +
" or s.Year between " + cboFromYearSearch.Text + " and " + cboToYearSearch.Text + " " ;
displayAllMembersSavings(strFilter);
displayAllMembersSavingsDetails(strFilter);
strFilter = " where Month between " + cboFromMonthSearch.SelectedIndex + " and " + cboToMonthSearch.SelectedIndex +
" or Year between " + cboFromYearSearch.Text + " and " + cboToYearSearch.Text + " ";
getTotalSavings(strFilter);
getSelectedDetailsTotalSavings(strFilter);
}
else
{
MessageBox.Show("The Date period has to be in the proper order", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Select the Date periods to perform this search", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnExportSavings_Click(object sender, EventArgs e)
{
ExportData exportSavings = new ExportData();
exportSavings.ExportToExcel(dtSavings,saveFD);
}
private void btnExportSavingsDetails_Click(object sender, EventArgs e)
{
ExportData exportSavingsDetails = new ExportData();
exportSavingsDetails.ExportToExcel(dtSavingsDetails, saveFD);
}
private void btnDateFilter_Click_1(object sender, EventArgs e)
{
}
private void datGridSavingsDetails_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string savingsID = string.Empty;
string savingSource = string.Empty;
string transactionID = string.Empty;
//MessageBox.Show(e.ColumnIndex.ToString());
if (e.ColumnIndex == 0)
{
savingsID = datGridSavingsDetails.Rows[e.RowIndex].Cells[1].Value.ToString();
savingSource = datGridSavingsDetails.Rows[e.RowIndex].Cells[5].Value.ToString();
transactionID = datGridSavingsDetails.Rows[e.RowIndex].Cells[9].Value.ToString();
}
else if(e.ColumnIndex==10)
{
savingsID = datGridSavingsDetails.Rows[e.RowIndex].Cells[0].Value.ToString();
savingSource = datGridSavingsDetails.Rows[e.RowIndex].Cells[4].Value.ToString();
transactionID = datGridSavingsDetails.Rows[e.RowIndex].Cells[8].Value.ToString();
}
if (e.ColumnIndex == 0 || e.ColumnIndex == 10)
{
ViewSavingsDetails viewSavingsDetails = new ViewSavingsDetails(savingsID, savingSource, transactionID);
//MessageBox.Show("Saving Source: " + savingSource + "\nSavings ID: " + savingSource + "\nTransactionID " + transactionID);
viewSavingsDetails.MdiParent = this.ParentForm;
viewSavingsDetails.Show();
}
}
}
}
<file_sep>/MainApp/MainApp/Members/MembersList.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class MembersList : Form
{
public MembersList()
{
InitializeComponent();
}
private void MembersList_Load(object sender, EventArgs e)
{
loadMembersRecords();
}
private void loadMembersRecords()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo 'File No', m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name' " +
"from Members m ";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Members");
DataTable dt = ds.Tables["Members"];
datGrdMembers.DataSource = dt;
datGrdMembers.Columns["File No"].Width = 70;
datGrdMembers.Columns["Full Name"].Width = 210;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGrdMembers.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Details";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
datGrdMembers.Columns[0].Visible = false;
lblRecordNo.Text = "No. of Records : " + dt.Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnMemberProfile_Click(object sender, EventArgs e)
{
MemberProfile memberProfile = new MemberProfile();
memberProfile.ShowDialog();
}
private void datGrdMembers_SelectionChanged(object sender, EventArgs e)
{
}
private void datGrdMembers_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
MessageBox.Show(datGrdMembers.Rows[e.RowIndex].Cells[2].Value.ToString());
}
}
private void datGrdMembers_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.ColumnIndex.ToString());
string memberID = string.Empty;
if (e.ColumnIndex == 0)
{
memberID = datGrdMembers.Rows[e.RowIndex].Cells[1].Value.ToString();
memberPersonalProfile(memberID);
memberSavings(memberID);
contributions(memberID);
deductions(memberID);
loans(memberID);
}
}
private void memberPersonalProfile(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID 'ID', m.FileNo as [File No.], m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"m.Gender,m.Address, m.LGA, s.State, m.Phone, m.Email, d.DepartmentName [Department], b.BankName [Bank], m.AccountNo [Account], m.NOKFullName [Next of Kin]," +
"m.NOKPhone [Kin Phone], m.NOKAddress [NOK Addr.] from Members m " +
"left join States s on m.StateID = s.StateID " +
"left join Departments d on m.DepartmentID=d.DepartmentID " +
"left join Banks b on m.BankID=b.BankID " +
"where m.MemberID='" + memberID + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Members");
DataTable dt = ds.Tables["Members"];
dtGrdPersonalProfile.DataSource = dt;
dtGrdPersonalProfile.Columns["ID"].Width = 60;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void memberSavings(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select s.SavingsID 'ID',m.Title + ' ' + m.LastName + ' ' + m.FirstName + ' ' + m.MiddleName as 'Full Name', " +
"s.SavingSource 'Saving Source',s.Amount,mnth.Month,s.Year,s.TransactionID,s.Date from Savings s " +
"left join Members m on m.MemberID=s.MemberID " +
"left join MonthByName mnth on mnth.MonthID=s.Month " +
"where s.MemberID='" + memberID + "' order by s.SavingsID desc";
SqlCommand cmd = new SqlCommand(strQuery,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdVwSavings.DataSource = dt;
dtGrdVwSavings.Columns["ID"].Width = 50;
dtGrdVwSavings.Columns["Full Name"].Width = 150;
dtGrdVwSavings.Columns["Saving Source"].Width = 120;
dtGrdVwSavings.Columns["Full Name"].Visible = false;
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void contributions(string memberID)
{
BuildTempSavingsAcctType.Create();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select c.ContributionID 'ID',p.PaymentMode,c.OtherPayment,b.BankName,s.Amount,s.SavingSource 'Saving Source',mnth.Month,s.Year,c.TellerNo 'Teller No.',c.ReceiptNo 'Receipt No.',c.Comment, " +
"t.SavingsName 'Savings Type',s.TransactionID,s.Date from Contributions c " +
"left join Savings s on c.SavingsID=s.SavingsID " +
"left join Members m on s.MemberID = m.MemberID " +
"left join PaymentMode p on p.PaymentModeID=c.PaymentModeID " +
"left join Banks b on b.BankID=c.BankID " +
"left join MonthByName mnth on mnth.MonthID=s.Month " +
"left join TempSavingsAcctType t on c.SavingsAcctID=t.SavingsTypeID " +
"where s.MemberID='" + memberID + "' order by c.ContributionID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Contributions");
DataTable dt = ds.Tables["Contributions"];
dtGrdVwContributions.DataSource = dt;
dtGrdVwContributions.Columns["ID"].Width = 60;
dtGrdVwContributions.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwContributions.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void deductions(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select d.DeductionID 'ID',mnth.Month,d.Year,d.Savings,d.Loans,d.Total,d.TransactionID,DatePosted " +
"from Deductions d left join MonthByName mnth on d.Month=mnth.MonthID " +
"where d.MemberID='" + memberID + "' order by d.DeductionID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Deductions");
DataTable dt = ds.Tables["Deductions"];
dtGrdVwDeductions.DataSource = dt;
dtGrdVwDeductions.Columns["ID"].Width = 60;
dtGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Format = "N2";
dtGrdVwDeductions.Columns["Savings"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Format = "N2";
dtGrdVwDeductions.Columns["Loans"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwDeductions.Columns["Total"].DefaultCellStyle.Format = "N2";
dtGrdVwDeductions.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loans(string memberID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select a.LoanApplicationID 'ID',mnth.Month,a.AppYear 'Year',lc.Name 'Loan Category',lt.Type 'Loan Type', "+
"a.LoanAmount 'Loan Amt.',a.InterestAmount 'Interest',a.TotalRepayment 'Total Repayment',a.MonthlyRepayment 'Monthly Repayment', " +
"l.AmountPaid 'Amount Paid',l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status',a.DatePosted 'Date Posted' " +
"from LoanApplication a left join Loans l on a.LoanApplicationID=l.LoanApplicationID " +
"left join MonthByName mnth on mnth.MonthID=a.AppMonth " +
"left join LoanCategory lc on lc.LoanCategoryID=a.LoanCategoryID " +
"left join LoanType lt on lt.LoanTypeID=a.LoanTypeID " +
"where a.MemberID='" + memberID + "' order by a.LoanApplicationID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
dtGrdVwLoans.DataSource = dt;
dtGrdVwLoans.Columns["ID"].Width = 60;
dtGrdVwLoans.Columns["Loan Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Loan Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Interest"].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Interest"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Total Repayment"].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Total Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Monthly Repayment"].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Monthly Repayment"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Amount Paid"].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Amount Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwLoans.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
dtGrdVwLoans.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Savings/SavingsForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class SavingsForward : Form
{
int memberID;
decimal totalAmount = 0;
string userId;
public SavingsForward(string UserID)
{
InitializeComponent();
userId = UserID;
//ListView Properties
lstVwSavings.View = View.Details;
lstVwSavings.FullRowSelect = true;
//Construct Columns
lstVwSavings.Columns.Add("Id", 10);
lstVwSavings.Columns.Add("Savings Account", 200);
lstVwSavings.Columns.Add("Amount", 150);
lstVwSavings.Columns[0].Width = 0;
}
private void btnFindMember_Click(object sender, EventArgs e)
{
//Build Savings Table with Personal Savings Account Type and other Savings Account Type using the BuildTempSavingsAcctType Class
BuildTempSavingsAcctType.Create();
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, FileNo, LastName + ' ' + FirstName + ' ' + MiddleName as FullName, Photo from Members " +
"where FileNo='" + txtFileNo.Text.Trim() + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
memberID = Convert.ToInt16(reader["MemberID"].ToString());
lblMemberProfile.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
//display member photo
string paths = PhotoPath.getPath();
//MessageBox.Show(reader["Photo"].ToString());
if (reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
picMember.Visible = true;
lblMemberProfile.Visible = true;
grpBoxSavingsInfo.Enabled = true;
loadDataSetSavingsForward();
loadDataSetMemberSavings();
}
else
{
MessageBox.Show("Sorry, there is no Member with that File No.", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void SavingsForward_Load(object sender, EventArgs e)
{
loadSavingsType();
}
private void loadSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsTypeID, SavingsName from SavingsType";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingsType");
DataTable dt = ds.Tables["SavingsType"];
cboSavingsAcct.ValueMember = "SavingsTypeID";
cboSavingsAcct.DisplayMember = "SavingsName";
DataRow row = dt.NewRow();
row["SavingsName"] = "Shares Savings";
row["SavingsTypeID"] = 99;
dt.Rows.InsertAt(row, 0);
cboSavingsAcct.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadDataSetSavingsForward()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select sf.SavingsID, m.Month, sf.Year, sf.Amount, sf.TransactionID, sf.Date from Savings sf " +
"left join MonthByName m on sf.Month=m.MonthID " +
"where sf.MemberID=" + memberID + " and sf.SavingSource='SavingsForward' order by sf.savingsID desc";
string strQuery2 = "Select Sum(Amount) as TotalSavingsForward from Savings where MemberID=" + memberID + " and SavingSource='SavingsForward'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dtGrdVwSavingsForward.DataSource = null;
dtGrdVwSavingsForward.Columns.Clear();
dtGrdVwSavingsForward.Rows.Clear();
dtGrdVwSavingsForward.Refresh();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdVwSavingsForward.DataSource = dt;
int rowFound = dtGrdVwSavingsForward.Rows.Count;
dtGrdVwSavingsForward.Columns["SavingsID"].Visible = false;
dtGrdVwSavingsForward.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwSavingsForward.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwSavingsForward.Columns["Year"].Width = 60;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dtGrdVwSavingsForward.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Details";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
if (rowFound > 0)
{
cmd.CommandText = strQuery2;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string totalSavingsForward = CheckForNumber.formatCurrency(reader["TotalSavingsForward"].ToString());
lblTotalSavingsForward.Text = "Total: " + totalSavingsForward;
reader.Close();
}
else
{
lblTotalSavingsForward.Text = "Total: 0.00";
}
}
else
{
lblTotalSavingsForward.Text = "Total: 0.00";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cboSavingsAcct_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void txtAmount_Leave(object sender, EventArgs e)
{
if (txtAmount.Text != string.Empty)
{
if (CheckForNumber.isNumeric(txtAmount.Text))
{
txtAmount.Text = CheckForNumber.formatCurrency2(txtAmount.Text);
}
btnPostSavings.Enabled = true;
}
}
private void btnAddSavings_Click(object sender, EventArgs e)
{
//check if the proper data has been entered
if (txtAmount.Text != string.Empty)
{
if (CheckForNumber.isNumeric(txtAmount.Text.Trim()))
{
addSavingsIntoListView();
txtAmount.Text = string.Empty;
}
}
else
{
MessageBox.Show("The Amount has to be filled in","Savings",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void addSavingsIntoListView()
{
bool alreadyExist = false;
if (lstVwSavings.Items.Count != 0)
{
for (int i = 0; i < lstVwSavings.Items.Count; i++)
{
if (lstVwSavings.Items[i].SubItems[1].Text.Trim() == cboSavingsAcct.Text)
{
alreadyExist = true;
}
}
}
if (alreadyExist == false)
{
String[] row = { cboSavingsAcct.SelectedValue.ToString(), cboSavingsAcct.Text, txtAmount.Text };
ListViewItem item = new ListViewItem(row);
lstVwSavings.Items.Add(item);
//Add amount to total
totalAmount = Convert.ToDecimal(txtAmount.Text) + totalAmount;
lblTotalSavings.Text = "Total: " + CheckForNumber.formatCurrency2(totalAmount.ToString());
}
else
{
MessageBox.Show("That Savings Account has already been added", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void lstVwSavings_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstVwSavings.SelectedItems.Count>0)
{
btnRemoveSavings.Enabled = true;
}
else
{
btnRemoveSavings.Enabled = false;
}
}
private void btnRemoveSavings_Click(object sender, EventArgs e)
{
if (lstVwSavings.SelectedItems.Count>0)
{
decimal selAmount = Convert.ToDecimal(lstVwSavings.SelectedItems[0].SubItems[2].Text.ToString());
totalAmount = totalAmount - selAmount;
lblTotalSavings.Text = "Total: " + CheckForNumber.formatCurrency2(totalAmount.ToString());
lstVwSavings.Items.RemoveAt(lstVwSavings.SelectedIndices[0]);
}
else
{
MessageBox.Show("Please select an item to remove from the list", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnPostSavings_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you wish to execute this posting?", "Savings Forward", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (DialogResult.Yes == res)
{
ExecuteSave();
//reset totalAmount
totalAmount = 0;
}
}
private void ExecuteSave()
{
SqlConnection conn = null;
SqlCommand cmd = null;
bool errorFlag = false;
int rowAffected;
string strQuery;
if ((lstVwSavings.Items.Count != 0) && (totalAmount > 0) && (cboMonth.Text != string.Empty) && (cboYear.Text != string.Empty))
{
conn = ConnectDB.GetConnection();
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
cmd = conn.CreateCommand();
cmd.Transaction = sqlTrans;
string transactionID = "SAV" + DateTime.Now.ToString("ddMMyyhhmmss");
strQuery = "Insert into Savings(MemberID,SavingSource,Amount,Month,Year,TransactionID)" +
"values(@MemberID,@SavingSource,@Amount,@Month,@Year,@TransactionID)";
#region cmd parameters
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@SavingSource", SqlDbType.NVarChar, 40);
cmd.Parameters["@SavingSource"].Value = "SavingsForward";
cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = totalAmount;
cmd.Parameters.Add("@Month", SqlDbType.Int);
cmd.Parameters["@Month"].Value = Convert.ToInt16(cboMonth.SelectedIndex);
cmd.Parameters.Add("@Year", SqlDbType.Int);
cmd.Parameters["@Year"].Value = Convert.ToInt16(cboYear.Text);
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
cmd.CommandText = strQuery;
try
{
rowAffected = cmd.ExecuteNonQuery();
#region if Statement of rowAffected
if (rowAffected > 0)
{
//Get SavingsID from the savings Table
strQuery = "Select SavingsID from Savings where TransactionID='" + transactionID + "'";
cmd.CommandText = strQuery;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
string SavingsID = reader["SavingsID"].ToString();
reader.Close();
cmd.Parameters.Add("@SavingsID", SqlDbType.Int);
cmd.Parameters.Add("@SavingsTypeID", SqlDbType.Int);
cmd.Parameters.Add("@Comment", SqlDbType.NVarChar, 400);
for (int i = 0; i < lstVwSavings.Items.Count; i++)
{
strQuery = "Insert into SavingsForward(SavingsID,Month,Year,SavingsTypeID,Amount,Comment,TransactionID)" +
"values(@SavingsID,@Month,@Year,@SavingsTypeID,@Amount,@Comment,@TransactionID)";
#region cmd parameters
cmd.Parameters["@SavingsID"].Value = SavingsID;
cmd.Parameters["@Month"].Value = Convert.ToInt16(cboMonth.SelectedIndex);
cmd.Parameters["@Year"].Value = Convert.ToInt16(cboYear.Text);
cmd.Parameters["@SavingsTypeID"].Value = Convert.ToInt16(lstVwSavings.Items[i].SubItems[0].Text.ToString());
cmd.Parameters["@Amount"].Value = Convert.ToDecimal(lstVwSavings.Items[i].SubItems[2].Text.ToString());
cmd.Parameters["@Comment"].Value = txtComment.Text.Trim();
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
cmd.CommandText = strQuery;
rowAffected = cmd.ExecuteNonQuery();
if (rowAffected == 0)
{
MessageBox.Show("An error has occurred", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
errorFlag = true;
break;
}
}
}
else
{
errorFlag = true;
}
#endregion end of if statement
//Check if Transaction has been successful without error and commit or rollback
if (errorFlag == false)
{
sqlTrans.Commit();
ActivityLog.logActivity(userId, "SavingsForward", "Added a new Savings record with TransactionID of " + transactionID);
MessageBox.Show("Savings has been successfully posted", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadDataSetSavingsForward();
loadDataSetMemberSavings();
}
else
{
sqlTrans.Rollback();
MessageBox.Show("An error has occurred posting savings", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
clearFields();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Month, Year and Amount are required", "Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void clearFields()
{
cboMonth.SelectedIndex = 0;
cboYear.SelectedIndex = 0;
txtAmount.Text = string.Empty;
lblTotalSavings.Text = "Total: " + 0;
txtComment.Text = string.Empty;
lstVwSavings.Items.Clear();
}
private void loadDataSetMemberSavings()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.Month, sf.Year, sf.Amount, sf.SavingSource, sf.TransactionID, sf.Date from Savings sf " +
"left join MonthByName m on sf.Month=m.MonthID " +
"where MemberID=" + memberID + " order by savingsID desc";
string strQuery2 = "Select Sum(Amount) as TotalSavings from Savings where MemberID=" + memberID;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Savings");
DataTable dt = ds.Tables["Savings"];
dtGrdVwSavings.DataSource = dt;
int rowFound = dtGrdVwSavings.Rows.Count;
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Format = "N2";
dtGrdVwSavings.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dtGrdVwSavings.Columns["Year"].Width = 60;
dtGrdVwSavings.Columns["Month"].Width = 80;
if (rowFound > 0)
{
cmd.CommandText = strQuery2;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string totalSavings = CheckForNumber.formatCurrency(reader["TotalSavings"].ToString());
lblMemberTotalSavings.Text = "Total: " + totalSavings;
reader.Close();
}
else
{
lblMemberTotalSavings.Text = "Total: 0.00";
}
}
else
{
lblMemberTotalSavings.Text = "Total: 0.00";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dtGrdVwSavingsForward_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 6)
{
string savingsID = dtGrdVwSavingsForward.Rows[e.RowIndex].Cells[0].Value.ToString();
string savingSource = "SavingsForward";
string transactionID = dtGrdVwSavingsForward.Rows[e.RowIndex].Cells[4].Value.ToString();
ViewSavingsDetails viewSavingsDetails = new ViewSavingsDetails(savingsID, savingSource, transactionID);
viewSavingsDetails.MdiParent = this.ParentForm;
viewSavingsDetails.Show();
}
}
}
}
<file_sep>/MainApp/MainApp/FrmRprtMemberSavings.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class FrmRprtMemberSavings : Form
{
public FrmRprtMemberSavings()
{
InitializeComponent();
}
private void FrmRprtMemberSavings_Load(object sender, EventArgs e)
{
}
private void txtFileNo_Leave(object sender, EventArgs e)
{
if (txtFileNo.Text.Trim() != string.Empty)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select Title + ' ' + LastName + ' ' + FirstName + ' ' + MiddleName as 'FullName' " +
"from Members " +
"where FileNo='" + txtFileNo.Text + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
lblMemberInfo.Text = reader["FullName"].ToString();
lblMemberInfo.Visible = true;
btnSubmit.Enabled = true;
}
}
else
{
MessageBox.Show("Sorry, there is no member with that FileNo.", "Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string strFileNo;
string strFromDate;
string strToDate;
if (txtFileNo.Text.Trim() != string.Empty)
{
strFileNo = txtFileNo.Text;
strFromDate = dtFrom.Value.ToShortDateString();
strToDate = dtTo.Value.ToShortDateString();
RprtMemberSavings rptMemberSavings = new RprtMemberSavings(strFileNo, strFromDate, strToDate);
rptMemberSavings.MdiParent = this.ParentForm;
rptMemberSavings.Show();
}
else
{
MessageBox.Show("Member FileNo. is missing", "Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
<file_sep>/MainApp/MainApp/Contributions/EditContributions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class EditContributions : Form
{
//declare a member global MemberID
int memberID;
public EditContributions()
{
InitializeComponent();
}
private void EditContributions_Load(object sender, EventArgs e)
{
loadItemIntoCboYear();
loadPayment();
loadBanks();
}
private void loadItemIntoCboYear()
{
DateTime myDate = DateTime.Now;
int thisYear = myDate.Year;
int countback = 10;
while (countback > 0)
{
cboYear.Items.Add(thisYear--);
countback--;
}
}
private void loadPayment()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select PaymentModeID, PaymentMode from PaymentMode";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "PaymentMode");
DataTable dt = ds.Tables["PaymentMode"];
DataRow row = dt.NewRow();
row["PaymentMode"] = "-- Select a Payment Mode --";
dt.Rows.InsertAt(row, 0);
cboPaymentMode.DisplayMember = "PaymentMode";
cboPaymentMode.ValueMember = "PaymentModeID";
cboPaymentMode.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void loadBanks()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select BankID, BankName from Banks";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Banks");
DataTable dt = ds.Tables["Banks"];
DataRow row = dt.NewRow();
row["BankName"] = "-- Select a Bank --";
dt.Rows.InsertAt(row, 0);
cboBank.DisplayMember = "BankName";
cboBank.ValueMember = "BankID";
cboBank.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void btnFindMember_Click(object sender, EventArgs e)
{
if (txtfileNo.Text == string.Empty)
{
MessageBox.Show("Enter a File No. to Find a Member", "Edit Contributions", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
SqlConnection conn = ConnectDB.GetConnection();
memberID = findMember(txtfileNo.Text.Trim(), conn);
if (memberID != 0)
{
fetchMemberContributions(conn, memberID);
getMemberSavingsType();
}
}
}
private int findMember(string fileNo, SqlConnection conn)
{
int memberID = 0;
string strQuery = "Select MemberID, FileNo, Title + ' ' + LastName + ' ' + MiddleName + ' ' + FirstName as FullName, Photo from Members where FileNo='" + fileNo + "'";
SqlCommand cmd = new SqlCommand(strQuery, conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
if (reader.HasRows)
{
if (reader.Read())
{
memberID = Convert.ToInt16(reader["MemberID"]);
MemberProfileInfo.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
if(reader["Photo"].ToString() !=null || reader["Photo"].ToString()==string.Empty)
{
picMember.Image = Image.FromFile(paths + "//photos//" + reader["Photo"].ToString());
}
picMember.Visible = true;
MemberProfileInfo.Visible = true;
}
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
picMember.Visible = false;
MemberProfileInfo.Visible = false;
MessageBox.Show("Sorry, that Record is not Found!","Edit Contributions",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return memberID;
}
private void fetchMemberContributions(SqlConnection conn, int memberID)
{
string strQuery = "Select p.PaymentMode [Payment Mode],m.Month,s.Year,s.Amount,b.BankName [Bank],c.OtherPayment [Other Payment],c.TellerNo [Teller No.], c.Comment, s.TransactionID [Transact. ID],s.Date " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join MonthByName m on s.Month=m.MonthID " +
"left join Banks b on c.BankID=b.BankID " +
"where SavingSource='Contribution' and MemberID=" + memberID + " order by s.SavingsID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Contributions");
DataTable dt = ds.Tables["Contributions"];
datGVContributions.DataSource = null;
datGVContributions.Columns.Clear();
datGVContributions.Rows.Clear();
datGVContributions.Refresh();
if (dt.Rows.Count > 0)
{
datGVContributions.DataSource = dt;
datGVContributions.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGVContributions.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGVContributions.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Select Record";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtfileNo_TextChanged(object sender, EventArgs e)
{
if (txtfileNo.Text == String.Empty)
{
btnFindMember.Enabled = false;
}
else
{
btnFindMember.Enabled = true;
}
}
private void datGVContributions_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 10)
{
//MessageBox.Show(e.ColumnIndex.ToString());
//MessageBox.Show(datGVContributions.Rows[e.RowIndex].Cells[8].Value.ToString());
string transactionID = datGVContributions.Rows[e.RowIndex].Cells[8].Value.ToString();
getContributionDetails(transactionID);
}
}
private void chkMonthYear_CheckedChanged(object sender, EventArgs e)
{
if (chkMonthYear.Checked == true)
{
cboMonth.Enabled = true;
cboYear.Enabled = true;
}
else if (chkMonthYear.Checked == false)
{
cboMonth.Enabled = false;
cboYear.Enabled = false;
}
}
private void getContributionDetails(string transactionID)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select c.ContributionID,c.SavingsID,c.PaymentModeID,c.OtherPayment,c.BankID,c.TellerNo,c.Comment,c.SavingsAcctID,c.TransactionID,"+
"s.SavingsID,s.MemberID,s.SavingSource,s.Amount,s.Month,s.Year,s.TransactionID " +
"from Savings s inner join Contributions c on s.TransactionID=c.TransactionID and s.SavingSource='Contribution' and s.TransactionID='" + transactionID + "'";
SqlCommand cmd = new SqlCommand(strQuery,conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
if (reader["BankID"].ToString() != string.Empty)
{
cboBank.SelectedIndex = Convert.ToInt16(reader["BankID"]);
}
//MessageBox.Show(reader["BankID"].ToString());
cboPaymentMode.SelectedIndex = (int) reader["PaymentModeID"];
txtAmount.Text = CheckForNumber.formatCurrency(reader["Amount"].ToString());
cboMemberSavingsType.SelectedValue = reader["SavingsAcctID"];
txtTellerNo.Text = reader["TellerNo"].ToString();
txtOtherPayments.Text = reader["OtherPayment"].ToString();
txtComment.Text = reader["Comment"].ToString();
cboYear.Text = reader["Year"].ToString();
int specifiedMonth = Convert.ToInt16(reader["Month"]);
string monthByName = null;
switch (specifiedMonth)
{
case 1:
monthByName = "January";
break;
case 2:
monthByName = "February";
break;
case 3:
monthByName = "March";
break;
case 4:
monthByName = "April";
break;
case 5:
monthByName = "May";
break;
case 6:
monthByName = "June";
break;
case 7:
monthByName = "July";
break;
case 8:
monthByName = "August";
break;
case 9:
monthByName = "September";
break;
case 10:
monthByName = "October";
break;
case 11:
monthByName = "November";
break;
case 12:
monthByName = "December";
break;
}
cboMonth.Text = monthByName;
btnEditRecord.Enabled = true;
lblSelTransactionalID.Text = reader["TransactionID"].ToString();
lblSavingsID.Text = reader["SavingsID"].ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show("getContributionDetails : - " + ex.Message);
}
finally
{
conn.Close();
}
}
private void btnEditRecord_Click(object sender, EventArgs e)
{
if (btnEditRecord.Text == "Edit Record")
{
groupBox2.Enabled = true;
btnEditRecord.Text = "Cancel Edit";
}
else if (btnEditRecord.Text == "Cancel Edit")
{
groupBox2.Enabled = false;
btnEditRecord.Text = "Edit Record";
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strContribution = "Update Contributions set PaymentModeID=@PaymentModeID,OtherPayment=@OtherPayment,BankID=@BankID,TellerNo=@TellerNo,Comment=@Comment,SavingsAcctID=@SavingsAcctID where TransactionID=@TransactionID and SavingsID=@SavingsID";
string strSavings = "Update Savings set Amount=@Amount, Month=@Month, Year=@Year where TransactionID=@TransactionID and SavingsID=@SavingsID";
#region strContribution Parameters and strSavings Parameters
SqlCommand cmdContribution = new SqlCommand(strContribution, conn);
cmdContribution.Parameters.Add("@PaymentModeID", SqlDbType.Int);
cmdContribution.Parameters["@PaymentModeID"].Value = cboPaymentMode.SelectedValue;
cmdContribution.Parameters.Add("@OtherPayment", SqlDbType.NVarChar, 50);
cmdContribution.Parameters["@OtherPayment"].Value = txtOtherPayments.Text;
cmdContribution.Parameters.Add("@BankID", SqlDbType.NVarChar, 5);
cmdContribution.Parameters["@BankID"].Value = cboBank.SelectedValue;
cmdContribution.Parameters.Add("@TellerNo", SqlDbType.NVarChar, 50);
cmdContribution.Parameters["@TellerNo"].Value = txtTellerNo.Text;
cmdContribution.Parameters.Add("@Comment", SqlDbType.NVarChar, 100);
cmdContribution.Parameters["@Comment"].Value = txtComment.Text;
cmdContribution.Parameters.Add("@TransactionID", SqlDbType.NVarChar,50);
cmdContribution.Parameters["@TransactionID"].Value = lblSelTransactionalID.Text;
cmdContribution.Parameters.Add("@SavingsID", SqlDbType.Int);
cmdContribution.Parameters["@SavingsID"].Value = lblSavingsID.Text;
cmdContribution.Parameters.Add("@SavingsAcctID", SqlDbType.Int);
cmdContribution.Parameters["@SavingsAcctID"].Value = cboMemberSavingsType.SelectedValue;
SqlCommand cmdSavings = new SqlCommand(strSavings, conn);
cmdSavings.Parameters.Add("@Amount", SqlDbType.Decimal);
cmdSavings.Parameters["@Amount"].Value = txtAmount.Text;
string selectedMonthValue = pickMonthValue(cboMonth.Text);
cmdSavings.Parameters.Add("@Month", SqlDbType.NVarChar,5);
cmdSavings.Parameters["@Month"].Value = selectedMonthValue;
cmdSavings.Parameters.Add("@Year", SqlDbType.NVarChar, 5);
cmdSavings.Parameters["@Year"].Value = cboYear.Text;
cmdSavings.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 50);
cmdSavings.Parameters["@TransactionID"].Value = lblSelTransactionalID.Text;
cmdSavings.Parameters.Add("@SavingsID", SqlDbType.Int);
cmdSavings.Parameters["@SavingsID"].Value = lblSavingsID.Text;
#endregion End of strContribution Parameters and end of strSavings Parameters
SqlTransaction sqlTrans = null;
try
{
conn.Open();
sqlTrans = conn.BeginTransaction();
int rowsAffected = 0;
bool dbOperationSuccess = true;
cmdContribution.Transaction = sqlTrans;
rowsAffected = cmdContribution.ExecuteNonQuery();
//MessageBox.Show("No. of Record Updated in Contributions: " + rowsAffected);
if (rowsAffected > 0)
{
rowsAffected = 0;
cmdSavings.Transaction = sqlTrans; //attaching the cmdSavings Object to Transaction
rowsAffected = cmdSavings.ExecuteNonQuery();
//MessageBox.Show("No. of Record Updated in Savings: " + rowsAffected);
if (rowsAffected==0)
{
dbOperationSuccess = false;
}
}
else
{
//if update operation fail writing to contributions turn dbOperationSuccess status to false
dbOperationSuccess = false;
}
//perform commit or rollback depending on the outcome of operations.
if (dbOperationSuccess == true)
{
MessageBox.Show("Contribution has been Successfully Updated.","Edit/Update Contributions", MessageBoxButtons.OK, MessageBoxIcon.Information);
sqlTrans.Commit();
}
else
{
MessageBox.Show("An Error has Occurred!", "Edit/Update Contributions", MessageBoxButtons.OK, MessageBoxIcon.Error);
sqlTrans.Rollback();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
fetchMemberContributions(conn, memberID);
}
private string pickMonthValue(string specifiedDateMonth)
{
string selectedMonthValue = null;
switch (specifiedDateMonth)
{
case "January":
selectedMonthValue = "1";
break;
case "February":
selectedMonthValue = "2";
break;
case "March":
selectedMonthValue = "3";
break;
case "April":
selectedMonthValue = "4";
break;
case "May":
selectedMonthValue = "5";
break;
case "June":
selectedMonthValue = "6";
break;
case "July":
selectedMonthValue = "7";
break;
case "August":
selectedMonthValue = "8";
break;
case "September":
selectedMonthValue = "9";
break;
case "October":
selectedMonthValue = "10";
break;
case "November":
selectedMonthValue = "11";
break;
case "December":
selectedMonthValue = "12";
break;
}
return selectedMonthValue;
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (btnEditRecord.Text == "Edit Record")
{
groupBox2.Enabled = true;
btnEditRecord.Text = "Cancel Edit";
}
else if (btnEditRecord.Text == "Cancel Edit")
{
groupBox2.Enabled = false;
btnEditRecord.Text = "Edit Record";
}
}
private void txtTransactionID_TextChanged(object sender, EventArgs e)
{
if (txtTransactionID.Text != string.Empty)
{
btnSearchByTransactionID.Enabled = true;
}
else
{
btnSearchByTransactionID.Enabled = false;
}
}
private void btnSearchByTransactionID_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select p.PaymentMode [Payment Mode],m.Month,s.Year,s.Amount,b.BankName [Bank],c.OtherPayment [Other Payment],c.TellerNo [Teller No.], c.Comment, s.TransactionID [Transaction ID],s.Date " +
"from Savings s left join Contributions c on s.SavingsID=c.SavingsID " +
"left join PaymentMode p on c.PaymentModeID=p.PaymentModeID " +
"left join MonthByName m on s.Month=m.MonthID " +
"left join Banks b on c.BankID=b.BankID " +
"where SavingSource='Contribution' and MemberID=" + memberID + " and c.TellerNo='"+ txtTransactionID.Text.Trim() +"' or s.TransactionID='"+ txtTransactionID.Text.Trim() +"' order by s.SavingsID desc";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Contributions");
DataTable dt = ds.Tables["Contributions"];
if (dt.Rows.Count > 0)
{
datGVContributions.DataSource = null;
datGVContributions.Columns.Clear();
datGVContributions.Rows.Clear();
datGVContributions.Refresh();
datGVContributions.DataSource = dt;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGVContributions.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Select Record";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
else
{
MessageBox.Show("Sorry, that Transaction ID does not exist for this member", "Edit/Update Contributuons", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void getMemberSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select MemberID, SavingsTypeID, Remark from MemberSavingsTypeAcct where MemberID=@MemberID";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "MemberSavingsTypeAcct");
DataTable dt = ds.Tables["MemberSavingsTypeAcct"];
cboMemberSavingsType.DataSource = dt;
cboMemberSavingsType.DisplayMember = "Remark";
cboMemberSavingsType.ValueMember = "SavingsTypeID";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/MainApp.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MainApp
{
public partial class MainApp : Form
{
private string userId;
private string lastname;
private string firstname;
private string loanApproval;
public MainApp(string UserID, string Lastname, string Firstname)
{
InitializeComponent();
this.IsMdiContainer = true;
userId = UserID;
lastname = Lastname;
firstname = Firstname;
loanApproval = string.Empty;
string ActivityType = "LogIn";
string Description = Lastname + " " + Firstname + " with UserID [" + userId + "] logged In";
logUserActivity(userId,ActivityType,Description);
}
private void registrationToolStripMenuItem_Click(object sender, EventArgs e)
{
AddMember addMemberForm = new AddMember();
addMemberForm.MdiParent = this;
addMemberForm.Show();
}
private void addDepartmentToolStripMenuItem_Click(object sender, EventArgs e)
{
AddDepartment addDepartment = new AddDepartment();
addDepartment.MdiParent = this;
addDepartment.Show();
}
private void viewDepartmentsToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewDepartments viewDept = new ViewDepartments();
viewDept.MdiParent = this;
viewDept.Show();
}
private void editDepartmToolStripMenuItem_Click(object sender, EventArgs e)
{
EditDepartment editDept = new EditDepartment();
editDept.MdiParent = this;
editDept.Show();
}
private void deleteDepartmentToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteDepartment delDept = new DeleteDepartment();
delDept.MdiParent = this;
delDept.Show();
}
private void addBankToolStripMenuItem_Click(object sender, EventArgs e)
{
AddBank addBank = new AddBank();
addBank.MdiParent = this;
addBank.Show();
}
private void viewBanksToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewBanks viewBanks = new ViewBanks();
viewBanks.MdiParent = this;
viewBanks.Show();
}
private void editBankToolStripMenuItem_Click(object sender, EventArgs e)
{
EditBank editBank = new EditBank();
editBank.MdiParent = this;
editBank.Show();
}
private void deleteBankToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteBank deleteBank = new DeleteBank();
deleteBank.MdiParent = this;
deleteBank.Show();
}
private void addTypeToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateSavingsType createSavingsType = new CreateSavingsType();
createSavingsType.MdiParent = this;
createSavingsType.Show();
}
private void editTypeToolStripMenuItem1_Click(object sender, EventArgs e)
{
EditSavingsType editSavingsType = new EditSavingsType();
editSavingsType.MdiParent = this;
editSavingsType.Show();
}
private void memberListToolStripMenuItem_Click(object sender, EventArgs e)
{
MembersList membersList = new MembersList();
membersList.MdiParent = this;
membersList.Show();
}
private void findMemberToolStripMenuItem_Click(object sender, EventArgs e)
{
FindMember findMember = new FindMember();
findMember.MdiParent = this;
findMember.Show();
}
private void editMemberToolStripMenuItem_Click(object sender, EventArgs e)
{
EditMember editMember = new EditMember();
editMember.MdiParent = this;
editMember.Show();
}
private void setupSavingsToolStripMenuItem_Click(object sender, EventArgs e)
{
SetUpMemberSavingsAccount setUpMemberSavingsAccount = new SetUpMemberSavingsAccount();
setUpMemberSavingsAccount.MdiParent = this;
setUpMemberSavingsAccount.Show();
}
private void editSavingsToolStripMenuItem_Click(object sender, EventArgs e)
{
EditMemberSavings editMemberSavings = new EditMemberSavings();
editMemberSavings.MdiParent = this;
editMemberSavings.Show();
}
private void makeContributionToolStripMenuItem_Click(object sender, EventArgs e)
{
MakeContributions makeContributions = new MakeContributions();
makeContributions.MdiParent = this;
makeContributions.Show();
}
private void viewContributionsToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewContributions viewContributions = new ViewContributions();
viewContributions.MdiParent = this;
viewContributions.Show();
}
private void editContributionsToolStripMenuItem_Click(object sender, EventArgs e)
{
EditContributions editContributions = new EditContributions();
editContributions.MdiParent = this;
editContributions.Show();
}
private void addCategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateLoanCategory createLoanCategory = new CreateLoanCategory();
createLoanCategory.MdiParent = this;
createLoanCategory.Show();
}
private void addTypeToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateLoanType createLoanType = new CreateLoanType();
createLoanType.MdiParent = this;
createLoanType.Show();
}
private void newApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
LoanApplication loanApplication = new LoanApplication(userId);
loanApplication.MdiParent = this;
loanApplication.Show();
}
private void loansApprovalToolStripMenuItem1_Click(object sender, EventArgs e)
{
LoanApplicationApproval loanApplicationApproval = new LoanApplicationApproval();
loanApplicationApproval.MdiParent = this;
loanApplicationApproval.Show();
}
private void postRepaymentToolStripMenuItem_Click(object sender, EventArgs e)
{
PostLoanRepayment postLoanRepayment = new PostLoanRepayment();
postLoanRepayment.MdiParent = this;
postLoanRepayment.Show();
}
private void postDeductionsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void collectiveToolStripMenuItem_Click(object sender, EventArgs e)
{
PostDeductions postDeductions = new PostDeductions(userId);
postDeductions.MdiParent = this;
postDeductions.Show();
}
private void individualToolStripMenuItem_Click(object sender, EventArgs e)
{
PostDeduction_Individual postIndividualDeduction = new PostDeduction_Individual(userId);
postIndividualDeduction.MdiParent = this;
postIndividualDeduction.Show();
}
private void viewSavingsToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewSavings viewSavings = new ViewSavings();
viewSavings.MdiParent = this;
viewSavings.Show();
}
private void membersListToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmReportMembers frmReportMembers = new FrmReportMembers();
frmReportMembers.MdiParent = this;
frmReportMembers.Show();
}
private void MainApp_Load(object sender, EventArgs e)
{
//((MainApp)this.MdiParent).toolStripStatusLoggedInUser.Text = "Seyibabs";
lblLoggedInUserID.Text = userId;
lblLoggedInUserName.Text = lastname.ToString().ToUpper() + ' ' + firstname.ToString();
//toolStripStatusOps.Text = "Progress...";
//statusStrip1.Refresh();
toolStripStatusLblSpring.Text = string.Empty;
toolStripStatusLblLoggedInUser.Text = "Logged In User: " + lblLoggedInUserName.Text;
}
private void memberProfileToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmGenerateMemberProfileByFileNo frmGenerateMemberProfileByFileNo = new FrmGenerateMemberProfileByFileNo();
frmGenerateMemberProfileByFileNo.MdiParent = this;
frmGenerateMemberProfileByFileNo.Show();
}
private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);
}
private void tileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical);
}
private void tileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.TileHorizontal);
}
private void exitApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult res = MessageBox.Show("Do you really wish to Exit Application?", "Application Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
Application.Exit();
}
}
private void logUserActivity(string userId, string ActivityType,string Description)
{
ActivityLog.logActivity(userId, ActivityType, Description);
}
private void viewDeductionsToolStripMenuItem_Click(object sender, EventArgs e)
{
string month = string.Empty;
string year = string.Empty;
ViewDeductions viewductions = new ViewDeductions(month,year);
viewductions.MdiParent = this;
viewductions.Show();
}
private void withdrawalToolStripMenuItem_Click(object sender, EventArgs e)
{
MembershipWithdrawal withdrawal = new MembershipWithdrawal();
withdrawal.MdiParent = this;
withdrawal.Show();
}
private void savingsForwardToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void newPostingToolStripMenuItem_Click(object sender, EventArgs e)
{
SavingsForward savingsForward = new SavingsForward(userId);
savingsForward.MdiParent = this;
savingsForward.Show();
}
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
EditSavingsForward editSavingsForward = new EditSavingsForward(userId);
editSavingsForward.MdiParent = this;
editSavingsForward.Show();
}
private void toolStripButtonNewMember_Click(object sender, EventArgs e)
{
registrationToolStripMenuItem_Click(sender, e);
}
private void toolStripButtonMembers_Click(object sender, EventArgs e)
{
findMemberToolStripMenuItem_Click(sender, e);
}
private void toolStripButtonFindMember_Click(object sender, EventArgs e)
{
findMemberToolStripMenuItem_Click(sender, e);
}
private void toolStripButtonEditMember_Click(object sender, EventArgs e)
{
editMemberToolStripMenuItem_Click(sender, e);
}
private void toolStripButtonSavings_Click(object sender, EventArgs e)
{
viewSavingsToolStripMenuItem_Click(sender, e);
}
private void toolStripButtonEditSavings_Click(object sender, EventArgs e)
{
editSavingsToolStripMenuItem_Click(sender, e);
}
private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
DeleteSavingsForward deleteSavingsForward = new DeleteSavingsForward();
deleteSavingsForward.MdiParent = this;
deleteSavingsForward.Show();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteLoanApplication deleteLoanApplication = new DeleteLoanApplication();
deleteLoanApplication.MdiParent = this;
deleteLoanApplication.Show();
}
private void membershipToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void makeWithdrawalToolStripMenuItem_Click(object sender, EventArgs e)
{
MakeWithdrawal makewithdrawal = new MakeWithdrawal(userId);
makewithdrawal.MdiParent = this;
makewithdrawal.Show();
}
private void deleteWithdrawalToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteWithdrawal deleteWithdrawal = new DeleteWithdrawal(userId);
deleteWithdrawal.MdiParent = this;
deleteWithdrawal.Show();
}
private void newLoanBFToolStripMenuItem_Click(object sender, EventArgs e)
{
NewLoanBroughtForward newLoanBroughtForward = new NewLoanBroughtForward(userId);
newLoanBroughtForward.MdiParent = this;
newLoanBroughtForward.Show();
}
private void editToolStripMenuItem1_Click(object sender, EventArgs e)
{
EditLoansBroughtForward editLoansBroughtForward = new EditLoansBroughtForward(userId);
editLoansBroughtForward.MdiParent = this;
editLoansBroughtForward.Show();
}
private void deleteToolStripMenuItem2_Click(object sender, EventArgs e)
{
DeleteLoanBroughtForward deleteLoanBroughtForward = new DeleteLoanBroughtForward(userId);
deleteLoanBroughtForward.MdiParent = this;
deleteLoanBroughtForward.Show();
}
private void viewLoansToolStripMenuItem_Click(object sender, EventArgs e)
{
loanApproval = "Yes";
ViewLoanApplication viewLoanApplication = new ViewLoanApplication(loanApproval);
viewLoanApplication.MdiParent = this;
viewLoanApplication.Show();
}
private void viewApplicationsToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewLoanApplication viewApplicationLoan = new ViewLoanApplication(loanApproval);
viewApplicationLoan.MdiParent = this;
viewApplicationLoan.Show();
}
private void deleteDeductionsToolStripMenuItem_Click(object sender, EventArgs e)
{
UnpostDeductions unpostDeductions = new UnpostDeductions(userId);
unpostDeductions.MdiParent = this;
unpostDeductions.Show();
}
private void memberSavingsToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmRprtMemberSavings frmRprtMemberSavings = new FrmRprtMemberSavings();
frmRprtMemberSavings.MdiParent = this;
frmRprtMemberSavings.Show();
}
}
}
<file_sep>/MainApp/MainApp/Classes/ExportData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace MainApp
{
public class ExportData
{
public void ExportToExcel(DataTable dt, SaveFileDialog saveFD)
{
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
//Headers
for (int i = 0; i < dt.Columns.Count; i++)
{
ws.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
//content
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
ws.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
}
}
ws.Name = dt.TableName;
string SavedFile = string.Empty;
saveFD.InitialDirectory = "C:";
saveFD.Title = "Export File to Location with FileName";
saveFD.FileName = "";
saveFD.Filter = "Excel Files|*.xls|All Files|*.*";
try
{
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
SavedFile = saveFD.FileName;
//wb.SaveAs(@"C:\Users\seyibabs\Documents\exportData.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.SaveAs(@SavedFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.Close(true, misValue, misValue);
app.Quit();
MessageBox.Show("Information item has been exported to the Saved File and Location", "Contribution", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
<file_sep>/MainApp/MainApp/Settings/ShowActivityLog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class ShowActivityLog : Form
{
public ShowActivityLog()
{
InitializeComponent();
}
private void ShowActivityLog_Load(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select l.ActivityLogID as [ActivityLog ID],l.UserID,u.LastName + ' ' + u.FirstName as [FullName],u.Role,l.ActivityType,l.Description " +
"from ActivityLog l left join Users u";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "ActivityLog");
DataTable dt = ds.Tables["ActivityLog"];
datGrdViewActivityLog.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
<file_sep>/MainApp/MainApp/Loans/DeleteLoanBroughtForward.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class DeleteLoanBroughtForward : Form
{
private string userId;
private string strFilter;
public DeleteLoanBroughtForward(string UserID)
{
this.userId = UserID;
InitializeComponent();
}
private void DeleteLoanBroughtForward_Load(object sender, EventArgs e)
{
strFilter = string.Empty;
loadLoansBroughtForward();
}
private void loadLoansBroughtForward()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = string.Empty;
if (strFilter == string.Empty)
{
strQuery = "Select l.LoansID,a.LoanApplicationID,m.FileNo,m.Title + ' ' + m.FirstName + ' ' + m.MiddleName + ' ' + m.LastName as 'Full Name'," +
"a.LoanAmount 'Amount', l.RepaymentAmount 'Repayment Amt.',l.AmountPaid 'Amt. Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status',l.PaymentFinished 'Payment Finished',l.DateFinishedPayment 'Finished Paying',l.TransactionID," +
"l.DateCreated 'Date' from LoanApplication a " +
"inner join Loans l on l.LoanApplicationID=a.LoanApplicationID " +
"inner join Members m on a.MemberID=m.MemberID " +
"where l.TransactionID LIKE '%LBF%' " +
"order by l.LoansID desc";
}
else
{
strQuery = "Select l.LoansID,a.LoanApplicationID,m.FileNo,m.Title + ' ' + m.FirstName + ' ' + m.MiddleName + ' ' + m.LastName as 'Full Name'," +
"a.LoanAmount 'Amount', l.RepaymentAmount 'Repayment Amt.',l.AmountPaid 'Amt. Paid', l.OutstandingAmount 'Outstanding Amt.',l.PaymentStatus 'Payment Status',l.PaymentFinished 'Payment Finished',l.DateFinishedPayment 'Finished Paying',l.TransactionID," +
"l.DateCreated 'Date' from LoanApplication a " +
"inner join Loans l on l.LoanApplicationID=a.LoanApplicationID " +
"inner join Members m on a.MemberID=m.MemberID " +
"where l.TransactionID LIKE '%LBF%' and m.FileNo='" + strFilter + "' " +
"order by l.LoansID desc";
}
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
datGrdVwLoansForward.DataSource = null;
datGrdVwLoansForward.Columns.Clear();
datGrdVwLoansForward.Rows.Clear();
datGrdVwLoansForward.Refresh();
try
{
conn.Open();
da.Fill(ds, "Loans");
DataTable dt = ds.Tables["Loans"];
datGrdVwLoansForward.DataSource = dt;
lblRecordNo.Text = "No. of Record: " + dt.Rows.Count;
datGrdVwLoansForward.Columns["LoansID"].Visible = false;
datGrdVwLoansForward.Columns["LoanApplicationID"].Visible = false;
datGrdVwLoansForward.Columns["Repayment Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Repayment Amt."].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Amt. Paid"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Amt. Paid"].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Outstanding Amt."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
datGrdVwLoansForward.Columns["Outstanding Amt."].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["FileNo"].Width = 50;
datGrdVwLoansForward.Columns["Payment Status"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoansForward.Columns["Payment Finished"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
datGrdVwLoansForward.Columns["Payment Status"].Width = 80;
datGrdVwLoansForward.Columns["Payment Finished"].Width = 80;
datGrdVwLoansForward.Columns["Amount"].DefaultCellStyle.Format = "N2";
datGrdVwLoansForward.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
datGrdVwLoansForward.Columns.Add(btn);
btn.HeaderText = "Action";
btn.Text = "Delete";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void txtFileNo_TextChanged(object sender, EventArgs e)
{
if (txtFileNo.Text != string.Empty)
{
btnFileNoSearch.Enabled = true;
}
else
{
btnFileNoSearch.Enabled = false;
}
}
private void btnFileNoSearch_Click(object sender, EventArgs e)
{
if (txtFileNo.Text != string.Empty)
{
strFilter = txtFileNo.Text.ToUpper();
loadLoansBroughtForward();
}
}
private void datGrdVwLoansForward_CellClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(datGrdVwLoansForward.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
MessageBox.Show(e.ColumnIndex.ToString());
}
}
}
<file_sep>/MainApp/MainApp/RprtMemberSavings.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MainApp
{
public partial class RprtMemberSavings : Form
{
string strFileNo;
DateTime strFromDt;
DateTime strToDt;
public RprtMemberSavings(string strFNo,string strFromDt,string strToDt)
{
InitializeComponent();
this.strFileNo = strFNo;
this.strFromDt = Convert.ToDateTime(Convert.ToDateTime(strFromDt).ToShortDateString());
this.strToDt = Convert.ToDateTime(Convert.ToDateTime(strToDt).ToShortDateString());
}
private void RprtMemberSavings_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DatasetMembers.Savings' table. You can move, or remove it, as needed.
this.SavingsTableAdapter.FillByMemberSavings(this.DatasetMembers.Savings, strFileNo, strFromDt, strToDt);
// TODO: This line of code loads data into the 'DatasetMembers.Members' table. You can move, or remove it, as needed.
this.MembersTableAdapter.Fill(this.DatasetMembers.Members);
this.reportViewer1.RefreshReport();
}
}
}
<file_sep>/MainApp/MainApp/Savings/SetUpMemberSavingsAccount.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MainApp
{
public partial class SetUpMemberSavingsAccount : Form
{
string memberFileNo = null;
int myselectedmemberID = 0;
public SetUpMemberSavingsAccount()
{
InitializeComponent();
}
private void SetUpMemberSavingsAccount_Load(object sender, EventArgs e)
{
//ListView Properties Settings
lstVSavings.View = View.Details;
lstVSavings.FullRowSelect = true;
//ListView Columns Name
lstVSavings.Columns.Add("ID", 0);
lstVSavings.Columns.Add("Savings Type", 300);
lstVSavings.Columns.Add("Amount", 200);
lstVSavings.Columns.Add("Date Created", 200);
txtRegularSavings.TextAlign = HorizontalAlignment.Right;
//txtShares.TextAlign = HorizontalAlignment.Right;
txtSavingsAmount.TextAlign = HorizontalAlignment.Right;
}
private void btnFindRecord_Click(object sender, EventArgs e)
{
memberFileNo = txtFileNo.Text.Trim();
setAndClearFieldsToDefault();
if (txtFileNo.Text == string.Empty)
{
MessageBox.Show("File No is required to perform a search", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
loadMemberRegisteredSavingsType();
}
if (cboSavingsType.Items.Count==0 && myselectedmemberID != 0 )
{
//Load Savings Type after loading of Member's Savings Type
loadSavingsType();
}
}
private void loadMemberRegisteredSavingsType()
{
decimal totalSavings = 0;
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select m.MemberID, m.FileNo, m.Title + ' ' + m.LastName + ' ' + m.MiddleName + ' ' + m.FirstName as [FullName], "+
"m.Photo, m.DateCreated as RegDateCreated, t.SavingsName, s.SavingsAcctID, s.Amount, s.Remark, " +
"s.DateCreated as SavingsDateCreated from Members m left join MemberSavingsTypeAcct s on m.MemberID=s.MemberID " +
"left join SavingsType t on s.SavingsTypeID=t.SavingsTypeID where m.FileNo='" + txtFileNo.Text.Trim() + "'";
/**
string strSharesQuery = "Select m.MemberID, m.FileNo, s.Shares from Members m " +
"inner join Shares s on m.MemberID=s.MemberID where m.FileNo='" + txtFileNo.Text.Trim() + "'";
**/
SqlCommand cmd = new SqlCommand(strQuery, conn);
//SqlCommand cmdShares = new SqlCommand(strSharesQuery, conn);
try
{
conn.Open();
/****Execute and read shares --- Modification after first Observation meeting with Client
SqlDataReader reader = cmdShares.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
txtShares.Text = CheckForNumber.formatCurrency(reader["Shares"].ToString());
}
}
reader.Close();
*
* ***/
//Execute and read Regular Savings and other savings
SqlDataReader reader = cmd.ExecuteReader();
int recordCount = 0;
lstVSavings.Items.Clear();
//Check if record is found and start performing operation
if (reader.HasRows)
{
string paths = PhotoPath.getPath();
picMember.Visible = true;
lblMemberProfileInfo.Visible = true;
lblRegistrationDate.Visible = true;
#region Read Data from Reader
while (reader.Read())
{
recordCount++;
if (recordCount == 1)
{
//MessageBox.Show("Record Count: " + recordCount.ToString());
if (reader["Photo"].ToString() != string.Empty)
{
picMember.Image = Image.FromFile(paths + "\\photos\\" + reader["Photo"].ToString());
}
else
{
picMember.Image = Image.FromFile(paths + "\\photos\\profile_img.png");
}
lblMemberProfileInfo.Text = reader["FullName"].ToString() + "\n" + reader["FileNo"].ToString();
lblRegistrationDate.Text = "Member since " + string.Format("{0:ddd, MMM d, yyyy}", reader["RegDateCreated"]);
myselectedmemberID = (int)reader["MemberID"];
}
if (reader["Remark"].ToString() == "Shares Savings")
{
txtRegularSavings.Text = CheckForNumber.formatCurrency(reader["Amount"].ToString());
totalSavings += Convert.ToDecimal(reader["Amount"]);
continue;
}
string[] row = {reader["SavingsAcctID"].ToString(), reader["Remark"].ToString(), CheckForNumber.formatCurrency(reader["Amount"].ToString()), string.Format("{0:ddd, MMM d, yyyy}", reader["SavingsDateCreated"])};
ListViewItem item = new ListViewItem(row);
lstVSavings.Items.Add(item);
totalSavings += Convert.ToDecimal(reader["Amount"]);
}
#endregion
}
else
{
MessageBox.Show("Sorry, Record with that FileNo is not found", "Members Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
lblRecordNo.Text = "No. of Records : " + recordCount;
lblTotalSavings.Text = "Savings Total: " + CheckForNumber.formatCurrency2(totalSavings.ToString());
lblTotalSavings.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "-- loadMemberRegisteredSavingsType -- ");
}
finally
{
conn.Close();
}
}
private void cboSavingsType_Click(object sender, EventArgs e)
{
}
private void loadSavingsType()
{
if (memberFileNo == null || memberFileNo == string.Empty)
{
MessageBox.Show("Select a member record ");
}
else
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Select SavingsTypeID, SavingsName from SavingsType order by SavingsName";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "SavingsType");
DataTable dt = ds.Tables["SavingsType"];
cboSavingsType.Items.Clear();
DataRow row = dt.NewRow();
row["SavingsName"] = "-- Select Savings Type to Add --";
dt.Rows.InsertAt(row, 0);
cboSavingsType.DisplayMember = "SavingsName";
cboSavingsType.ValueMember = "SavingsTypeID";
cboSavingsType.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "--loadSavingsType--");
}
finally
{
conn.Close();
}
}
}
private void cboSavingsType_SelectedIndexChanged(object sender, EventArgs e)
{
string selSavingsType = cboSavingsType.Text;
bool matchFound = false;
if (cboSavingsType.Text != "-- Select Savings Type to Add --")
{
for (int i = 0; i < lstVSavings.Items.Count; i++)
{
//MessageBox.Show("SelSavingsType = " + selSavingsType.ToString() + " - listView Item : " + lstVSavings.Items[i].SubItems[0].Text + " -- savingsTypeID -- " + cboSavingsType.SelectedValue.ToString());
if (selSavingsType == lstVSavings.Items[i].SubItems[1].Text)
{
matchFound = true;
}
}
if (matchFound == false)
{
txtSavingsAmount.ReadOnly = false;
txtSavingsAmount.Enabled = true;
btnAddSavingsType.Enabled = true;
}
else if (matchFound == true)
{
MessageBox.Show("You already have [" + cboSavingsType.Text + "] Savings Type Created\nYou can't run duplicate accounts.", "SetUp Savings Account", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSavingsAmount.ReadOnly = true;
txtSavingsAmount.Enabled = false;
btnAddSavingsType.Enabled = false;
}
}
}
private void txtSavingsAmount_Leave(object sender, EventArgs e)
{
bool isNumeric = CheckForNumber.isNumeric(txtSavingsAmount.Text.Trim());
if (isNumeric)
{
txtSavingsAmount.Text = CheckForNumber.formatCurrency(txtSavingsAmount.Text.Trim());
}
else
{
MessageBox.Show("The amount is invalid. Please enter numeric values.", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAddSavingsType_Click(object sender, EventArgs e)
{
if (txtSavingsAmount.Text.Trim() != string.Empty)
{
DialogResult result = MessageBox.Show("Do you wish to create [" + cboSavingsType.Text + "] Savings Type with Amount of [" + txtSavingsAmount.Text + "]", "SetUp Member Savings", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
addNewSavingsType();
}
}
else
{
MessageBox.Show("Savings Amount is required!", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void addNewSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into MemberSavingsTypeAcct(MemberID,SavingsTypeID,Amount,Remark)Values(@MemberID,@SavingsTypeID,@Amount,@Remark)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
#region cmd parameters
cmd.Parameters.Add("@MemberID", System.Data.SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = myselectedmemberID;
cmd.Parameters.Add("@SavingsTypeID", System.Data.SqlDbType.Int);
cmd.Parameters["@SavingsTypeID"].Value = cboSavingsType.SelectedValue;
cmd.Parameters.Add("@Amount", System.Data.SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = txtSavingsAmount.Text.Trim();
cmd.Parameters.Add("@Remark", System.Data.SqlDbType.NVarChar);
cmd.Parameters["@Remark"].Value = cboSavingsType.Text;
#endregion
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Savings Types [" + cboSavingsType.Text + "] has been successfully created.", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadMemberRegisteredSavingsType();
setAndClearFieldsToDefault();
}
else
{
MessageBox.Show("An Error has Occurred Creating Savings Type!", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void setAndClearFieldsToDefault()
{
txtSavingsAmount.Clear();
txtSavingsAmount.Enabled = false;
txtSavingsAmount.ReadOnly = true;
btnAddSavingsType.Enabled = false;
btnRemoveSavingsType.Enabled = false;
}
private void btnRemoveSavingsType_Click(object sender, EventArgs e)
{
if (lstVSavings.SelectedItems.Count != 0)
{
DialogResult result = MessageBox.Show("Do You Really Wish to Remove [" + lstVSavings.SelectedItems[0].SubItems[1].Text + "] Savings Type\nfrom Member's Savings Account", "SetUp Member Savings", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
removeSelectedSavingsType();
}
}
else
{
MessageBox.Show("Select a Savings Type from the List to Remove", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void lstVSavings_Click(object sender, EventArgs e)
{
btnRemoveSavingsType.Enabled = true;
}
private void removeSelectedSavingsType()
{
SqlConnection conn = ConnectDB.GetConnection();
string selSavingsAcctID = lstVSavings.SelectedItems[0].SubItems[0].Text;
string selSavingsName = lstVSavings.SelectedItems[0].SubItems[1].Text;
string strQuery = "Delete from MemberSavingsTypeAcct where SavingsAcctID=@SavingsAcctID";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@SavingsAcctID", System.Data.SqlDbType.Int);
cmd.Parameters["@SavingsAcctID"].Value = Convert.ToInt16(selSavingsAcctID);
try
{
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Savings Type [" + selSavingsName + "] has been Successfully Removed\n from Member's Account.", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadMemberRegisteredSavingsType();
}
else
{
MessageBox.Show("An Error Occurred Removing [" + selSavingsName + "] Savings Type from Member's Account", "SetUp Member Savings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void lstVSavings_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/MainApp/MainApp/Classes/Deduction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace MainApp
{
class Deduction
{
#region postSavings
public string postSavings(SqlConnection conn, SqlCommand cmd, SqlTransaction sqlTrans, int memberID, string transactionID, decimal totalSavings, int numOfRows, int errorflag, int selectedMonth, int selectedYear)
{
//Record savings in Savings Table
cmd.CommandText = "Insert into Savings(MemberID,SavingSource,Amount,Month,Year,TransactionID)" +
"Values(@MemberID,@SavingSource,@Amount,@Month,@Year,@TransactionID)";
#region cmd parameters savings
cmd.Parameters.Add("@MemberID", SqlDbType.Int);
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@SavingSource", SqlDbType.NVarChar, 40);
cmd.Parameters["@SavingSource"].Value = "Deduction";
cmd.Parameters.Add("@Amount", SqlDbType.Decimal);
cmd.Parameters["@Amount"].Value = totalSavings;
cmd.Parameters.Add("@Month", SqlDbType.Int);
cmd.Parameters["@Month"].Value = selectedMonth;
cmd.Parameters.Add("@Year", SqlDbType.Int);
cmd.Parameters["@Year"].Value = selectedYear;
cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar, 100);
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
return ("Saved Amount: " + totalSavings + "\n Savings status: " + numOfRows);
}
#endregion end postSavings
#region postLoans
public string postLoans(SqlConnection conn, SqlCommand cmd, SqlTransaction sqlTrans, int memberID, string transactionID, int currentRecord, int selectedMonth, int selectedYear, int numOfRows, int errorflag, decimal monthlyLoanRepayment)
{
//if loan repayment is more than zero perform loan deductions
string oppStatus = null;
while (monthlyLoanRepayment > 0)
{
string sqlQuery = "Select a.MonthlyRepayment as MonthlyRepayment,l.AmountPaid,l.RepaymentAmount,l.OutstandingAmount,l.LoansID,l.TransactionID from LoanApplication a " +
"inner join Loans l on a.LoanApplicationID = l.LoanApplicationID where a.MemberID=@MemberID and l.OutstandingAmount<>0";
cmd.CommandText = sqlQuery;
SqlDataReader readerCount = cmd.ExecuteReader();
int recFound = readerCount.Cast<object>().Count();
readerCount.Close();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
decimal originalLoanPayment = monthlyLoanRepayment;
monthlyLoanRepayment = payLoanDeduction(cmd, monthlyLoanRepayment, transactionID, recFound, reader, numOfRows, errorflag);
oppStatus += "MonthLoanRepayment found: " + originalLoanPayment + "\n";
}
}
else
{
//Deposit in Member Savings if there is not other Loan to service with the excess cash"
reader.Close();
depositExcessIntoSavings(cmd, monthlyLoanRepayment, memberID, transactionID, selectedMonth, selectedYear, numOfRows, errorflag);
oppStatus += "Deposit into savings : " + monthlyLoanRepayment + "\nError Flag: " + errorflag;
break;
}
}//end of while (monthLoanRepayment>outstandingAmount)
return oppStatus;
}
#endregion
#region payLoanDeduction
private decimal payLoanDeduction(SqlCommand cmd, decimal monthlyLoanRepayment, string transactionID, int recFound, SqlDataReader reader, int numOfRows, int errorflag)
{
//decimal monthlyRepayment = Convert.ToDecimal(reader["MonthlyRepayment"]);
decimal monthlyRepayment = monthlyLoanRepayment;
decimal amountPaid = Convert.ToDecimal(reader["AmountPaid"]);
decimal repaymentAmount = Convert.ToDecimal(reader["RepaymentAmount"]);
decimal outstandingAmount = Convert.ToDecimal(reader["OutstandingAmount"]);
int loanID = (int)reader["LoansID"];
string repayTransactionID = transactionID;
string loanTransactionID = reader["TransactionID"].ToString();
reader.Close();
decimal new_outstandingAmount;
decimal new_AmountPaid;
decimal new_PaidCumulative;
string new_paymentStatus;
string new_paymentFinished;
decimal excess = 0;
#region if monthlyrepayment is less than outstanding repayment
if (monthlyRepayment <= outstandingAmount)
{
#region monthlyRepayment is less than or equal to the outstandingAmount
new_AmountPaid = amountPaid + monthlyRepayment;
new_outstandingAmount = repaymentAmount - new_AmountPaid;
new_PaidCumulative = new_AmountPaid;
//check if loan has been completely paid
if (new_outstandingAmount == 0)
{
new_paymentStatus = "PAID";
new_paymentFinished = "Yes";
}
else
{
new_paymentStatus = "Paying";
new_paymentFinished = "No";
}
string strLoanRepayment = "Insert into LoanRepayment(MemberID,LoanID,TransactionID,RepaymentAmount,PaidAmount,Outstanding,PaidCumulative,Excess,RepayTransactID)" +
"values(@MemberID,@LoanID,@TransactionID,@RepaymentAmount,@PaidAmount,@Outstanding,@PaidCumulative,@Excess,@RepayTransactID)";
cmd.CommandText = strLoanRepayment;
//set parameters for cmd
#region cmd parameters for LoanRepayment
cmd.Parameters.Add("@LoanID", SqlDbType.Int);
cmd.Parameters["@LoanID"].Value = loanID;
cmd.Parameters["@TransactionID"].Value = loanTransactionID;
cmd.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmd.Parameters["@RepaymentAmount"].Value = repaymentAmount;
cmd.Parameters.Add("@PaidAmount", SqlDbType.Decimal);
cmd.Parameters["@PaidAmount"].Value = monthlyRepayment;
cmd.Parameters.Add("@Outstanding", SqlDbType.Decimal);
cmd.Parameters["@Outstanding"].Value = new_outstandingAmount;
cmd.Parameters.Add("@PaidCumulative", SqlDbType.Decimal);
cmd.Parameters["@PaidCumulative"].Value = new_PaidCumulative;
cmd.Parameters.Add("@Excess", SqlDbType.Decimal);
cmd.Parameters["@Excess"].Value = excess;
cmd.Parameters.Add("@RepayTransactID", SqlDbType.NVarChar, 50);
cmd.Parameters["@RepayTransactID"].Value = repayTransactionID;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
string strLoan = "update Loans set AmountPaid=@AmountPaid,OutstandingAmount=@OutstandingAmount,PaymentStatus=@PaymentStatus,PaymentFinished=@PaymentFinished " +
"where LoansID=@LoansID";
cmd.CommandText = strLoan;
//set parameters for cmd
#region cmd parameters for Loans
cmd.Parameters.Add("@AmountPaid", SqlDbType.Decimal);
cmd.Parameters["@AmountPaid"].Value = new_AmountPaid;
cmd.Parameters.Add("@OutstandingAmount", SqlDbType.Decimal);
cmd.Parameters["@OutstandingAmount"].Value = new_outstandingAmount;
cmd.Parameters.Add("@PaymentStatus", SqlDbType.NVarChar, 10);
cmd.Parameters["@PaymentStatus"].Value = new_paymentStatus;
cmd.Parameters.Add("@PaymentFinished", SqlDbType.NVarChar, 5);
cmd.Parameters["@PaymentFinished"].Value = new_paymentFinished;
cmd.Parameters.Add("@LoansID", SqlDbType.Int);
cmd.Parameters["@LoansID"].Value = loanID;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
//No need to go through the loop, so break out by turning monthLoanRepayment to zero (excess = 0; monthlyLoanRepayment = 0)
monthlyLoanRepayment = excess;
#endregion end of monthlyrepayment is less than outstanding repayment
}
else if (monthlyRepayment > outstandingAmount)
{
//if the monthlyLoanRepayment is more than the outstanding amount, that means there will
//be so excess left of the monthLoanRepayment. The excess should be used to pay for subsquent loan
//repayment if it exist or deposited in the member savings.
#region monthlyRepayment is greater than outstandingAmount
new_AmountPaid = repaymentAmount;
new_outstandingAmount = 0;
new_PaidCumulative = new_AmountPaid;
excess = monthlyRepayment - outstandingAmount;
//Take the excess from what is left after monthly repayment and put it into monthlyLoanRepayment for subequent
//operation for further loan repayment or depositing into member's savings
monthlyLoanRepayment = excess;
//check if loan has been completely paid and set status appropriately
if (new_outstandingAmount == 0)
{
new_paymentStatus = "PAID";
new_paymentFinished = "Yes";
}
else
{
new_paymentStatus = "Paying";
new_paymentFinished = "No";
}
string strLoanRepayment = "Insert into LoanRepayment(MemberID,LoanID,TransactionID,RepaymentAmount,PaidAmount,Outstanding,PaidCumulative,Excess)" +
"values(@MemberID,@LoanID,@TransactionID,@RepaymentAmount,@PaidAmount,@Outstanding,@PaidCumulative,@Excess)";
cmd.CommandText = strLoanRepayment;
//set parameters for cmd
#region cmd parameters for LoanRepayment
cmd.Parameters.Add("@LoanID", SqlDbType.Int);
cmd.Parameters["@LoanID"].Value = loanID;
cmd.Parameters.Add("@RepaymentAmount", SqlDbType.Decimal);
cmd.Parameters["@RepaymentAmount"].Value = repaymentAmount;
cmd.Parameters.Add("@PaidAmount", SqlDbType.Decimal);
cmd.Parameters["@PaidAmount"].Value = monthlyRepayment;
cmd.Parameters.Add("@Outstanding", SqlDbType.Decimal);
cmd.Parameters["@Outstanding"].Value = new_outstandingAmount;
cmd.Parameters.Add("@PaidCumulative", SqlDbType.Decimal);
cmd.Parameters["@PaidCumulative"].Value = new_PaidCumulative;
cmd.Parameters.Add("@Excess", SqlDbType.Decimal);
cmd.Parameters["@Excess"].Value = excess;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
string strLoan = "update Loans set AmountPaid=@AmountPaid,OutstandingAmount=@OutstandingAmount,PaymentStatus=@PaymentStatus,PaymentFinished=@PaymentFinished " +
"where LoansID=@LoansID";
cmd.CommandText = strLoan;
//set parameters for cmd
#region cmd parameters for Loans
cmd.Parameters.Add("@AmountPaid", SqlDbType.Decimal);
cmd.Parameters["@AmountPaid"].Value = new_AmountPaid;
cmd.Parameters.Add("@OutstandingAmount", SqlDbType.Decimal);
cmd.Parameters["@OutstandingAmount"].Value = new_outstandingAmount;
cmd.Parameters.Add("@PaymentStatus", SqlDbType.NVarChar, 10);
cmd.Parameters["@PaymentStatus"].Value = new_paymentStatus;
cmd.Parameters.Add("@PaymentFinished", SqlDbType.NVarChar, 5);
cmd.Parameters["@PaymentFinished"].Value = new_paymentFinished;
cmd.Parameters.Add("@LoansID", SqlDbType.Int);
cmd.Parameters["@LoansID"].Value = loanID;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
#endregion
}
#endregion end of if monthlyRepayment <= outstandingAmount
return monthlyLoanRepayment;
}
#endregion payLoanDeduction
#region depositExcessIntoSavings
private void depositExcessIntoSavings(SqlCommand cmd, decimal monthlyLoanRepayment, int memberID, string transactionID, int selectedMonth, int selectedYear, int numOfRows, int errorflag )
{
string sqlQuery = "Insert into Savings(MemberID,SavingSource,Amount,Month,Year,TransactionID) " +
"Values(@MemberID,@SavingSource,@Amount,@Month,@Year,@TransactionID)";
cmd.CommandText = sqlQuery;
#region cmd Parameters
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters["@SavingSource"].Value = "Deduction - Loan Repayment Excess";
cmd.Parameters["@Amount"].Value = monthlyLoanRepayment;
cmd.Parameters["@Month"].Value = selectedMonth;
cmd.Parameters["@Year"].Value = selectedYear;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion end cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
}
#endregion end depositExcessIntoSavings
#region Record Deduction Method
public string recordDeduction(SqlCommand cmd, int memberID, string transactionID, int currentRecord, int selectedMonth, int selectedYear, decimal lstAllSavingsDeduction, decimal lstAllLoansDeduction, decimal lstTotalDeductions, int numOfRows, int errorflag)
{
string strQuery = "Insert into Deductions(Month,Year,MemberID,Savings,Loans,Total,TransactionID) " +
"Values(@Month,@Year,@MemberID,@Savings,@Loans,@Total,@TransactionID)";
cmd.CommandText = strQuery;
#region cmd parameters
cmd.Parameters["@Month"].Value = selectedMonth;
cmd.Parameters["@Year"].Value = selectedYear;
cmd.Parameters["@MemberID"].Value = memberID;
cmd.Parameters.Add("@Savings", SqlDbType.Decimal);
cmd.Parameters["@Savings"].Value = lstAllSavingsDeduction;
cmd.Parameters.Add("@Loans", SqlDbType.Decimal);
cmd.Parameters["@Loans"].Value = lstAllLoansDeduction;
cmd.Parameters.Add("@Total", SqlDbType.Decimal);
cmd.Parameters["@Total"].Value = lstTotalDeductions;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; };
//return "Savings: " + lstAllSavingsDeduction + "\nLoans: " + lstAllLoansDeduction +"\nTotal: " + lstTotalDeductions;
return numOfRows.ToString();
}
#endregion Record Deduction Method
#region Record Deduction Details
public string recordDeductionDetails(SqlCommand cmd, int memberID, string transactionID, int currentRecord, int numOfRows, int errorflag, decimal lstAllSavingsDeduction, decimal lstAllLoansDeduction, string repaymentLoanType,bool servicingLoan, bool loanMoreThanSavings)
{
//retrieve the DeductionID for this Deduction Operation
string strQuery = "Select DeductionID,TransactionID from Deductions where TransactionID=@TransactionID and MemberID=@MemberID";
cmd.CommandText = strQuery;
#region cmd parameters
cmd.Parameters["@TransactionID"].Value = transactionID;
cmd.Parameters["@MemberID"].Value = memberID;
#endregion
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int deductionID = (int)reader["DeductionID"];
reader.Close();
//Get the savings of the member that amounts for the total monthly savings
strQuery = "Select MemberID,Amount,Remark,SavingsTypeID from MemberSavingsTypeAcct where MemberID=@MemberID";
cmd.CommandText = strQuery;
#region cmd parameters;
cmd.Parameters["@MemberID"].Value = memberID;
#endregion
Hashtable memberSavings = new Hashtable();
Hashtable memberSavingsType = new Hashtable();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
memberSavings.Add(reader["Remark"], reader["Amount"]);
memberSavingsType.Add(reader["Remark"], reader["SavingsTypeID"]);
}
reader.Close();
}
//Insert Savings into DeductionsDetails
strQuery = "Insert into DeductionDetails(DeductionID,DeductionType,SavingsTypeID,Amount,Remarks,TransactionID)Values" +
"(@DeductionID,@DeductionType,@SavingsTypeID,@Amount,@Remarks,@TransactionID)";
cmd.CommandText = strQuery;
cmd.Parameters.Add("@DeductionID", SqlDbType.Int);
cmd.Parameters.Add("@DeductionType", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("@SavingsTypeID", SqlDbType.NVarChar, 10);
cmd.Parameters.Add("@Remarks", SqlDbType.NVarChar,400);
if ((lstAllLoansDeduction==0) && (lstAllSavingsDeduction>0))
{
foreach (DictionaryEntry child in memberSavings)
{
#region cmd parameters
cmd.Parameters["@DeductionID"].Value = deductionID;
cmd.Parameters["@DeductionType"].Value = child.Key;
cmd.Parameters["@SavingsTypeID"].Value = memberSavingsType[child.Key];
cmd.Parameters["@Amount"].Value = child.Value;
cmd.Parameters["@Remarks"].Value = string.Empty;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
// MessageBox.Show(child.Key.ToString() + " - " + child.Value.ToString() + "\nError Flag: " + errorflag);
}
}
else if ((lstAllLoansDeduction>0) && (lstAllSavingsDeduction == 0))
{
#region cmd parameters
cmd.Parameters["@DeductionId"].Value = deductionID;
cmd.Parameters["@DeductionType"].Value = "Savings";
cmd.Parameters["@SavingsTypeID"].Value = string.Empty;
cmd.Parameters["@Amount"].Value = 0;
cmd.Parameters["@Remarks"].Value = "No Savings, loan repayment.";
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion end of cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
}
else if ((lstAllLoansDeduction>0) && (lstAllSavingsDeduction>0))
{
decimal savingsAmount = 0;
decimal theAmountSaved = 0;
foreach (DictionaryEntry child in memberSavings)
{
savingsAmount = Convert.ToDecimal(child.Value);
if (savingsAmount >= lstAllSavingsDeduction)
{
theAmountSaved = lstAllSavingsDeduction;
}
else
{
lstAllSavingsDeduction = lstAllSavingsDeduction - savingsAmount;
theAmountSaved = savingsAmount;
}
#region cmd parameters
cmd.Parameters["@DeductionID"].Value = deductionID;
cmd.Parameters["@DeductionType"].Value = child.Key;
cmd.Parameters["@SavingsTypeID"].Value = memberSavingsType[child.Key];
cmd.Parameters["@Amount"].Value = theAmountSaved;
cmd.Parameters["@Remarks"].Value = string.Empty;
cmd.Parameters["@TransactionID"].Value = transactionID;
#endregion cmd parameters
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
if (savingsAmount >= lstAllSavingsDeduction) { break; }
// MessageBox.Show(child.Key.ToString() + " - " + child.Value.ToString() + "\nError Flag: " + errorflag);
}
}
//Check if the member is serving a loan. Get the type of loan and amount paying per month
string loanRepaymentType = null;
decimal loanRepaymentAmount = 0;
loanRepaymentAmount = lstAllLoansDeduction;
if (loanRepaymentAmount > 0) { loanRepaymentType = repaymentLoanType; } else { loanRepaymentType = "Loan Repayment - None"; }
cmd.CommandText = strQuery;
#region cmd parameters
cmd.Parameters["@DeductionType"].Value = loanRepaymentType;
cmd.Parameters["@SavingsTypeID"].Value = string.Empty;
cmd.Parameters["@Amount"].Value = loanRepaymentAmount;
#endregion
numOfRows = cmd.ExecuteNonQuery();
if (numOfRows == 0) { errorflag = 1; }
return "Loan Details Insertion " + numOfRows.ToString() + "\nError Flag: " + errorflag;
}
#endregion End of Record Deduction Details
//Record DeductionDates
public string recordDeductionDate(int selectedMonth, int selectedYear)
{
SqlConnection conn = ConnectDB.GetConnection();
string strQuery = "Insert into DeductionDates(Month,Year)values(@Month,@Year)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Month", SqlDbType.Int);
cmd.Parameters["@Month"].Value = selectedMonth;
cmd.Parameters.Add("@Year", SqlDbType.Int);
cmd.Parameters["@Year"].Value = selectedYear;
int rowAffected;
try
{
conn.Open();
rowAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
conn.Close();
}
if (rowAffected > 0)
{
return "1";
}
else
{
return "0";
}
}
}
}
|
3146028b61a78e31615d8a49905c856b0fea3fa5
|
[
"C#"
] | 62
|
C#
|
babarindeos/Coops
|
9ef243ebde0d61d849cffc0951783b09dd06bfdd
|
94d87670443996fbcbdbf1c2b11f98608fc055ce
|
refs/heads/master
|
<repo_name>Hardey18/nodeFirstApp<file_sep>/sayHello.js
const inLogger = require('./logger');
function sayHello(name) {
console.log(`Hello ${name}`);
}
sayHello('Adeola');
console.log(module);
inLogger('Adeola');
|
c181a7c137eafa4411017cdddcc3a5ae23dab296
|
[
"JavaScript"
] | 1
|
JavaScript
|
Hardey18/nodeFirstApp
|
3ef84dd635a47b38e48b5d26e3c16abe9fbd0eec
|
49cf11db0e2b9c93f94cc4d7b7841b78fcf14acd
|
refs/heads/master
|
<repo_name>FE-wuhao/dailyTestPro<file_sep>/src/pages/Context/Father/index.jsx
import React, { useState} from 'react';
import ChildComponent from '../Child/index';
export const ct = React.createContext(null);
function ContextTest(){
const [count, setCount] = useState(0);
return (
<ct.Provider value='111'>
<button
onClick={() => {
setCount(count + 1);
}}>
count++
</button>
<br />
<div>点击了{count}次</div>
<br />
<ChildComponent />
</ct.Provider>
);
}
export default ContextTest;
<file_sep>/src/pages/Context/Child/index.jsx
/*
* @Author: 吴灏
* @Date: 2020-08-10 10:01:57
* @LastEditors: 吴灏
* @LastEditTime: 2020-08-19 14:40:08
* @Description: file content
*/
import React, {
useContext
} from 'react';
import {
ct
} from '../Father/index';
function ChildComponent() {
const ctContext = useContext(ct);
return (
<>
<div> 父组件的传值是: {ctContext}
</div>
<div> 这里是子组件 </div> </ >
);
}
export default React.memo(ChildComponent);
|
eb5434064d7283d1b893610d681796d6f71b0e1a
|
[
"JavaScript"
] | 2
|
JavaScript
|
FE-wuhao/dailyTestPro
|
16115b35b44cacadce6458a517c398222c7bf7b9
|
c08cb04f39c357a885bec17a4e0f5f96ceb4c5d3
|
refs/heads/master
|
<repo_name>ADY1992/lazioforeverBet<file_sep>/src/main/java/com/lazioforeverBet/springmvc/dao/LoginDao.java
package com.lazioforeverBet.springmvc.dao;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.lazioforeverBet.springmvc.dto.Users;
@Repository("loginDao")
@Transactional
public class LoginDao {
@Resource(name="sessionFactory")
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession(){
return sessionFactory.openSession();
}
public boolean checkLogin(String userName, String userPassword){
Session session = sessionFactory.getCurrentSession();
boolean userFound = false;
String SQL_QUERY =" from Users u where u.userName = :username and u.userPassword = :<PASSWORD>";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("username" ,userName);
query.setParameter("userpassword" ,userPassword);
List<Users> list = query.list();
if ((list != null) && (list.size() > 0)) {
userFound= true;
}
return userFound;
}
}
<file_sep>/src/main/webapp/resources/js/common.js
function resetErrors(formId) {
$(".error").removeClass("error");
$("#" + formId).find("span").remove();
}
function parseDate(date) {
// Interpreta la data tenendo conto della timezone in essa impostata.
return moment.parseZone(date);
}
function formatDate(date, format) {
return date.format(format);
}
function populateSelect(id, map) {
var options = $("#" + id);
var emptyElem = options.attr("emptyElement");
if (typeof emptyElem != 'undefined' && emptyElem == 'true'){
options.append($("<option />"));
}
$.each( map, function( key, value ) {
options.append($("<option />").val(key).text(value));
});
}
function enableField(id){
$("#" + id).removeAttr("disabled");
$("#" + id).removeAttr("readonly");
}
<file_sep>/src/main/webapp/resources/js/defaultAutocomplete.js
$(document).ready(function() {
$("input.autocompleteField").each(function() {
var element = this;
$(this).autocomplete({
delay : 500,
source : function(request, response) {
var otherParams = $(element).attr("commaseparatedotherparamsvalues");
var otherIds = $(element).attr("commaseparatedotherparamsids");
var params = [];
if (typeof otherIds != 'undefined') {
var ids = otherIds.split(",");
for (var i = 0; i < ids.length; i++) {
params[i] = $("#" + ids[i]).val();
if (params[i] == "")
params[i] = null;
}
}
var autocompleteObj = {
value : request.term,
otherParams : (typeof otherParams != 'undefined' ? otherParams : null),
idsValueList : (typeof params != 'undefined' ? params : null)
};
var jsonParam = JSON.stringify(autocompleteObj);
$.ajax({
url : $(element).attr("url"),
cache : false,
dataType : "json",
contentType : 'application/json',
type : "POST",
data : jsonParam,
success : function(data, status, xhr) {
response(data);
},
error : function(xhr, text, error) {
var x = 1;
}
});
},
select : function(event, ui) {
$(element).val(ui.item.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>").append(item.value + " - " + item.description + "</li>").appendTo(ul);
};
});
});<file_sep>/src/main/webapp/resources/js/sidebar.js
$(document).ready(function() {
var menuVisible = true;
$('[data-toggle=offcanvas]').click(function() {
$(this).find('i').toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
if (menuVisible) {
$('#lg-menu').css('display', 'none');
$('#xs-menu').css('display', 'block');
menuVisible = false;
} else {
$('#lg-menu').css('display', 'block');
$('#xs-menu').css('display', 'none');
menuVisible = true;
}
$('#menu').toggleClass('col-xs-4 col-sm-3 col-md-2 col-lg-2').toggleClass('col-xs-0 col-sm-0 col-md-0 col-lg-0');
$('#page').toggleClass('col-xs-8 col-sm-9 col-md-10 col-lg-10').toggleClass('col-xs-12 col-sm-12 col-md-12 col-lg-12');
});
});
|
257978d3c05e683323042933b87c6654ac9e15e9
|
[
"JavaScript",
"Java"
] | 4
|
Java
|
ADY1992/lazioforeverBet
|
3894ed54c5a75e252c9f81ba6d427aaa2f2f3726
|
7006b6ccee9e4146a709951e2d1a5c3e2248fa55
|
refs/heads/main
|
<file_sep>from flask import Flask, request
import json
from pymongo import MongoClient
from bson.json_util import dumps
from bson.objectid import ObjectId
client = MongoClient('localhost:27017')
db = client.cart
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return "<h1>API Test</h1><p>This site is a prototype API for a shopping cart<br>Use Postman to send requests</p>"
@app.route('/add_item', methods=['POST'])
def add_item():
try:
data = json.loads(request.data)
item = data['item']
amount = data['amount']
if data and item:
status = db.cart.insert_one({
"item":item,
"amount":amount,
})
return dumps({'message':'SUCCESS'})
except Exception as e:
return dumps({'error': str(e)})
@app.route('/get_items', methods = ['GET'])
def get_items():
try:
cart_items = db.cart.find()
return dumps(cart_items)
except Exception as e:
return dumps({"error": str(e)})
@app.route('/cart_value', methods=['GET'])
def cart_value():
try:
cart_items = db.cart.find()
cart_list = list(cart_items)
amount = 0
for each in cart_list:
amount += each['amount']
return dumps({"Cart value": str(amount)})
except Exception as e:
return dumps({"error": str(e)})
@app.route('/delete_item/<id>', methods =['DELETE'])
def delete_item(id):
try:
db.cart.delete_one({'_id': ObjectId(id)})
return dumps({"Message":"Item deleted"})
except Exception as e:
return dumps({"error": str(e)})
app.run()<file_sep># Python-Flask-REST-API
A shopping cart REST API that handles CRUD operations
Requires Python, Flask, MongoDB
Run app.py and use Postman to perform requests
|
1e8780aae6e84c5ac2a59991a62f2fedf82d78b9
|
[
"Markdown",
"Python"
] | 2
|
Python
|
akashs7/Python-Flask-REST-API
|
d6e235434b31a9e20146b33750e2db0a6ba971b1
|
f53fd8239a884813e74724000d9e7732cb38b093
|
refs/heads/master
|
<file_sep>package com.example.owen.reciver;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class ActivityNotification extends ActionBarActivity{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String name = intent.getStringExtra("NAME");
TextView tv = new TextView(ActivityNotification.this);
tv.setText("Greeting"+name);
tv.setTextSize(25);
setContentView(tv);
}
}
|
50419586a37fa5cdcd837eb22bb92f39514303b1
|
[
"Java"
] | 1
|
Java
|
fcu-D0441484/Android-HW4-2
|
63d955324f9100fcaaf383c60067fe0249469e32
|
0e037233ddbe7cc75aaaefcfa034ed3bf95c2e66
|
refs/heads/master
|
<file_sep>export type EVENTS = 'CLIENT_HEARTBEAT' | 'POPULARITY' | 'COMMAND' | 'AUTH_AND_JOIN_ROOM' | 'SERVER_HEARTBEAT' | 'UNKNOW_EVENT'
export type COMMAND_TYPE = 'INTERACT_WORD' | 'DANMU_MSG' | 'SEND_GIFT'
export interface Command{
meta: null, // 元数据,目前还不知道咋分析,暂时先标为 null
data: any, // 内部数据,object
}
export interface CommandData{
cmd: COMMAND_TYPE,
data: {
uid: number,
uname: string,
timestamp: number,
}
}<file_sep>import fetch from "node-fetch"
import { ICloseEvent, IMessageEvent, w3cwebsocket as WebSocket } from "websocket";
import { EventEmitter } from "events"
import Zlib from "zlib"
import { Command, EVENTS } from "./index.d"
import {
NOT_LOGIN_UID, PROTOCOL_VERSION, PLATFORM,
CLIENT_VERSION, HEAD_OFFSET, HEAD_LENGTH,
OPERATION_CODE, HEARTBEATS_INTERVAL, HEAD_SIZE,
SEQUENCE, BODY_META_SIZE, TWO_BYTE } from "./consts";
export class BiliBiliDanmu extends EventEmitter{
private roomId:number = 0
private realRoomId: number = 0
private ws: WebSocket | null = null
constructor(roomId: number){
super()
if (!roomId) throw Error("请传入roomid!")
this.roomId = roomId
this.init()
}
emit(event: EVENTS, ...params: any[]): boolean{
return super.emit(event, ...params)
}
private async init(){
let res = await fetch(`https://api.live.bilibili.com/room/v1/Room/room_init?id=${this.roomId}`)
let json = await res.json()
this.realRoomId = json.data.room_id
this.ws = new WebSocket(`wss://broadcastlv.chat.bilibili.com:2245/sub`)
this.ws.onopen = this.wsOnOpen.bind(this)
this.ws.onmessage = this.wsOnMessage.bind(this)
this.ws.onclose = this.wsOnClose.bind(this)
this.ws.onerror = this.wsOnError.bind(this)
}
private async wsOnOpen(){
this.initAuth()
}
private async wsOnMessage(ev: IMessageEvent){
await this.decodeMessage(ev.data as ArrayBuffer)
}
private async wsOnClose(ev: ICloseEvent){
console.log("连接关闭:", ev)
}
private async wsOnError(ev: Error){
console.log("连接错误:", ev)
}
private async initAuth(){
let authConfig = {
uid: NOT_LOGIN_UID,
roomid: this.realRoomId,
protover: PROTOCOL_VERSION,
platform: PLATFORM,
clientver: CLIENT_VERSION,
}
let bufferHead = await this.initBufferHead()
let bufferBody = await this.initBufferBody(authConfig)
let packageSize = bufferHead.length + bufferBody.byteLength
await this.fillHeadBuffer(bufferHead, HEAD_OFFSET.ALL_DATA_SIZE, HEAD_LENGTH.ALL_DATA_SIZE, packageSize)
await this.fillHeadBuffer(bufferHead, HEAD_OFFSET.OPERATION_CODE, HEAD_LENGTH.OPERATION_CODE, OPERATION_CODE.AUTH_AND_JOIN_ROOM)
let buffer = new Uint8Array(packageSize)
buffer.set(bufferHead)
buffer.set(bufferBody, bufferHead.length)
// @ts-ignore
this.ws.send(buffer)
this.initHeartbeat()
setInterval(this.initHeartbeat.bind(this), HEARTBEATS_INTERVAL)
}
private async initHeartbeat(){
let bufferHead = await this.initBufferHead()
await this.fillHeadBuffer(bufferHead, HEAD_OFFSET.ALL_DATA_SIZE, HEAD_LENGTH.ALL_DATA_SIZE, HEAD_SIZE)
await this.fillHeadBuffer(bufferHead, HEAD_OFFSET.OPERATION_CODE, HEAD_LENGTH.OPERATION_CODE, OPERATION_CODE.CLIENT_HEARTBEAT)
// @ts-ignore
this.ws.send(bufferHead)
}
private async initBufferHead(): Promise<Uint8Array>{
let arrayBuffer = new ArrayBuffer(HEAD_SIZE)
let uIntBuffer = new Uint8Array(arrayBuffer)
await this.fillHeadBuffer(uIntBuffer, HEAD_OFFSET.HEAD_SIZE, HEAD_LENGTH.HEAD_SIZE, HEAD_SIZE)
await this.fillHeadBuffer(uIntBuffer, HEAD_OFFSET.PROTOCOL_VERSION, HEAD_LENGTH.PROTOCOL_VERSION, PROTOCOL_VERSION)
await this.fillHeadBuffer(uIntBuffer, HEAD_OFFSET.SEQUENCE, HEAD_LENGTH.SEQUENCE, SEQUENCE)
return uIntBuffer
}
private async initBufferBody(data: any): Promise<Uint8Array>{
let jsonString = JSON.stringify(data)
let buffer = Buffer.from(jsonString)
return new Uint8Array(buffer)
}
private async decodeMessage(data: ArrayBuffer): Promise<any>{
let uIntBuffer = new Uint8Array(data)
let opCode: OPERATION_CODE = await this.getHeadBuffer(uIntBuffer, HEAD_OFFSET.OPERATION_CODE, HEAD_LENGTH.OPERATION_CODE)
uIntBuffer = uIntBuffer.slice(HEAD_SIZE)
switch(opCode){
case OPERATION_CODE.POPULARITY:
let popularity = await this.getPopularity(uIntBuffer)
this.emit('POPULARITY', popularity)
break
case OPERATION_CODE.COMMAND:
let command = await this.decodeBodyData(uIntBuffer)
this.emit('COMMAND', command)
break
case OPERATION_CODE.SERVER_HEARTBEAT:
this.emit('SERVER_HEARTBEAT')
break
default:
this.emit('UNKNOW_EVENT', uIntBuffer)
break
}
}
private async decodeBodyData(buffer: Uint8Array): Promise<Command> {
let uIntBuffer = new Uint8Array(buffer)
let data: Command = {
meta: null,
data: {},
}
uIntBuffer = Zlib.inflateSync(uIntBuffer)
// todo 解析body元数据,目前直接设置为 null
data.meta = null
uIntBuffer = uIntBuffer.slice(BODY_META_SIZE)
let string = Buffer.from(uIntBuffer).toString("utf-8")
let json = JSON.parse(string)
data.data = json
return data
}
private async getPopularity(buffer: Uint8Array): Promise<number>{
let popularity = 0
for (let i = 0; i < buffer.length; i++) {
popularity *= TWO_BYTE
popularity += buffer[i]
}
return popularity
}
private async getHeadBuffer(buffer: Uint8Array, offset: HEAD_OFFSET, length: HEAD_LENGTH): Promise<number> {
let number = 0
let i = 0
while(i < length){
number *= TWO_BYTE
number += buffer[offset + i]
i++
}
return number
}
private async fillHeadBuffer(buffer: Uint8Array, offset: HEAD_OFFSET, length: HEAD_LENGTH, data: number) {
while (length > 0) {
length --
buffer[offset + length] = data % TWO_BYTE
data = Math.floor(data / TWO_BYTE)
}
if (data !== 0) throw Error("数据溢出!")
}
}
<file_sep>export const enum HEAD_OFFSET {
ALL_DATA_SIZE = 0,
HEAD_SIZE = 4,
PROTOCOL_VERSION = 6,
OPERATION_CODE = 8,
SEQUENCE = 12,
}
export const enum HEAD_LENGTH {
ALL_DATA_SIZE = 4,
HEAD_SIZE = 2,
PROTOCOL_VERSION = 2,
OPERATION_CODE = 4,
SEQUENCE = 4,
}
export const enum BODY_META_OFFSET {
// todo:body 数据格式分析,
}
export const enum OPERATION_CODE {
CLIENT_HEARTBEAT = 2,
POPULARITY = 3,
COMMAND = 5,
AUTH_AND_JOIN_ROOM = 7,
SERVER_HEARTBEAT = 8,
}
export const LEFT_CURLY_BRACKET_CHAR_CODE = 123 // 左花括号编码
export const SEQUENCE = 1
export const PROTOCOL_VERSION = 2
export const PLATFORM = "web"
export const CLIENT_VERSION = "2.4.16"
export const HEAD_SIZE = 16
// 就 NM 离谱,版本为 2 的 body 中也带有一个长度为 16 字节的头部。
export const BODY_META_SIZE = 16
export const NOT_LOGIN_UID = 0
export const HEARTBEATS_INTERVAL = 30 * 1000
export const TWO_BYTE = 256<file_sep>"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BiliBiliDanmu = void 0;
var node_fetch_1 = __importDefault(require("node-fetch"));
var websocket_1 = require("websocket");
var events_1 = require("events");
var zlib_1 = __importDefault(require("zlib"));
var consts_1 = require("./consts");
var BiliBiliDanmu = /** @class */ (function (_super) {
__extends(BiliBiliDanmu, _super);
function BiliBiliDanmu(roomId) {
var _this = _super.call(this) || this;
_this.roomId = 0;
_this.realRoomId = 0;
_this.ws = null;
if (!roomId)
throw Error("请传入roomid!");
_this.roomId = roomId;
_this.init();
return _this;
}
BiliBiliDanmu.prototype.emit = function (event) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
return _super.prototype.emit.apply(this, __spreadArrays([event], params));
};
BiliBiliDanmu.prototype.init = function () {
return __awaiter(this, void 0, void 0, function () {
var res, json;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, node_fetch_1.default("https://api.live.bilibili.com/room/v1/Room/room_init?id=" + this.roomId)];
case 1:
res = _a.sent();
return [4 /*yield*/, res.json()];
case 2:
json = _a.sent();
this.realRoomId = json.data.room_id;
this.ws = new websocket_1.w3cwebsocket("wss://broadcastlv.chat.bilibili.com:2245/sub");
this.ws.onopen = this.wsOnOpen.bind(this);
this.ws.onmessage = this.wsOnMessage.bind(this);
this.ws.onclose = this.wsOnClose.bind(this);
this.ws.onerror = this.wsOnError.bind(this);
return [2 /*return*/];
}
});
});
};
BiliBiliDanmu.prototype.wsOnOpen = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.initAuth();
return [2 /*return*/];
});
});
};
BiliBiliDanmu.prototype.wsOnMessage = function (ev) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.decodeMessage(ev.data)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
BiliBiliDanmu.prototype.wsOnClose = function (ev) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
console.log("连接关闭:", ev);
return [2 /*return*/];
});
});
};
BiliBiliDanmu.prototype.wsOnError = function (ev) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
console.log("连接错误:", ev);
return [2 /*return*/];
});
});
};
BiliBiliDanmu.prototype.initAuth = function () {
return __awaiter(this, void 0, void 0, function () {
var authConfig, bufferHead, bufferBody, packageSize, buffer;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
authConfig = {
uid: consts_1.NOT_LOGIN_UID,
roomid: this.realRoomId,
protover: consts_1.PROTOCOL_VERSION,
platform: consts_1.PLATFORM,
clientver: consts_1.CLIENT_VERSION,
};
return [4 /*yield*/, this.initBufferHead()];
case 1:
bufferHead = _a.sent();
return [4 /*yield*/, this.initBufferBody(authConfig)];
case 2:
bufferBody = _a.sent();
packageSize = bufferHead.length + bufferBody.byteLength;
return [4 /*yield*/, this.fillHeadBuffer(bufferHead, 0 /* ALL_DATA_SIZE */, 4 /* ALL_DATA_SIZE */, packageSize)];
case 3:
_a.sent();
return [4 /*yield*/, this.fillHeadBuffer(bufferHead, 8 /* OPERATION_CODE */, 4 /* OPERATION_CODE */, 7 /* AUTH_AND_JOIN_ROOM */)];
case 4:
_a.sent();
buffer = new Uint8Array(packageSize);
buffer.set(bufferHead);
buffer.set(bufferBody, bufferHead.length);
// @ts-ignore
this.ws.send(buffer);
this.initHeartbeat();
setInterval(this.initHeartbeat.bind(this), consts_1.HEARTBEATS_INTERVAL);
return [2 /*return*/];
}
});
});
};
BiliBiliDanmu.prototype.initHeartbeat = function () {
return __awaiter(this, void 0, void 0, function () {
var bufferHead;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initBufferHead()];
case 1:
bufferHead = _a.sent();
return [4 /*yield*/, this.fillHeadBuffer(bufferHead, 0 /* ALL_DATA_SIZE */, 4 /* ALL_DATA_SIZE */, consts_1.HEAD_SIZE)];
case 2:
_a.sent();
return [4 /*yield*/, this.fillHeadBuffer(bufferHead, 8 /* OPERATION_CODE */, 4 /* OPERATION_CODE */, 2 /* CLIENT_HEARTBEAT */)
// @ts-ignore
];
case 3:
_a.sent();
// @ts-ignore
this.ws.send(bufferHead);
return [2 /*return*/];
}
});
});
};
BiliBiliDanmu.prototype.initBufferHead = function () {
return __awaiter(this, void 0, void 0, function () {
var arrayBuffer, uIntBuffer;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
arrayBuffer = new ArrayBuffer(consts_1.HEAD_SIZE);
uIntBuffer = new Uint8Array(arrayBuffer);
return [4 /*yield*/, this.fillHeadBuffer(uIntBuffer, 4 /* HEAD_SIZE */, 2 /* HEAD_SIZE */, consts_1.HEAD_SIZE)];
case 1:
_a.sent();
return [4 /*yield*/, this.fillHeadBuffer(uIntBuffer, 6 /* PROTOCOL_VERSION */, 2 /* PROTOCOL_VERSION */, consts_1.PROTOCOL_VERSION)];
case 2:
_a.sent();
return [4 /*yield*/, this.fillHeadBuffer(uIntBuffer, 12 /* SEQUENCE */, 4 /* SEQUENCE */, consts_1.SEQUENCE)];
case 3:
_a.sent();
return [2 /*return*/, uIntBuffer];
}
});
});
};
BiliBiliDanmu.prototype.initBufferBody = function (data) {
return __awaiter(this, void 0, void 0, function () {
var jsonString, buffer;
return __generator(this, function (_a) {
jsonString = JSON.stringify(data);
buffer = Buffer.from(jsonString);
return [2 /*return*/, new Uint8Array(buffer)];
});
});
};
BiliBiliDanmu.prototype.decodeMessage = function (data) {
return __awaiter(this, void 0, void 0, function () {
var uIntBuffer, opCode, _a, popularity, command;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
uIntBuffer = new Uint8Array(data);
return [4 /*yield*/, this.getHeadBuffer(uIntBuffer, 8 /* OPERATION_CODE */, 4 /* OPERATION_CODE */)];
case 1:
opCode = _b.sent();
uIntBuffer = uIntBuffer.slice(consts_1.HEAD_SIZE);
_a = opCode;
switch (_a) {
case 3 /* POPULARITY */: return [3 /*break*/, 2];
case 5 /* COMMAND */: return [3 /*break*/, 4];
case 8 /* SERVER_HEARTBEAT */: return [3 /*break*/, 6];
}
return [3 /*break*/, 7];
case 2: return [4 /*yield*/, this.getPopularity(uIntBuffer)];
case 3:
popularity = _b.sent();
this.emit('POPULARITY', popularity);
return [3 /*break*/, 8];
case 4: return [4 /*yield*/, this.decodeBodyData(uIntBuffer)];
case 5:
command = _b.sent();
this.emit('COMMAND', command);
return [3 /*break*/, 8];
case 6:
this.emit('SERVER_HEARTBEAT');
return [3 /*break*/, 8];
case 7:
this.emit('UNKNOW_EVENT', uIntBuffer);
return [3 /*break*/, 8];
case 8: return [2 /*return*/];
}
});
});
};
BiliBiliDanmu.prototype.decodeBodyData = function (buffer) {
return __awaiter(this, void 0, void 0, function () {
var uIntBuffer, data, string, json;
return __generator(this, function (_a) {
uIntBuffer = new Uint8Array(buffer);
data = {
meta: null,
data: {},
};
uIntBuffer = zlib_1.default.inflateSync(uIntBuffer);
// todo 解析body元数据,目前直接设置为 null
data.meta = null;
uIntBuffer = uIntBuffer.slice(consts_1.BODY_META_SIZE);
string = Buffer.from(uIntBuffer).toString("utf-8");
json = JSON.parse(string);
data.data = json;
return [2 /*return*/, data];
});
});
};
BiliBiliDanmu.prototype.getPopularity = function (buffer) {
return __awaiter(this, void 0, void 0, function () {
var popularity, i;
return __generator(this, function (_a) {
popularity = 0;
for (i = 0; i < buffer.length; i++) {
popularity *= consts_1.TWO_BYTE;
popularity += buffer[i];
}
return [2 /*return*/, popularity];
});
});
};
BiliBiliDanmu.prototype.getHeadBuffer = function (buffer, offset, length) {
return __awaiter(this, void 0, void 0, function () {
var number, i;
return __generator(this, function (_a) {
number = 0;
i = 0;
while (i < length) {
number *= consts_1.TWO_BYTE;
number += buffer[offset + i];
i++;
}
return [2 /*return*/, number];
});
});
};
BiliBiliDanmu.prototype.fillHeadBuffer = function (buffer, offset, length, data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
while (length > 0) {
length--;
buffer[offset + length] = data % consts_1.TWO_BYTE;
data = Math.floor(data / consts_1.TWO_BYTE);
}
if (data !== 0)
throw Error("数据溢出!");
return [2 /*return*/];
});
});
};
return BiliBiliDanmu;
}(events_1.EventEmitter));
exports.BiliBiliDanmu = BiliBiliDanmu;
<file_sep>import { EventEmitter } from "events"
import { EVENTS } from "./src"
declare class BilibiliLiveDanmu extends EventEmitter{
/** @param {number} roomId 房间号,包括正常房间号和短号码 */
private roomId: number
/** @param {number} realRoomId 真实房间号,短号码所对应的真实房间 */
private realRoomId: number
/** @param {WebSocket} ws websocket 实例 */
private ws: WebSocket
/**
* @function constructor websocket 实例
* @param {number} roomId 房间号,包括正常房间号和短号码 */
constructor(roomId: number)
/**
* @function init 初始化方法
*/
private async init(): Promise<void>{}
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {...any} params 其他参数
*/
emit(event: EVENTS, ...params: any[]): boolean
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
on(events: EVENTS, callback:Function)
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
addListener(events: EVENTS, callback:Function)
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
removeListener(events: EVENTS, callback:Function)
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
removeAllListeners(events: EVENTS, callback:Function)
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
once(events: EVENTS, callback:Function)
/**
* @function on 监听器函数
* @param {EVENTS} events 触发事件
* @param {Function} callback 回调事件
*/
off(events: EVENTS, callback:Function)
}<file_sep>## 使用方法:
```typescript
// commonjs 引入方法:
let BilibiliLiveDanmu = require("@flowfire/bilibili-live-danmu").BilibiliLiveDanmu
// es6 模块引入方法
import { BilibiliLiveDanmu } from "@flowfire/bilibili-live-danmu"
let danmu = new BilibiliLiveDanmu(17253) // 数字为直播间号码
danmu.on("POPULARITY", number => console.log("房间人气值为:", number))
danmu.on("COMMAND", cmd => console.log("命令弹幕,用户进入直播间,发送弹幕,礼物通知等都会出发该事件", cmd))
danmu.on("SERVER_HEARTBEAT", () => console.log("服务器心跳包,该事件没有数据"))
```
有 bug 请去 github 提交 issue。
|
2c925d57f42dff20ee900f652f6bc1b7b1bc7707
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 6
|
TypeScript
|
flowfire/bilibili-live-danmu
|
e5a3b89ad0569046c0682eb9fd177b7797506787
|
d8f067b70a9cc1b856d1bbe9d1e5b34a3084fdca
|
refs/heads/master
|
<repo_name>nmorkar/mywc<file_sep>/src/main/resources/db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.11.113.130:3306/wildfly8
jdbc.username=admin44lby3v
jdbc.password=<PASSWORD>
mail.smtp.host=localhost
mail.smtp.port=25
<file_sep>/src/main/java/com/cric/model/CricModel.java
package com.cric.model;
import java.util.Collection;
public class CricModel {
private String match;
private int playerCount;
private Collection<Player> players;
private String message;
private String nextUser;
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public int getPlayerCount() {
return playerCount;
}
public void setPlayerCount(int playerCount) {
this.playerCount = playerCount;
}
public Collection<Player> getPlayers() {
return players;
}
public void setPlayers(Collection<Player> players) {
this.players = players;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNextUser() {
return nextUser;
}
public void setNextUser(String next) {
this.nextUser = next;
}
}
<file_sep>/src/main/java/com/cric/util/CricUtil.java
package com.cric.util;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.cric.model.CricModel;
import com.cric.model.User;
public final class CricUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String getModelJSON() {
try {
return mapper.writeValueAsString(getModel());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String toJson(CricModel model){
try {
return mapper.writeValueAsString(model);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static CricModel getModel() {
CricModel model = new CricModel();
model.setMatch(CricMatchCache.getMatchId());
model.setPlayers(CricMatchCache.getPlayers());
model.setPlayerCount(CricMatchCache.getPlayerCount());
return model;
}
public static CricModel selectPlayer(String username) {
CricModel model = new CricModel();
User u = User.valueOf(username.toUpperCase());
CricMatchCache.addSelectionOrder(u); //add user for selection order
model.setPlayers(CricMatchCache.selectRandom(u));
model.setMatch(CricMatchCache.getMatchId());
model.setPlayerCount(CricMatchCache.getPlayerCount());
// model.setUsername(u.getName());
model.setNextUser(CricMatchCache.nextSelectionOrder(u)); //set next user to select
return model;
}
public static String nextUser(String username){
User u = User.valueOf(username.toUpperCase());
return CricMatchCache.nextSelectionOrder(u);
}
public static CricModel rest() {
CricMatchCache.reset();
CricModel model = new CricModel();
model.setPlayers(CricMatchCache.getPlayers());
return new CricModel();
}
public static CricModel startNew(String matchId) {
CricMatchCache.startNew(matchId);
CricModel model = new CricModel();
model.setMatch(matchId);
model.setPlayers(CricMatchCache.getPlayers());
model.setPlayerCount(CricMatchCache.getPlayerCount());
return model;
}
public static String convertToJSON(CricModel model) {
try {
return mapper.writeValueAsString(model);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
<file_sep>/src/main/java/com/cric/dao/UserSelectionDao.java
package com.cric.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import com.cric.domain.UserSelection;
@Component
public class UserSelectionDao extends HibernateDaoSupport {
/*@Autowired
SessionFactory sessionFactory;*/
@Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public void saveUpdate(List<UserSelection> c){
getHibernateTemplate().saveOrUpdateAll(c);
//getHibernateTemplate().flush();
}
public void save(UserSelection user){
getHibernateTemplate().save(user);
}
public void update(UserSelection user){
getHibernateTemplate().update(user);
}
public void delete(UserSelection user){
getHibernateTemplate().delete(user);
}
public void delete(List<UserSelection> user){
getHibernateTemplate().deleteAll(user);
}
public void delete(String deleteMatch){
getHibernateTemplate().deleteAll(getHibernateTemplate().find(" from UserSelection u where u.matchName = ? ", new Object[]{deleteMatch}) );
}
public void archive(String match){
List<UserSelection> u = find(match);
for (UserSelection userSelection : u) {
userSelection.setStatus(0l);
}
getHibernateTemplate().saveOrUpdateAll(u);
}
public void archive(UserSelection user){
user.setStatus(0l);
getHibernateTemplate().update(user);
}
public UserSelection get(Long selectionId){
return (UserSelection) getHibernateTemplate().get(UserSelection.class, selectionId);
}
public UserSelection load(Long selectionId){
return (UserSelection) getHibernateTemplate().load(UserSelection.class, selectionId);
}
@SuppressWarnings("unchecked")
public List<UserSelection> findAll(){
return getHibernateTemplate().find(" from UserSelection u where status = 1");
}
@SuppressWarnings("unchecked")
public List<UserSelection> find(Long userId){
return getHibernateTemplate().find(" from UserSelection u where u.userId = ? and status = 1 ", new Object[]{userId});
}
@SuppressWarnings("unchecked")
public List<UserSelection> find(Long userId, String matchname){
return getHibernateTemplate().find(" from UserSelection u where u.userId = ? and u.matchName = ? and status = 1 ", new Object[]{userId,matchname});
}
@SuppressWarnings("unchecked")
public List<UserSelection> find(String matchname){
return getHibernateTemplate().find(" from UserSelection u where u.matchName = ? and status = 1", new Object[]{matchname});
}
}
|
6f2faf98351f3f4012dedbd59375baa2b3f5f621
|
[
"Java",
"INI"
] | 4
|
INI
|
nmorkar/mywc
|
019cb72719a1626072804119d7b0e616e844b95b
|
6d889faf4be5bde16cd5d9d43e14718c026bc5ae
|
refs/heads/master
|
<file_sep>package de.mi.ur;
/**
* Created by Anna-Marie on 01.08.2016.
*/
public class Constants {
//communication between PracticeMain and PractiseActivities
public static final String KEY_TYPE_QUESTION = "type of practise question";
public static final int MULTIPLE_CHOICE = 0;
public static final int TRUE_FALSE = 1;
public static final int FREETEXT = 2;
public static final String KEY_NUMERAL_1_BASE = "numeral1 base";
public static final String KEY_NUMERAL_2_BASE = "numeral2 base";
public static final String KEY_QUESTION_LENGTH = "question length";
// Abfrage in ExplanationActivity, welches Tutorial angezeigt werden soll
public static final String KEY_TYPE_TUTORIAL = "type of tutorial";
public static final int INTRO_TUTORIAL = 0;
public static final int DECIMAL_TUTORIAL = 1;
public static final int OTHER_TUTORIAL = 2;
public static final int TRICKS_TUTORIAL = 3;
public static final String KEY_NUMBER_TUTORIAL = "number of explanation";
public static final int NUMBER_1 = 0;
//Anzahl der Screens pro Tutorial -> Zählanfang im Array bei 0, d.h. das ist der letzte zugreifbare Punkt im jeweiligen String-Array
public static final int MAX_EXPLANATION_NUM_INTRO = 5;
public static final int MAX_EXPLANATION_NUM_DECIMAL = 3;
public static final int MAX_EXPLANATION_NUM_OTHER = 5;
public static final int MAX_EXPLANATION_NUM_TRICKS = 5;
public static final int WEATHER_SUNNY = 0;
public static final int WEATHER_CLOUDY = 1;
public static final int WEATHER_RAINY = 2;
public static final int WEATHER_SNOWY = 3;
public static final int WEATHER_DEFAULT = 0;
//Extra für AndroidLauncher
public static final String CURRENT_WEATHER = "current weather";
public static final String BACKGROUND_MUSIC = "background music";
public static final String SOUND_EFFECTS = "sound effects";
//Permission
public static final int MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 111;
//Practice
public static final int NUM_QUESTIONS_PER_PRACTICE = 10;
public static final int PROGRESS_FULL = 100;
public static final int DELAY_HALF_SECOND = 500;
public static final int BACK_KEY_PRESSED = -1;
//Questions
public static final int NUM_WRONG_ANSWERS_MULTIPLE_CHOICE = 3;
public static final int MAX_NUMERAL_BASE = 16;
public static final int MIN_NUMERAL_BASE = 2;
public static final int DEFAULT_NUMERAL_BASE = 10;
//MultipleChoiceDialog
public static final int MULTIPLE_CHOICE_DIALOG_FIRST_NUMERAL_BASE = 2;
public static final int MULTIPLE_CHOICE_DIALOG_SECOND_NUMERAL_BASE = 10;
public static final int MULTIPLE_CHOICE_DIALOG_QUESTION_LENGTH = 6;
public static final int DIALOG_SHOW_TIME_IN_SECONDS = 5;
//WeatherExtras
public static final String API_ID = "50ddb65d4b6d51050e5844a4284d6d46";
public static final String DEFAULT_LATITUDE = "49";
public static final String DEFAULT_LONGITUDE = "12";
public static final String WEATHER_API_URL_1_LAT = "http://api.openweathermap.org/data/2.5/weather?lat=";
public static final String WEATHER_API_URL_2_LON = "&lon=";
public static final String WEATHER_API_URL_3 = "&appid=" + API_ID;
//Database
public static final int HIHGEST_LEVEL = 9;
public static final int CURRENT_LEVEL_ID = 20;
public static final String[] levelNames = {"Unwissender",
"Initiant",
"Padawan",
"Nullen-Nerd",
"<NAME>",
"Quaternal-Kenner",
"Oktal-Jongleur",
"Hex-Beherrscher",
"Meister der Systeme",
"5up3r N3rd"
};
public static final int LEVEL_NUM_0 = 0;
public static final int LEVEL_NUM_1 = 1;
public static final int LEVEL_NUM_2 = 2;
public static final int LEVEL_NUM_3 = 3;
public static final int LEVEL_NUM_4 = 4;
public static final int LEVEL_NUM_5 = 5;
public static final int LEVEL_NUM_6 = 6;
public static final int LEVEL_NUM_7 = 7;
public static final int LEVEL_NUM_8 = 8;
public static final int LEVEL_NUM_9 = 9;
public static final int NUM_POINTS_LVL_0 = 0;
public static final int NUM_POINTS_LVL_1 = 100;
public static final int NUM_POINTS_LVL_2 = 300;
public static final int NUM_POINTS_LVL_3 = 600;
public static final int NUM_POINTS_LVL_4 = 1000;
public static final int NUM_POINTS_LVL_5 = 1500;
public static final int NUM_POINTS_LVL_6 = 2100;
public static final int NUM_POINTS_LVL_7 = 2800;
public static final int NUM_POINTS_LVL_8 = 3600;
public static final int NUM_POINTS_LVL_9 = 4500;
public static final int QUESTION_DIFFICULTY_EASY = 0;
public static final int QUESTION_DIFFICULTY_MEDIUM = 1;
public static final int QUESTION_DIFFICULTY_HARD = 2;
public static final int QUESTION_DIFFICULTY_REALLY_HARD = 3;
//Font
public static final String FONT = "cantarell_font.ttf";
}
<file_sep>package de.mi.ur.LevelLogic;
/**
* Created by Anna-Marie on 07.09.2016.
*
* This class represent a Level the User can reach in Practicemode
*
* remark concerning pointsNeededForThisLevel: This is the amount of points the user needs to have to be in this level;
* in case of the currentLevel of the user, the points he/she currently has, are stored in this variable
*/
public class Level {
private int id;
private int levelNum;
private String levelName;
private int pointsNeededForThisLevel;
private int questionLength;
public Level(int id, int levelNum, String levelName, int pointsNeededForThisLevel, int questionLength){
this.id = id;
this.levelNum = levelNum;
this.levelName = levelName;
this.pointsNeededForThisLevel = pointsNeededForThisLevel;
this.questionLength = questionLength;
}
public int getId(){
return id;
}
public int getLevelNum() {
return levelNum;
}
public String getLevelName() {
return levelName;
}
public int getPointsNeededForThisLevel() {
return pointsNeededForThisLevel;
}
public int getQuestionLength() {
return questionLength;
}
}
<file_sep>package de.mi.ur.Activities;
import android.app.FragmentManager;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import de.mi.ur.SettingsFragment;
/**
* Created by Anna-Marie on 10.08.2016.
*/
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
<file_sep>package de.mi.ur.LevelLogic;
import de.mi.ur.Constants;
/**
* Created by Anna-Marie on 07.09.2016.
*
* This class is responsible for calculating how many points the user gets per correct answer in practice mode
* and how long the question-numbers are
*/
public class DifficultyCalculator {
/*
* The larger of the two chosen numeral bases and the question type are responsible for the number of points the
* user receives per correctly answered question
*
* If the question and answer system are the system, the user does not get points.
*
* The well-known systems from which you are able to transform by simple alignment (e.g. 2 -> 10 etc.)
* give the least points (2)
* 9<->3 is less known and 4 <-> 16 is a bit harder, you need two alignments in your head, so you get three points
* transformations to and from 10 are easier, because you know the system well -> 4 points
* If the bigger numeral system base is lower than 10 -> 5 points
* If it is higher than 10 -> 6 points
*
* FreeTextQuestions give 2 points more than the other two questiontypes
*/
public static int getPointsPerQuestion(int questionType, int numeral1Base, int numeral2Base){
int pointsPerQuestion = 0;
int biggerNumeralBase = getMaxNumeralBase(numeral1Base, numeral2Base);
if(numeral1Base == numeral2Base){
return pointsPerQuestion;
}else{
if(
(numeral1Base == 2 &&( numeral2Base == 4 || numeral2Base ==8 || numeral2Base == 16 )) ||
(numeral2Base == 2 &&( numeral1Base == 4 || numeral1Base ==8 || numeral1Base == 16 )) ||
(numeral1Base == 4 && numeral2Base ==16) || (numeral1Base == 16 && numeral2Base == 4)
){
pointsPerQuestion = 2;
}else if ((numeral1Base == 8 && (numeral2Base == 4 || numeral2Base == 16)) ||
(numeral2Base == 8 && (numeral1Base == 4 || numeral1Base == 16)) ||
(numeral1Base == 3 && numeral2Base ==9) || (numeral1Base ==9 && numeral2Base == 3 )
){
pointsPerQuestion = 3;
}else if(numeral1Base == 10 || numeral2Base == 10){
pointsPerQuestion = 4;
}else if (biggerNumeralBase <= 9){
pointsPerQuestion = 5;
}else if (biggerNumeralBase > 10){
pointsPerQuestion = 6;
}
if(questionType == Constants.FREETEXT){
pointsPerQuestion += 2;
}
}
return pointsPerQuestion;
}
/*
* returns the maximum of two given numeralBases
*/
private static int getMaxNumeralBase(int numeral1Base, int numeral2Base){
if(numeral1Base > numeral2Base){
return numeral1Base;
}else{
return numeral2Base;
}
}
/*
* Determs the basic question length in practicemode (depending on the concerned numeralsystems)
* Later, length is added depending on the current level of the user
*/
public static int getBaseQuestionLength(int numeral1Base, int numeral2Base){
if(numeral1Base > numeral2Base){
if(numeral1Base <= 4){
return 4;
}else if (numeral2Base <= 8) {
return 3;
} else if (numeral2Base <= 10){
return 2;
} else if (numeral1Base > 10){
return 1;
} else{
return 1;
}
}else{
if(numeral1Base ==2 ){
return 4;
}else if (numeral1Base <= 4){
return 3;
}else if (numeral1Base <= 8){
return 2;
}else if (numeral1Base >8){
return 1;
}else{
return 1;
}
}
}
}
<file_sep>package de.mi.ur.gameLogic;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import java.util.ArrayList;
import java.util.Random;
import de.mi.ur.AndroidCommunication.MultipleChoiceListener;
import de.mi.ur.ConstantsGame;
import de.mi.ur.sprites.AnswerPhone;
import de.mi.ur.states.PlayState;
public class GameQuestion {
private String toSolve;
private static String possAnswer1;
private static String possAnswer2;
private static String possAnswer3;
private static String possAnswer4;
public static boolean answerGenerated = false;
private static String[] question;
private static ArrayList<String> possAnswers;
private BitmapFont toSolveBitmap;
private BitmapFont number1;
private BitmapFont number2;
private BitmapFont number3;
private BitmapFont number4;
private BitmapFont possAnswer1Bitmap;
private BitmapFont possAnswer2Bitmap;
private BitmapFont possAnswer3Bitmap;
private BitmapFont possAnswer4Bitmap;
private MultipleChoiceListener multipleChoiceGenerator;
private int numeral1Base;
private int numeral2Base = 10;
private int maxDigits;
private boolean counted;
private Random random;
private boolean isBinary;
public GameQuestion(MultipleChoiceListener multipleChoiceGenerator) {
random = new Random();
counted = false;
this.multipleChoiceGenerator = multipleChoiceGenerator;
toSolve = "";
possAnswer1 = "";
possAnswer2 = "";
possAnswer3 = "";
possAnswer4 = "";
toSolveBitmap = new BitmapFont();
toSolveBitmap.setUseIntegerPositions(false);
number1 = new BitmapFont();
number1.setUseIntegerPositions(false);
number2 = new BitmapFont();
number2.setUseIntegerPositions(false);
number3 = new BitmapFont();
number3.setUseIntegerPositions(false);
number4 = new BitmapFont();
number4.setUseIntegerPositions(false);
possAnswer1Bitmap = new BitmapFont();
possAnswer1Bitmap.setUseIntegerPositions(false);
possAnswer2Bitmap = new BitmapFont();
possAnswer2Bitmap.setUseIntegerPositions(false);
possAnswer3Bitmap = new BitmapFont();
possAnswer3Bitmap.setUseIntegerPositions(false);
possAnswer4Bitmap = new BitmapFont();
possAnswer4Bitmap.setUseIntegerPositions(false);
}
public ArrayList<String> generatePossAnswers() {
ArrayList<String> possAnswers = new ArrayList<String>();
for (int i = ConstantsGame.POSS_ANSWER1_POS; i <= ConstantsGame.POSS_ANSWER4_POS; i++) {
possAnswers.add(question[i]);
}
return possAnswers;
}
public static int getRightAnswer() {
String rightAnswer = question[ConstantsGame.RIGHT_ANSWER_POS];
if (rightAnswer.equals(possAnswer1)) {
return possAnswers.indexOf(possAnswer1) + 1;
}
if (rightAnswer.equals(possAnswer2)) {
return possAnswers.indexOf(possAnswer2) + 1;
}
if (rightAnswer.equals(possAnswer3)) {
return possAnswers.indexOf(possAnswer3) + 1;
}
if (rightAnswer.equals(possAnswer4)) {
return possAnswers.indexOf(possAnswer4) + 1;
}
return 0;
}
/**
* this method chooses randomly, whether the next question is in the binary- or the hex-system.
*/
private void binaryOrHex() {
isBinary = random.nextBoolean();
//binär oder Hex-Abfrage
if (isBinary) {
numeral1Base = 2;
maxDigits = 6;
} else {
numeral1Base = 16;
maxDigits = 2;
}
}
/**
* This method updates the questions. It generates randomly a new question and 4 possible answers
*/
public void updateQuestions() {
binaryOrHex();
if (PlayState.isQuestionPhase() && !isCounted()) {
question = multipleChoiceGenerator.getQuestionInfos(numeral1Base, numeral2Base, maxDigits, 0);
if (isBinary) {
toSolve = question[ConstantsGame.QUESTION_POS] + " (2)";
} else {
toSolve = question[ConstantsGame.QUESTION_POS] + " (16)";
}
possAnswers = generatePossAnswers();
possAnswer1 = possAnswers.get(0);
possAnswer2 = possAnswers.get(1);
possAnswer3 = possAnswers.get(2);
possAnswer4 = possAnswers.get(3);
answerGenerated = true;
AnswerPhone.resetCounted();
setCounted();
}
}
public void drawTasks(SpriteBatch batch, OrthographicCamera cam) {
toSolveBitmap.draw(batch, toSolve, cam.position.x + ConstantsGame.QUESTION_TOSOLVE_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
toSolveBitmap.setColor(Color.RED);
number1.draw(batch, "1:", cam.position.x + ConstantsGame.QUESTION_POSSANS_1_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
number1.setColor(Color.RED);
possAnswer1Bitmap.draw(batch, " " + possAnswer1, cam.position.x + ConstantsGame.QUESTION_POSSANS_1_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
possAnswer1Bitmap.setColor(Color.BLACK);
number2.draw(batch, "2:", cam.position.x, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
number2.setColor(Color.RED);
possAnswer2Bitmap.draw(batch, " " + possAnswer2, cam.position.x, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
possAnswer2Bitmap.setColor(Color.BLACK);
number3.draw(batch, "3:", cam.position.x + ConstantsGame.QUESTION_POSSANS_3_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
number3.setColor(Color.RED);
possAnswer3Bitmap.draw(batch, " " + possAnswer3, cam.position.x + ConstantsGame.QUESTION_POSSANS_3_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
possAnswer3Bitmap.setColor(Color.BLACK);
number4.draw(batch, "4:", cam.position.x + ConstantsGame.QUESTION_POSSANS_4_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
number4.setColor(Color.RED);
possAnswer4Bitmap.setColor(Color.BLACK);
possAnswer4Bitmap.draw(batch, " " + possAnswer4, cam.position.x + ConstantsGame.QUESTION_POSSANS_4_OFFSET, cam.position.y + ConstantsGame.QUESTION_OFFSET_Y);
}
public void dipose() {
number1.dispose();
possAnswer1Bitmap.dispose();
number2.dispose();
possAnswer2Bitmap.dispose();
number3.dispose();
possAnswer3Bitmap.dispose();
number4.dispose();
possAnswer4Bitmap.dispose();
}
public boolean isCounted() {
return counted;
}
public void setCounted() {
counted = true;
}
public void resetCounted() {
counted = false;
}
}
<file_sep>package de.mi.ur.WeatherExtras;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import de.mi.ur.Constants;
/**
* Created by Anna-Marie on 11.08.2016.
*
* This class keeps the downloading of weather data away from the main thread and handles further processing of weather data
*/
public class WeatherAsyncTask extends AsyncTask<String, Integer, String> {
private WeatherListener listener;
private int currentWeather;
public WeatherAsyncTask(WeatherListener listener) {
this.listener = listener;
}
/*
* The actual background task,
* downloads data from given URL in params
*/
@Override
protected String doInBackground(String[] params) {
String jsonString = "";
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
jsonString += line;
}
br.close();
is.close();
conn.disconnect();
} else {
throw new IllegalStateException("HTTP response code: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
/*
* handles post executive tasks and notifies the listener, that the download has been finished
*/
protected void onPostExecute(String result) {
super.onPostExecute(result);
int currentWeatherId = getWeatherIdFromJson(result);
currentWeather = calculateCurrentWeather(currentWeatherId);
listener.onDownloadFinished();
}
/*
* Gets the weatherId (an int value representing different states of weather) out of the JSON received as an answer
*/
private int getWeatherIdFromJson(String text) {
int weatherId = -1;
try {
JSONObject jsonObj = new JSONObject(text);
JSONArray weatherArray = jsonObj.getJSONArray("weather");
JSONObject weatherObj = weatherArray.getJSONObject(0);
weatherId = weatherObj.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
return weatherId;
}
/*
* Transfers the weatherId into one of the four possible weather states in NNC (sunny, rainy, cloudy, snowing)
* 2xx - 5xx different types of rain
* 6xx different kinds of snow
* 800 clear (=sunny)
* 80x diffent kinds of clouds
* rest: extremes (e.g. volcanic ash, tornado...) are not represented in NNC
* For further information regarding the weather codes see http://openweathermap.org/weather-conditions
*/
private int calculateCurrentWeather(int weatherId) {
if (weatherId >= 200 && weatherId < 600) {
return Constants.WEATHER_RAINY;
} else if (weatherId >= 600 && weatherId < 700) {
return Constants.WEATHER_SNOWY;
} else if (weatherId == 800) {
return Constants.WEATHER_SUNNY;
} else {
return Constants.WEATHER_CLOUDY;
}
}
/*
* Allows other classes to get the information on currentWeather
*/
public int getCurrentWeather() {
return currentWeather;
}
}
<file_sep>package de.mi.ur.DataBase;
/**
* Created by Anna-Marie on 09.08.2016.
*
* This class represents a Highscore from the game
*/
public class Highscore {
private int rank;
private int points;
private String name;
public Highscore(int rank, int points, String name ){
this.rank = rank;
this.points = points;
this.name = name;
}
public int getRank(){
return this.rank;
}
public int getPoints(){
return this.points;
}
public String getName(){
return this.name;
}
public void lowerRankByOne(){
rank = rank +1;
}
}
<file_sep>package de.mi.ur.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import de.mi.ur.Constants;
import de.mi.ur.DataBase.NNCDatabase;
import de.mi.ur.LevelLogic.DifficultyCalculator;
import de.mi.ur.LevelLogic.Level;
import de.mi.ur.R;
/**
* Created by Lydia on 15.08.2016.
*/
public class PracticeMainActivity extends AppCompatActivity implements View.OnClickListener {
private NumberPicker firstNumberSystem;
private NumberPicker secondNumberSystem;
private Button multipleChoice;
private Button trueFalse;
private Button freeText;
private Toolbar myToolbar;
private NNCDatabase db;
private Level currentLevel;
private int questionLength;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice_main_activity);
db = new NNCDatabase(this);
setupToolbar();
setupNumberPickers();
setupUI();
}
private void setupToolbar() {
myToolbar = (Toolbar) findViewById(R.id.practice_main_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle(R.string.practice_main_toolbar_headline);
myToolbar.setNavigationIcon(R.drawable.toolbar_back);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void setupUI() {
multipleChoice = (Button) findViewById(R.id.multiple_choice_button);
multipleChoice.setOnClickListener(this);
freeText = (Button) findViewById(R.id.manual_entry_button);
freeText.setOnClickListener(this);
trueFalse = (Button) findViewById(R.id.wrong_true_button);
trueFalse.setOnClickListener(this);
}
private void setupNumberPickers() {
firstNumberSystem = (NumberPicker) findViewById(R.id.firstNumberPicker);
secondNumberSystem = (NumberPicker) findViewById(R.id.secondNumberPicker);
firstNumberSystem.setMinValue(2);
firstNumberSystem.setMaxValue(16);
secondNumberSystem.setMinValue(2);
secondNumberSystem.setMaxValue(16);
}
/*
* Handles Click-Events (activity starting)
*/
@Override
public void onClick(View v) {
Intent i = null;
switch (v.getId()) {
case R.id.multiple_choice_button:
i = new Intent(PracticeMainActivity.this, PracticeActivity.class);
i.putExtra(Constants.KEY_TYPE_QUESTION, Constants.MULTIPLE_CHOICE);
break;
case R.id.wrong_true_button:
i = new Intent(PracticeMainActivity.this, PracticeActivity.class);
i.putExtra(Constants.KEY_TYPE_QUESTION, Constants.TRUE_FALSE);
break;
case R.id.manual_entry_button:
i = new Intent(PracticeMainActivity.this, PracticeActivity.class);
i.putExtra(Constants.KEY_TYPE_QUESTION, Constants.FREETEXT);
break;
}
if (i != null) {
int numeral1Base = firstNumberSystem.getValue();
int numeral2Base = secondNumberSystem.getValue();
i.putExtra(Constants.KEY_NUMERAL_1_BASE, numeral1Base);
i.putExtra(Constants.KEY_NUMERAL_2_BASE, numeral2Base);
db.open();
currentLevel = db.getCurrentLevel();
db.close();
questionLength = currentLevel.getQuestionLength();
questionLength += DifficultyCalculator.getBaseQuestionLength(numeral1Base, numeral2Base) ;
i.putExtra(Constants.KEY_QUESTION_LENGTH, questionLength);
startActivity(i);
}
}
}
<file_sep>package de.mi.ur.CustomFont;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import de.mi.ur.Constants;
/**
* Created by maxiwindl on 01.09.16.
*/
public class myCustomTextView extends TextView {
public myCustomTextView(Context context) {
super(context);
utilizeMyFont(context);
}
public myCustomTextView(Context context, AttributeSet attrSet) {
super(context, attrSet);
utilizeMyFont(context);
}
public myCustomTextView(Context context, AttributeSet attrSet, int style) {
super(context, attrSet, style);
utilizeMyFont(context);
}
private void utilizeMyFont(Context context) {
Typeface myFont = FontSaver.getTypeface(Constants.FONT, context);
setTypeface(myFont);
}
}
<file_sep>package de.mi.ur.sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import de.mi.ur.ConstantsGame;
import de.mi.ur.states.PlayState;
/**
* Created by maxiwindl on 31.07.16.
*/
public class Nerd {
public static boolean jumpFinished;
private Vector3 position;
private Vector3 velocity;
private Rectangle bounds;
private Sound sound;
private Texture texture;
private Texture ground;
private Animation nerdAnimation;
public boolean colliding;
public Nerd(int x, int y) {
texture = new Texture("nerd.png");
position = new Vector3(x, y, 0);
velocity = new Vector3(0, 0, 0);
ground = new Texture("ground.png");
bounds = new Rectangle(x, y, texture.getWidth() / 7 + ConstantsGame.BOUNDS_OFFSET, texture.getHeight());
sound = Gdx.audio.newSound(Gdx.files.internal("jumpsfx.ogg"));
nerdAnimation = new Animation(new TextureRegion(texture), 7, 0.6f);
}
public void checkIfJumping() {
if (!jumpFinished) {
nerdAnimation = new Animation(new TextureRegion(texture), 7, 0.6f);
}
}
public void update(float dt, int gravity, float movement) {
checkIfJumping();
nerdAnimation.update(dt);
if (!colliding) {
if (position.y > 0) {
velocity.add(0, gravity, 0);
}
}
//multiplies all the values with the delta time.
velocity.scl(dt);
position.add(movement * dt, velocity.y, 0);
if (position.y <= ground.getHeight() + ConstantsGame.GROUND_Y_OFFSET) {
position.y = ground.getHeight() + ConstantsGame.GROUND_Y_OFFSET;
jumpFinished = true;
}
velocity.scl(1 / dt);
bounds.setPosition(position.x, position.y);
}
public int getWidth() {
return texture.getWidth() / 7;
}
public Vector3 getPosition() {
return position;
}
public void jump() {
if (PlayState.soundEffects) {
sound.play(0.5f);
}
velocity.y = 650;
}
public void dispose() {
sound.dispose();
texture.dispose();
}
public Rectangle getBounds() {
return bounds;
}
public float getX() {
return position.x;
}
public float getY() {
return position.y;
}
public TextureRegion getTexture() {
return nerdAnimation.getFrame();
}
}
<file_sep>package de.mi.ur.gameLogic;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.Timer;
import de.mi.ur.ConstantsGame;
import de.mi.ur.states.GameOverState;
import de.mi.ur.states.GameStateManager;
import de.mi.ur.states.PlayState;
/**
* Created by maxiwindl on 07.08.16.
*/
public class Score {
private static String currentScore;
private static long currentBasicScorePoints;
private static Texture heartFilled;
public static Array<Texture> hearts;
private long startTime;
private static Sound powerUp;
public static Sound gameOver;
BitmapFont scoreFont;
private static Sound fail;
private String pointUpdateString;
private BitmapFont updateFont;
private static Texture heartEmpty;
private static boolean pointsAdded;
public static int state;
public Score() {
hearts = new Array<Texture>();
powerUp = Gdx.audio.newSound(Gdx.files.internal("powerupsfx.ogg"));
state = 4;
fail = Gdx.audio.newSound(Gdx.files.internal("failsfx.ogg"));
gameOver = Gdx.audio.newSound(Gdx.files.internal("gameoversfx.ogg"));
currentScore = "Score: 0";
currentBasicScorePoints = 0;
scoreFont = new BitmapFont(Gdx.files.internal("goodTimesNew.fnt"));
heartFilled = new Texture("heart_filled.png");
heartEmpty = new Texture("heart_empty.png");
scoreFont.setUseIntegerPositions(false);
updateFont = new BitmapFont();
updateFont.setUseIntegerPositions(false);
}
public static void changeHeart(Boolean isDead, int position) {
if (isDead) {
hearts.set(position, heartEmpty);
} else {
hearts.set(position, heartFilled);
}
}
public void renderScore(SpriteBatch batch, OrthographicCamera cam) {
for (int i = 0; i < 3; i++) {
hearts.add(heartFilled);
batch.draw(hearts.get(i), cam.position.x + ConstantsGame.SCORE_HEARTS_OFFSET_X + i * hearts.get(i).getWidth(), cam.position.y + ConstantsGame.SCORE_HEARTS_OFFSET_Y);
}
scoreFont.draw(batch, currentScore, cam.position.x + ConstantsGame.SCORE_OFFSET_X, cam.position.y + ConstantsGame.SCORE_OFFSET_Y);
scoreFont.setColor(Color.BLACK);
}
public long getCurrentScore() {
return getTimeElapsed();
}
private long getCurrentBasicScorePoints() {
return currentBasicScorePoints;
}
public long getCurrentScorePoints() {
return getCurrentScore() + getCurrentBasicScorePoints();
}
public long startTimer() {
startTime = TimeUtils.millis();
return startTime;
}
private long getTimeElapsed() {
return TimeUtils.timeSinceMillis(startTime) / 1000;
}
/*
* state 1: 2 hearts full
* state 2: 1 heart full
* state 3: 0 hearts full
* state 4: all hearts full
*/
public static int getStateOfHearts() {
if ((!PlayState.alreadChanged && hearts.get(0) == heartEmpty) && (hearts.get(1) == heartFilled) && hearts.get(2) == heartFilled) {
state = ConstantsGame.HEARTSTATE_2_HEARTS;
PlayState.alreadChanged = true;
return state;
} else if (!PlayState.alreadChanged && hearts.get(0) == heartEmpty && hearts.get(1) == heartEmpty && hearts.get(2) == heartFilled) {
state = ConstantsGame.HEARTSTATE_1_HEART;
PlayState.alreadChanged = true;
return state;
} else if (!PlayState.alreadChanged && hearts.get(0) == heartEmpty && hearts.get(1) == heartEmpty && hearts.get(2) == heartEmpty) {
state = ConstantsGame.HEARTSTATE_NO_HEART;
PlayState.alreadChanged = true;
return state;
} else if (!PlayState.alreadChanged && hearts.get(0) == heartFilled && hearts.get(1) == heartFilled && hearts.get(2) == heartFilled) {
PlayState.alreadChanged = true;
state = ConstantsGame.HEARTSTATE_ALL_HEARTS_FULL;
return state;
} else {
return ConstantsGame.HEARTSTATE_OTHER;
}
}
/**
* this method is called, whenever the nerd loses one life. The method checks in which state the hearts are, e.g.
* which heart has to be set to an empty shape. To that it also plays the "fail" soundeffect, when the soundeffects are enabled in the settings.
*/
public static void updateHeart(GameStateManager manager, boolean dead) {
state = getStateOfHearts();
if (PlayState.soundEffects) {
fail.play(0.5f);
}
if (state == ConstantsGame.HEARTSTATE_ALL_HEARTS_FULL) {
changeHeart(dead, 0);
} else if (state == ConstantsGame.HEARTSTATE_NO_HEART) {
gameOver.play(0.5f);
manager.set(new GameOverState(manager));
} else if (state == ConstantsGame.HEARTSTATE_1_HEART) {
changeHeart(dead, 2);
} else if (state == ConstantsGame.HEARTSTATE_2_HEARTS) {
changeHeart(dead, 1);
}
}
/**
* this method does nearly the same as the updateHeart method, but is called when the nerd regains a heart.
* To that it plays the "power up" soundeffect, when the soundeffects are enabled in the settings.
*/
public static void refillHeart() {
state = getStateOfHearts();
if (PlayState.soundEffects) {
powerUp.play(0.5f);
}
if (state == ConstantsGame.HEARTSTATE_ALL_HEARTS_FULL) {
addPoints();
pointsAdded = true;
} else if (state == ConstantsGame.HEARTSTATE_NO_HEART) {
changeHeart(false, 2);
} else if (state == ConstantsGame.HEARTSTATE_1_HEART) {
changeHeart(false, 1);
} else if (state == ConstantsGame.HEARTSTATE_2_HEARTS) {
changeHeart(false, 0);
}
}
public static void addPoints() {
currentBasicScorePoints += 10;
}
/**
* this method updates the score shown on the game in the top left corner. Per second the player gets
* one point.
* @param manager
*/
public void updateScore(GameStateManager manager) {
if (getTimeElapsed() < 2) {
currentScore = "0" + getTimeElapsed() + " Point";
}
if (getTimeElapsed() > 1 && getTimeElapsed() < 10) {
currentScore = "0" + getTimeElapsed() + " Points";
} else {
currentScore = "" + (getTimeElapsed() + currentBasicScorePoints) + " Points";
}
}
public void showPointUpdate(SpriteBatch batch, OrthographicCamera cam) {
if (pointsAdded) {
pointUpdateString = "+10 Points!";
updateFont.setColor(Color.GREEN);
updateFont.draw(batch, pointUpdateString, cam.position.x - 70, cam.position.y + 10);
updateFont.setColor(Color.GREEN);
Timer.schedule(new Timer.Task() {
@Override
public void run() {
setPointsAdded();
}
}, 2);
}
}
private boolean setPointsAdded() {
return pointsAdded = false;
}
public void dispose() {
gameOver.dispose();
powerUp.dispose();
fail.dispose();
for (Texture heart : hearts) {
heart.dispose();
}
updateFont.dispose();
scoreFont.dispose();
}
}
<file_sep>package de.mi.ur.QuestionFragments;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import de.mi.ur.R;
/**
* Created by Anna-Marie on 05.08.2016.
*/
public class FreeTextQuestionFragment extends QuestionFragment {
private EditText solutionEditText;
private OnKeyboardListener mCallback;
public FreeTextQuestionFragment(){
super();
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.free_text_question_fragment, container, false);
this.solutionEditText = (EditText) fragmentView.findViewById(R.id.freetext_edit_text);
this.solutionEditText.setOnFocusChangeListener(new View.OnFocusChangeListener(){
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) mCallback.onOpen();
}
});
this.solutionEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCallback.onOpen();
}
});
return fragmentView;
}
public interface OnKeyboardListener{
void onOpen();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnKeyboardListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnKeyboardListener");
}
}
public EditText getSolutionEditText(){
return solutionEditText;
}
public String getTextFromSolutionEditText(){
return solutionEditText.getText().toString();
}
public void deleteText(){
solutionEditText.setText("");
}
public void setTextInvisible(){
solutionEditText.setVisibility(View.INVISIBLE);
}
public void setTextVisible(){
solutionEditText.setVisibility(View.VISIBLE);
}
/*
* Gets the input from the EditText and compares it in case of right answer returns true, else false,
* in both cases resets EditText to empty
*/
public boolean isCorrectAnswer(String rightAnswer){
if((solutionEditText.getText().toString()).equals(trimLeadingZeros(rightAnswer))){
solutionEditText.setText("");
return true;
}else{
solutionEditText.setText("");
return false;
}
}
/*
* Value of a number is the same with or without leading zeros, for comparability, they are trimmed away
*/
private String trimLeadingZeros(String string) {
String trimmed = string.trim();
for (int i = 0; i < string.length() - 1; i++) {
if (string.charAt(i) == '0') {
trimmed = trimmed.substring(1);
} else {
break;
}
}
return trimmed;
}
public void setSolutionEditTextInputType(int inputType){
solutionEditText.setInputType(inputType);
}
}
<file_sep>package de.mi.ur.Activities;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import de.mi.ur.AndroidCommunication.WeatherDataListener;
import de.mi.ur.AndroidLauncher;
import de.mi.ur.Constants;
import de.mi.ur.R;
import de.mi.ur.WeatherExtras.WeatherListener;
import de.mi.ur.WeatherExtras.WeatherManager;
public class GameMainActivity extends AppCompatActivity implements View.OnClickListener, WeatherDataListener, WeatherListener {
private Button buttonStartGame;
private Button buttonWeather;
private Button buttonViewHighscore;
private Button buttonHelp;
private WeatherManager weatherManager;
private Toolbar myToolbar;
private SharedPreferences sharedPref;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_main_activity);
setupUI();
setupToolbar();
weatherManager = new WeatherManager(this, this, this);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
private void setupToolbar() {
myToolbar = (Toolbar) findViewById(R.id.game_main_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle(R.string.game_main_toolbar_headline);
myToolbar.setNavigationIcon(R.drawable.toolbar_back);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/*
* This method shows the menu (only settings icon here) in the toolbar
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_settings_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/*
* This method is the onClickListener and onClick-Method for the menu-item (settings icon)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(GameMainActivity.this, SettingsActivity.class);
startActivity(i);
return super.onOptionsItemSelected(item);
}
private void setupUI() {
buttonStartGame = (Button) findViewById(R.id.game_start_button);
buttonStartGame.setOnClickListener(this);
buttonWeather = (Button) findViewById(R.id.game_update_weather_button);
buttonWeather.setOnClickListener(this);
buttonViewHighscore = (Button) findViewById (R.id.game_highscore_button);
buttonViewHighscore.setOnClickListener(this);
buttonHelp = (Button) findViewById (R.id.game_help_button);
buttonHelp.setOnClickListener(this);
}
/*
* Handles Click-Events (mostly activity starting)
*/
@Override
public void onClick(View v) {
Intent i = null;
switch (v.getId()){
case R.id.game_start_button:
i = new Intent(GameMainActivity.this, AndroidLauncher.class);
i.putExtra(Constants.CURRENT_WEATHER, weatherManager.getCurrentWeather());
i.putExtra(Constants.BACKGROUND_MUSIC, getBackgroundMusic());
i.putExtra(Constants.SOUND_EFFECTS, getSoundEffects());
break;
case R.id.game_update_weather_button:
handleWeatherButtonClick();
break;
case R.id.game_highscore_button:
i = new Intent(GameMainActivity.this, HighscoreActivity.class);
break;
case R.id.game_help_button:
i = new Intent(GameMainActivity.this, GameHelpActivity.class);
break;
default:
break;
}
if(i!=null){
startActivity(i);
}
}
/*
* requests new weather information (if relevant permissions were given
* else informs the user that default weather was set)
*/
private void handleWeatherButtonClick() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
weatherManager.startCurrentWeatherGetter();
} else {
requestWeatherPermission(this);
String toastMessage = getResources().getString(R.string.default_weather_toast);
Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
}
}
/*
* Checks the parameter, which kind of weather it is and generates appropriate content for user information
*/
private String convertToWeatherName(int weatherNumber) {
switch (weatherNumber) {
case Constants.WEATHER_SUNNY:
return getResources().getString(R.string.weather_sunny);
case Constants.WEATHER_CLOUDY:
return getResources().getString(R.string.weather_cloudy);
case Constants.WEATHER_RAINY:
return getResources().getString(R.string.weather_rainy);
case Constants.WEATHER_SNOWY:
return getResources().getString(R.string.weather_snowy);
default:
return getResources().getString(R.string.weather_default);
}
}
@Override
public int getCurrentWeather() {
return weatherManager.getCurrentWeather();
}
/*
* Requests the permission to access location data (fine location is required to use the gps-sensor.
*/
public static void requestWeatherPermission(Activity activity) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Constants.MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
} else {
createInformationDialog(activity);
}
}
/*
* Shows an information dialog to explain why the location permission is needed.
*/
private static void createInformationDialog(Activity activity){
final Activity activity1 = activity;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.location_permission_explanation).setTitle(R.string.location_permission_headline);
builder.setPositiveButton(R.string.ok_string, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(activity1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Constants.MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
}
});
AlertDialog permissionInfoDialog = builder.create();
permissionInfoDialog.show();
}
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case Constants.MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
weatherManager.getCurrentWeather();
}
break;
}
}
}
/*
* If the download and processing of new weather data is finished, this method is called to notify the user.
*/
@Override
public void onDownloadFinished() {
String weather = convertToWeatherName(weatherManager.getCurrentWeather());
String toastMessage = getResources().getString(R.string.weather_toast_1) + weather + getResources().getString(R.string.weather_toast_2);
Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
}
private boolean getBackgroundMusic() {
return sharedPref.getBoolean("pref_music", true);
}
private boolean getSoundEffects() {
return sharedPref.getBoolean("pref_sound_effects", true);
}
}
<file_sep>package de.mi.ur.sprites;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import de.mi.ur.ConstantsGame;
import de.mi.ur.states.PlayState;
/**
* Created by maxiwindl on 01.08.16.
*/
public class Pit extends Obstacle {
private Texture pit;
private Rectangle bounds;
private Vector2 pitPos;
public Pit (float x) {
super(x, 0, new Texture("pit_old.png"), ConstantsGame.PIT_TYPE);
if (PlayState.sunny) {
pit = new Texture("pit_old.png");
} else {
pit = new Texture("pit_bad_weather.png");
}
pitPos = new Vector2(x, 0);
bounds = new Rectangle(pitPos.x, pitPos.y, pit.getWidth() + ConstantsGame.BOUNDS_OFFSET, pit.getHeight());
}
public Texture getPit () {
return pit;
//return super.getObstacle();
}
public Vector2 getPitPos() {
//return super.getObstaclePos();
return pitPos;
}
public Vector2 getObstaclePos() {
return getPitPos();
}
public Texture getTexture() {
return pit;
}
public boolean collides(Rectangle player){
// return super.collides(player);
return player.overlaps(bounds);
}
public void dispose() {
// super.dispose();
pit.dispose();
}
public void reposition(float x){
//super.reposition(x);
pitPos.set(x, 0);
bounds.setPosition(pitPos.x, pitPos.y);
}
}
<file_sep>package de.mi.ur.QuestionLogic;
import java.util.Random;
import de.mi.ur.Constants;
/**
* Created by Anna-Marie on 06.09.2016.
*/
public class NumeralConverter {
private static Random randomGen = new Random();
public NumeralConverter(){}
/*
* Int number is converted to a String as a representation of another numeral system
*/
public static String convertToNumeral(int number, int radix){
if (radix < Constants.MIN_NUMERAL_BASE || radix > Constants.MAX_NUMERAL_BASE) {
radix = Constants.DEFAULT_NUMERAL_BASE;
}
String toReturn = Integer.toString(number, radix);
return toReturn.toUpperCase();
}
/*
* String representation of a number in a numeralsystem with base radix is converted to a decimal int
*/
public static int convertFromNumeral(String number, int radix){
return Integer.parseInt(number, radix);
}
/*
* String representation of a number is converted from one numeralSystem (base radixInput base) to another (base radixOutput)
*/
public static String convertFromNumeralToNumeral(String number, int radixInput, int radixOutput){
int num = convertFromNumeral(number, radixInput);
return convertToNumeral(num, radixOutput);
}
/*
* Generates a number in the numeral system with base numeralBase and maxDigits digits
*/
public static String generateNumWithMaxDigits(int numeralBase, int maxDigits){
String number = "";
for(int i = 0; i<maxDigits; i++){
int num = randomGen.nextInt(numeralBase);
number += convertToNumeral(num, numeralBase);
}
return number;
}
/*
* Generates a number in the destinationNumeralBase numeral system, which is below the threshold maxDecimal (in decimal numeral system)
*/
public static String generateNumBelowMax(int destinationNumeralBase, int maxDecimal){
int num = randomGen.nextInt(maxDecimal);
return convertToNumeral(num, destinationNumeralBase);
}
}
<file_sep>package de.mi.ur.NumberPicker;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.NumberPicker;
/**
* Created by Anna-Marie on 01.09.2016.
*
* Enables setting the min, max, and default Values of the Number Picker in the xml, separating code and layout
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NumeralNumberPicker extends NumberPicker {
public NumeralNumberPicker(Context context) {
super(context);
}
public NumeralNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
processAttributeSet(attrs);
}
public NumeralNumberPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
processAttributeSet(attrs);
}
private void processAttributeSet(AttributeSet attrs) {
//This method reads the parameters given in the xml file and sets the properties according to it
this.setMinValue(attrs.getAttributeIntValue(null, "min", 0));
this.setMaxValue(attrs.getAttributeIntValue(null, "max", 0));
this.setValue(attrs.getAttributeIntValue(null, "default", 0));
}
}
<file_sep>package de.mi.ur.QuestionLogic;
import android.content.res.Resources;
/**
* Created by Anna-Marie on 19.08.2016.
*
* Is a basis, so that they can be saved together with FreeTextQuestions in a single Instance Variable
*/
public class KnowledgeQuestion extends Question {
String question;
String rightAnswer;
public KnowledgeQuestion(String question, String rightAnswer) {
super(-1, -1, -1);
this.question = question;
this.rightAnswer = rightAnswer;
}
@Override
public boolean isCorrectAnswer(String answer) {
return answer.equals(rightAnswer);
}
@Override
public String getQuestionString(Resources resources) {
return question;
}
public String getRightAnswerString() {
return rightAnswer;
}
}
|
fde10a2a5e9afbeda949af2e654d2baadae7d262
|
[
"Java"
] | 17
|
Java
|
Maxikilliane/NerdyNumeralChallenge
|
3b7a18d33365bca993e3e17a5c6fb63ffeb06a4c
|
d75b55086a254a3b8a7e8f6adb5f52684afb0d00
|
refs/heads/master
|
<file_sep>using System;
namespace exercise2
{
class Program
{
static void Main(string[] args)
{
string appUsername = "dionfinnerty";
string appPassword = "<PASSWORD>";
Console.WriteLine("please enter username");
string username = Console.ReadLine();
Console.WriteLine("please enter your password!");
string userPassword = Console.ReadLine();
if (username == appUsername )
{
if (userPassword == appPassword)
{
Console.WriteLine("login successful");
}
else
{
Console.WriteLine("login unsuccessful");
}
}
else
{
Console.WriteLine("login unsuccessful");
}
}
}
}
<file_sep>using System;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("what is your age?");
string age = Console.ReadLine();
int userAge = int.Parse(age);
Console.WriteLine("are you male or female?");
string userGender = Console.ReadLine();
Console.WriteLine("enter a random number between 1-10!");
string userNum1 = Console.ReadLine();
int number1 = int.Parse(userNum1);
Console.WriteLine("enter another random number between 1-10!");
string userNum2 = Console.ReadLine();
int number2 = int.Parse(userNum2);
if (userAge > 17)
{
Console.WriteLine("Legally adult age");
if (userGender == "male")
{
Console.WriteLine("Male is an adult");
}
if (userGender == "female")
{
Console.WriteLine("Female is an adult");
}
}
else
{
Console.WriteLine("Legally not adult age");
if (userGender == "male")
{
Console.WriteLine("Male is not an adult");
}
if (userGender == "female")
{
Console.WriteLine("Female is not an adult");
}
}
if (number2 + number1 > 10)
{
Console.WriteLine("Sum of numbers is greater than 10");
}
else
if (number2 + number1 < 10)
{
Console.WriteLine("Sum of numbers is less than 10");
}
}
}
}
|
f886289daf2251a86549833f2b5f381ffbdade6d
|
[
"C#"
] | 2
|
C#
|
DionFinn/SelectionTaskEx1
|
e36c8b31521f23d6cfb47ce37e0e9c3b70ea64cb
|
e1508e5021230a03299ff2a0c7049ac9e90a7ca8
|
refs/heads/master
|
<file_sep>package com.example.giaodientrangchu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.adapter.AdapterBV;
import com.example.adapter.AdapterTrieuChung;
import com.example.model.BenhVien;
import com.example.model.TrieuChung;
import java.util.ArrayList;
public class activity_tu_van extends AppCompatActivity {
ImageButton imbtnBack;
ListView lvTC;
ArrayList<TrieuChung> arrayList;
AdapterTrieuChung adapterTrieuChung;
EditText edtSearch;
ArrayAdapter<TrieuChung> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tu_van);
linkView();
loadData();
addEvents();
}
private void addEvents() {
imbtnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(activity_tu_van.this,MainActivity.class);
startActivity(intent);
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
activity_tu_van.this.adapter.getFilter().filter(charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
private void loadData() {
arrayList = new ArrayList<>();
arrayList.add(new TrieuChung("Buồn nôn"));
arrayList.add(new TrieuChung("Bị đau cơ khi căng người"));
arrayList.add(new TrieuChung("Bị choáng khi đứng lên đột ngột"));
arrayList.add(new TrieuChung("Đau thắt ngực trái"));
arrayList.add(new TrieuChung("Đau vùng thuợng vị"));
arrayList.add(new TrieuChung("Choáng váng"));
adapterTrieuChung = new AdapterTrieuChung(activity_tu_van.this,R.layout.list_trieu_chung,arrayList);
lvTC.setAdapter(adapterTrieuChung);
}
private void linkView() {
imbtnBack = findViewById(R.id.imbtnBack);
lvTC = findViewById(R.id.lvTC);
edtSearch = findViewById(R.id.edtSearch);
}
}<file_sep>package com.example.model;
public class TrieuChung {
private String trieuchung;
public TrieuChung(String triechung) {
this.trieuchung = triechung;
}
public String getTrieuchung() {
return trieuchung;
}
}
<file_sep>package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.giaodientrangchu.R;
import com.example.model.BenhVien;
import java.util.ArrayList;
public class AdapterBV extends BaseAdapter {
Context context;
int item_layout;
ArrayList<BenhVien> benhViens;
public AdapterBV(Context context, int item_layout, ArrayList<BenhVien> benhViens) {
this.context = context;
this.item_layout = item_layout;
this.benhViens = benhViens;
}
@Override
public int getCount() {
return benhViens.size();
}
@Override
public Object getItem(int i) {
return benhViens.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(item_layout, null);
holder.imvThumbBV = view.findViewById(R.id.imvThumbBV);
holder.txtNameBV = view.findViewById(R.id.txtNameBV);
holder.txtAddress = view.findViewById(R.id.txtAddress);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
BenhVien b = benhViens.get(i);
holder.imvThumbBV.setImageResource(b.getThumbBV());
holder.txtNameBV.setText(String.valueOf(b.getName()));
holder.txtAddress.setText(String.valueOf(b.getAddress()));
return view;
}
protected static class ViewHolder {
ImageView imvThumbBV;
TextView txtNameBV, txtAddress;
}
}
<file_sep>package com.example.giaodientrangchu;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
public class activity_verifyotp extends AppCompatActivity {
EditText edtInputOTP,edtInputOTP_2,edtInputOTP_3,edtInputOTP_4,edtInputOTP_5,edtInputOTP_6;
TextView txtMobile;
ProgressBar progressBar;
Button btnVerify;
private String verificationId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verifyotp);
linkViews();
addEvents();
setupInputs();
}
private void linkViews() {
txtMobile = findViewById(R.id.txtMobile);
progressBar = findViewById(R.id.progressbar);
btnVerify = findViewById(R.id.btnVerify);
edtInputOTP = findViewById(R.id.edtInputOTP);
edtInputOTP_2 = findViewById(R.id.edtInputOTP_2);
edtInputOTP_3 = findViewById(R.id.edtInputOTP_3);
edtInputOTP_4 = findViewById(R.id.edtInputOTP_4);
edtInputOTP_5 = findViewById(R.id.edtInputOTP_5);
edtInputOTP_6 = findViewById(R.id.edtInputOTP_6);
}
private void addEvents() {
txtMobile.setText(String.format("+84-",getIntent().getStringExtra("sdt")));
verificationId = getIntent().getStringExtra("verificationId");
btnVerify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(edtInputOTP.getText().toString().trim().isEmpty()
|| edtInputOTP_2.getText().toString().trim().isEmpty()
||edtInputOTP_3.getText().toString().trim().isEmpty()
||edtInputOTP_4.getText().toString().trim().isEmpty()
|| edtInputOTP_5.getText().toString().trim().isEmpty()
|| edtInputOTP_6.getText().toString().trim().isEmpty()){
Toast.makeText(activity_verifyotp.this,"Vui lòng nhập otp", Toast.LENGTH_SHORT).show();
return;
}
String code = edtInputOTP.getText().toString()+
edtInputOTP_2.getText().toString()+
edtInputOTP_3.getText().toString()+
edtInputOTP_4.getText().toString()+
edtInputOTP_5.getText().toString()+
edtInputOTP_6.getText().toString();
if(verificationId != null){
progressBar.setVisibility(View.VISIBLE);
btnVerify.setVisibility(View.INVISIBLE);
PhoneAuthCredential phoneAuthProvider = PhoneAuthProvider.getCredential(
verificationId,
code
);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthProvider).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
btnVerify.setVisibility(View.VISIBLE);
if (task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else Toast.makeText(activity_verifyotp.this,"Otp không hợp lệ", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
private void setupInputs(){
edtInputOTP.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().trim().isEmpty()){
edtInputOTP_2.requestFocus();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
edtInputOTP_2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().trim().isEmpty()){
edtInputOTP_3.requestFocus();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
edtInputOTP_3.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().trim().isEmpty()){
edtInputOTP_4.requestFocus();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
edtInputOTP_4.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().trim().isEmpty()){
edtInputOTP_5.requestFocus();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
edtInputOTP_5.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().trim().isEmpty()){
edtInputOTP_6.requestFocus();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}<file_sep>package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.giaodientrangchu.R;
import com.example.model.ThongBao;
import java.util.ArrayList;
public class AdapterTB extends BaseAdapter {
Context context;
int item_layout;
ArrayList<ThongBao> thongBaos;
public AdapterTB(Context context, int item_layout, ArrayList<ThongBao> thongBaos) {
this.context = context;
this.item_layout = item_layout;
this.thongBaos = thongBaos;
}
@Override
public int getCount() {
return thongBaos.size();
}
@Override
public Object getItem(int i) {
return thongBaos.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder1 holder;
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(view==null) {
holder = new ViewHolder1();
view = inflater.inflate(item_layout, null);
holder.imvThumbTB = view.findViewById(R.id.imvThumbTB);
holder.txtThongBao = view.findViewById(R.id.txtThongBao);
holder.txtNgay = view.findViewById(R.id.txtNgay);
holder.txtGioKham = view.findViewById(R.id.txtGioKham);
holder.txtTime=view.findViewById(R.id.txtTime);
view.setTag(holder);
}else {
holder=(ViewHolder1) view.getTag();
}
ThongBao b= thongBaos.get(i);
holder.imvThumbTB.setImageResource(b.getThumbTB());
holder.txtThongBao.setText(String.valueOf(b.getThongBao()));
holder.txtNgay.setText(String.valueOf(b.getNgay()));
holder.txtGioKham.setText(String.valueOf(b.getTime()));
return view;
}
protected static class ViewHolder1{
ImageView imvThumbTB;
TextView txtNgay,txtGioKham,txtTime,txtThongBao;
}
}
<file_sep>package com.example.giaodientrangchu;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class Login_Activity extends AppCompatActivity {
EditText inputMobile ;
Button btnLogin;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
linkViews();
addEvents();
}
private void linkViews() {
inputMobile = findViewById(R.id.edtSđt);
btnLogin = findViewById(R.id.btnLogin);
progressBar = findViewById(R.id.progressbar);
}
private void addEvents() {
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inputMobile.getText().toString().trim().isEmpty()){
Toast.makeText(Login_Activity.this,"Nhập số điện thoại", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
btnLogin.setVisibility(View.INVISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber("+84" + inputMobile.getText().toString(),
60, TimeUnit.SECONDS,
Login_Activity.this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks(){
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
progressBar.setVisibility(View.GONE);
btnLogin.setVisibility(View.VISIBLE);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
progressBar.setVisibility(View.GONE);
btnLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login_Activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId , @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
progressBar.setVisibility(View.GONE);
btnLogin.setVisibility(View.VISIBLE);
Intent intent = new Intent(getApplicationContext(), activity_verifyotp.class);
intent.putExtra("mobile", inputMobile.getText().toString());
intent.putExtra("verificationId",verificationId);
startActivity(intent);
}
});
}
});
}
}<file_sep>package com.example.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.giaodientrangchu.R;
import com.example.model.Postdiendan;
import java.util.List;
public class DiendanAdapter extends BaseAdapter {
Activity context;
int item_listview;
List<Postdiendan> postdiendanList;
public DiendanAdapter(Activity context, int item_listview, List<Postdiendan> postdiendanList) {
this.context = context;
this.item_listview = item_listview;
this.postdiendanList = postdiendanList;
}
@Override
public int getCount() {
return postdiendanList.size();
}
@Override
public Object getItem(int i) {
return postdiendanList.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder=null;
if(view==null){
holder= new ViewHolder();
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(item_listview,null);
holder.txtUserName=view.findViewById(R.id.txtName_User);
holder.txtUserTime=view.findViewById(R.id.txtThoiGian);
holder.txtUserQuestion=view.findViewById(R.id.txtQuestion);
view.setTag(holder);
} else {
holder= (ViewHolder) view.getTag();
}
Postdiendan postdiendan=postdiendanList.get(i);
holder.txtUserName.setText(postdiendan.getUserName());
holder.txtUserTime.setText(postdiendan.getUserTime());
holder.txtUserQuestion.setText(postdiendan.getUserQuestion());
return view;
}
public static class ViewHolder{
TextView txtUserName, txtUserTime, txtUserQuestion;
}
}
<file_sep>package com.example.model;
public class LichKhamht {
private String hospitalName,hospitalTime,hospitalDate,hospitalXN;
private int hositalThumb;
public LichKhamht(String hospitalName, String hospitalTime, String hospitalDate, String hospitalXN, int hositalThumb) {
this.hospitalName = hospitalName;
this.hospitalTime = hospitalTime;
this.hospitalDate = hospitalDate;
this.hospitalXN = hospitalXN;
this.hositalThumb = hositalThumb;
}
public String getHospitalName() {
return hospitalName;
}
public void setHospitalName(String hospitalName) {
this.hospitalName = hospitalName;
}
public String getHospitalTime() {
return hospitalTime;
}
public void setHospitalTime(String hospitalTime) {
this.hospitalTime = hospitalTime;
}
public String getHospitalDate() {
return hospitalDate;
}
public void setHospitalDate(String hospitalDate) {
this.hospitalDate = hospitalDate;
}
public String getHospitalXN() {
return hospitalXN;
}
public void setHospitalXN(String hospitalXN) {
this.hospitalXN = hospitalXN;
}
public int getHositalThumb() {
return hositalThumb;
}
public void setHositalThumb(int hositalThumb) {
this.hositalThumb = hositalThumb;
}
}
<file_sep>package com.example.giaodientrangchu;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.model.BenhVien;
import com.example.adapter.AdapterBV;
import java.util.ArrayList;
public class Booking_Activity extends AppCompatActivity {
ImageView imvShapeGreen,imbtnHomePage,imbtnLichKham,imbtnThongBao,imbtnTaiKhoan,imbtnBack;;
TextView txtListBV;
ListView lvBV;
ArrayList<BenhVien> arrayList;
AdapterBV adapterBV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
linkView();
loadData();
addEvents();
}
private void addEvents() {
imbtnLichKham.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Booking_Activity.this,LichKham.class);
startActivity(intent);
}
});
imbtnThongBao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Booking_Activity.this,ThongBao_Activity.class);
startActivity(intent);
}
});
imbtnTaiKhoan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Booking_Activity.this,TrangUser.class);
startActivity(intent);
}
});
imbtnHomePage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Booking_Activity.this,MainActivity.class);
startActivity(intent);
}
});
imbtnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Booking_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void linkView() {
lvBV=findViewById(R.id.lvBV);
imvShapeGreen=findViewById(R.id.imvShapeGreen);
txtListBV=findViewById(R.id.txtListBV);
imbtnHomePage=findViewById(R.id.imbtnHomePage);
imbtnLichKham=findViewById(R.id.imbtnLichKham);
imbtnThongBao=findViewById(R.id.imbtnThongBao);
imbtnTaiKhoan=findViewById(R.id.imbtnTaikhoan);
imbtnBack=findViewById(R.id.imbtnBachDatLich);
}
private void loadData() {
arrayList = new ArrayList<>();
arrayList.add(new BenhVien(R.drawable.bv_tudu, "Bệnh viện Từ Dũ", "284, Cống Quỳnh, Phạm Ngũ Lão, Q.1,HCM"));
arrayList.add(new BenhVien(R.drawable.bv_choray, "Bệnh viện Chợ Rẫy", "21B,Nguyễn Chí Thanh, P.12, Q.5,HCM"));
arrayList.add(new BenhVien(R.drawable.bv_yduoc, "Bệnh viện Y Dược", "201,Nguyễn Chí Thanh, P.12, Q.5,HCM"));
adapterBV = new AdapterBV(Booking_Activity.this, R.layout.item_list_bv, arrayList);
lvBV.setAdapter(adapterBV);
}}
<file_sep>package com.example.giaodientrangchu;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
public class HoSo_Activity extends AppCompatActivity {
ImageButton imbtnHomePage,imbtnLichKham,imbtnThongBao,imbtnTaiKhoan,imbtnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ho_so);
linkView();
addEvents();
}
private void addEvents() {
imbtnLichKham.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(HoSo_Activity.this,LichKham.class);
startActivity(intent);
}
});
imbtnThongBao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(HoSo_Activity.this,ThongBao_Activity.class);
startActivity(intent);
}
});
imbtnTaiKhoan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(HoSo_Activity.this,TrangUser.class);
startActivity(intent);
}
});
imbtnHomePage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(HoSo_Activity.this,MainActivity.class);
startActivity(intent);
}
});
imbtnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(HoSo_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void linkView() {
imbtnHomePage=findViewById(R.id.imbtnHomePage);
imbtnLichKham=findViewById(R.id.imbtnLichKham);
imbtnThongBao=findViewById(R.id.imbtnThongBao);
imbtnTaiKhoan=findViewById(R.id.imbtnTaikhoan);
imbtnBack=findViewById(R.id.imbtnBackHoso);
}
}<file_sep>package com.example.model;
public class ThongBao {
private int thumbTB;
private String thongBao;
private String ngay;
private String gioKham;
private String time;
public ThongBao(int thumbTB, String thongBao, String ngay, String gioKham, String time) {
this.thumbTB = thumbTB;
this.thongBao = thongBao;
this.ngay = ngay;
this.gioKham = gioKham;
this.time = time;
}
public int getThumbTB() {
return thumbTB;
}
public void setThumbTB(int thumbTB) {
this.thumbTB = thumbTB;
}
public String getThongBao() {
return thongBao;
}
public void setThongBao(String thongBao) {
this.thongBao = thongBao;
}
public String getNgay() {
return ngay;
}
public void setNgay(String ngay) {
this.ngay = ngay;
}
public String getGioKham() {
return gioKham;
}
public void setGioKham(String gioKham) {
this.gioKham = gioKham;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
|
b8556905d27308d8684d2165042d6ec8d9e6b0fb
|
[
"Java"
] | 11
|
Java
|
minh-ngan/App_Hepat
|
b8ca3ee2ededc10c5e991e9490cb51af5ba0c425
|
7acf9d10e8ce5fc9c15be9d283e10d9db0a9deeb
|
refs/heads/master
|
<file_sep>####################
# 给定 trigger 预测 这个trigger的属性 subject time value ratio..
## 原始句子 company time trigger1 m m m, org time trigger2 m m m
## 想分别预测 trigger1 的相关 attribute:company time m m m ,
# trigger2和相关的属性 都作为unlabel
## 输入 company time triggerRoot m m m, org time trigger m m m
## 输出 subject time trigger value value value unlabel unlabel unlabel unlabel unlabel unlabel
import json
import re
import sys
import os
import copy
import numpy as np
lenll=[]
p_num=re.compile('\d+')
f='./train.json'
writer=open('tmp.txt','w')
reader=open(f)
n=0
for line in reader.readlines():
ll=json.loads(line)
print ('')
line=' '.join([d['char'] for d in ll])
print (line)
writer.write(line+'\n')
n+=1
if n>5:break<file_sep>#!/bin/bash
image=tensorflow/tensorflow:1.15.2-gpu-py3
docker run -it --name cc --runtime=nvidia -v /home/op/congc/:/vproblem $image bash<file_sep>####################
# 给定 trigger 预测 这个trigger的属性 subject time value ratio..
## 原始句子 company time trigger1 m m m, org time trigger2 m m m
## 想分别预测 trigger1 的相关 attribute:company time m m m ,
# trigger2和相关的属性 都作为unlabel
## 输入 company time triggerRoot m m m, org time trigger m m m
## 输出 subject time trigger value value value unlabel unlabel unlabel unlabel unlabel unlabel
import json
import re
import sys
import os
import copy
import numpy as np
import pandas as pdd
lenll=[]
p_num=re.compile('\d+')
event_mention_typ={'m','TIME','trigger','WithIn','company','ORG'}
def make_pair(head,headpos,tail,tailpos,rela):
return ' '.join([head,str(headpos),tail,str(tailpos),rela])
def calc_precision_recall_f1(yll,predll):
yll=set(yll)
predll=set(predll)
eps=0.000001
precision = len(yll & predll) / float(eps + len(predll))
recall =len(yll&predll)/float(eps+len(yll))
f1=precision*2*recall/(precision+recall+eps)
return precision,recall,f1
f='output.pkl'
rst=pdd.read_pickle(f)
print ('')
xll_predll,yll=rst
xll,predll=xll_predll
precisionll,recalll,f1ll=[],[],[]
for x1,pred1,y1 in zip(xll,predll,yll):
print ('')
#############
# 找出所有 关系 评估
## 先找到 trigger root
root=None
rootpos=None
for wid,pred in enumerate(pred1):
word=x1[wid]
if pred=='trigger':
root=word
rootpos=wid
break
##### 预测的
pred_pair_ll = []
for wid,pred in enumerate(pred1):
if pred=='trigger':continue
if pred!='unlabel':
l=make_pair(root,rootpos,x1[wid],wid,pred)
pred_pair_ll.append(l)
####### 标注的
label_pair_ll=[]
for wid,y in enumerate(y1):
if y=='trigger':continue
if y!='unlabel':
l=make_pair(root,rootpos,x1[wid],wid,y)
label_pair_ll.append(l)
precision,recall,f1=calc_precision_recall_f1(label_pair_ll,pred_pair_ll)
precisionll.append(precision)
recalll.append(recall)
f1ll.append(f1)
####
print (np.mean(precisionll),np.mean(recalll),np.mean(f1ll))
<file_sep># financial_event 使用 t2t transformer_l2
依赖
tensor2tensor==1.15.4
生成数据 t2t_data_gen.py
训练 t2t_trainer_yr.py
预测 t2t_decoder_test_v04.py
event extraction
原始数据1条 :2018年 实 现 总资产 81万元 , 总负债 45万元 。
p(arg|text ,trigger) 给定的trigger预测arguments
1,第一个样本要预测的关系 {trigger:总资产,arguments:{ arg1:81万元 , 关系:value }; {arg2:time , 关系:time} #arg =argument
```input :TIME , 实 现 triggerRoot mEntity , trigger mEntity 。```
```y: time u u u trigger value u u u u ```#u=unlabel
2,第二个样本要预测的关系 {trigger:总负债,arguments:{ arg1:45万元 , 关系:value }; {arg2:time , 关系:time}
```input :TIME , 实 现 trigger mEntity , triggerRoot mEntity 。```
```y : time u u u u u u trigger value u```
# 评估标准
事件评估基本单位 [head, head-position, tail,tail-position, relation]
例如:
[总资产 3 81万元 4 value]
[总资产 3 2018年 0 time]
当然数据泛化后,具体数值变成mEntity,具体资产 负债变成trigger 之后 trainset devset会有交集 所以评估去掉交集的结果如下:
```
precision=0.93
recall=0.94
f1-score=0.93
```
去重策略为如下是否重复
例如:'其 中 trigger 占 比 最 大 TIME trigger 占 trigger 比 重 分 别 为 m 、 m 、 m 和 m 。'
<file_sep>####################
# 给定 trigger 预测 这个trigger的属性 subject time value ratio..
## 原始句子 company time trigger1 m m m, org time trigger2 m m m
## 想分别预测 trigger1 的相关 attribute:company time m m m ,
# trigger2和相关的属性 都作为unlabel
## 输入 company time triggerRoot m m m, org time trigger m m m
## 输出 subject time trigger value value value unlabel unlabel unlabel unlabel unlabel unlabel
# 原始数据1条 :2018年实现总资产81万元,总负债45万元
# 第一个样本要预测的关系[trigger:总资产 argument1:81万元 关系:value ; arg2:time 关系:time]
# TIME , 实 现 triggerRoot mEntity , trigger mEntity 。
# 第二个样本要预测的关系 [trigger:总负债 argument 45万元 关系value;arg2:time 关系:time]
# TIME , 实 现 trigger mEntity , triggerRoot mEntity 。
import json
import re
import sys
import os
import copy
import numpy as np
lenll=[]
p_num=re.compile('\d+')
event_mention_typ={'m','TIME','trigger','WithIn','company','ORG'}
## trigger time 没有other
def remove_num(w):# ratio3->ratio
return p_num.sub('',w)
def replace_num(line):
line=p_num.sub('m',line)
return line
def number_the_triggers(wordll):
cnt=0
ret=[]
for idx,w in enumerate(wordll):
if w=='trigger':
w=w+str(cnt)
cnt+=1
ret.append(w)
###
else:ret.append(w)
return ret
def run(reader,writer):
global vocaby,vocabx,lenll
for line in reader.readlines():
#### 每个句子
line = line.strip()
lab, d = line.split('\t')
d = json.loads(d)
#print('')
### get rawsent
wordll = [w['typ'] if w['typ'] in event_mention_typ else w['val'] for w in d['words']]
wordll=['mEntity' if w=='m' else w for w in wordll]
### trigger ->trigger1 trigger2
#wordll = number_the_triggers(wordll)
whether_event_mention = [True if w['typ'] in event_mention_typ else False for w in d['words']]
### event
for event in d['events']:
## 每个事件 一个ROOT 多个attribute
this_event_y = ['unlabel'] * len(wordll)
if 'trigger' not in event:continue
rootPos = event['trigger']
this_event_y[rootPos] = 'trigger'
for rela, attPos in event.items():
if rela=='trigger':continue
this_event_y[attPos] = rela
###
#print('')
### combine x y -> [{x:x,y:y},{},,,]
xydictll = [{'w': w, 'y': y, 'eventflag': flag} for w, y, flag in
zip(wordll, this_event_y, whether_event_mention)]
#### 一个句子多个TRIGGER 时候 把其中ROOT 的trigger ->trigger_root
xydictll[rootPos]['w']='triggerRoot'
#print('')
#############
# word -> char
charll = []
for dic in xydictll:
if dic['eventflag'] == False: # 只把不是EVENT MENTION的单词拆成字
for char in dic['w']:
charll.append({'char': char, 'y': 'unlabel'})
else:
charll.append({'char': dic['w'], 'y': dic['y']})
#### ###
# p(attribute|trigger-root)
##### ratio4->ratio
charll1=copy.deepcopy(charll)
for wdic in charll:
wdic['y']=remove_num(wdic['y'])
writer.write(json.dumps(charll, ensure_ascii=False) + '\n')
######字典
for char in charll:
vocabx.add(char['char'])
vocaby.add(char['y'])
###### length
lenll.append(len(charll))
f='./trigger.train'
writer=open('train.json','w')
vocabx,vocaby=set(),set()
reader=open(f)
run(reader,writer)
#########
# test
f = './trigger.dev'
writer = open('test.json', 'w')
reader = open(f)
run(reader, writer)
######## xvocab
writerv=open('vocabx.txt','w')
writerv.write('PAD\n')
writerv.write('EOS\n')
writerv.write('UNK\n')
for w in vocabx:
writerv.write(w+'\n')
writerv=open('vocaby.txt','w')
writerv.write('PAD\n')
writerv.write('EOS\n')
writerv.write('UNK\n')
for w in vocaby:
writerv.write(w+'\n')
print (np.histogram(lenll))
# (array([29374, 8635, 2215, 887, 584, 140, 65, 140, 20,10]),
# array([ 6. , 36.7, 67.4, 98.1, 128.8, 159.5, 190.2, 220.9, 251.6, 282.3, 313. ]))
<file_sep>from . import problem_seq2seq
|
22c1252fd83436212ac513071f6e124ecac799d8
|
[
"Markdown",
"Python",
"Shell"
] | 6
|
Python
|
2877992943/financialReport_event
|
655c0c57d06e8599bb939721456bf1159e6fbe6c
|
0eb4ee982dd857535d2a0c120c111e8afa2009f3
|
refs/heads/master
|
<repo_name>sjameson-jhcs/classes<file_sep>/app.py
# *********************************
# ****** SECTION 1 - CLASSES ******
# *********************************
# A "Class" is like a blueprint for an object
# Objects can be many different things
# In a grade tracking program objects might be: Course, Period, Teacher, Student, Gradable Assignment, Comment, Etc.
# In Mario objects might be: Mario, Level, Enemy, Power Up (like star or mushroom), Hittable Block, Etc.
# In banking software objects might be: Customer, Account, Deposit, Withdrawal, Etc.
# Note: Classes are normally named with capital letters with no spaces. But that is not required, just recommended.
class UnknownStudent:
name = "Unknown"
age = "Unknown"
# Now that the blueprint exists we can create an INSTANCE of the class
first_student = UnknownStudent()
first_student.name = "<NAME>"
first_student.age = 15
print(f"The student's name is {first_student.name} and he is {first_student.age} years old.")
# ********************************************
# ****** SECTION 2 - CONSTRUCTOR METHOD ******
# ********************************************
# A method is what we call a function that belongs to a class.
# A CONSTRUCTOR method runs when a new instance is created.
# The purpose of a constructor is to setup any initial values for a new instance.
# A constructor in python uses the name: __init__
# NOTE: It is considered good practice to always have a constructor even if it does nothing.
class Student:
# NOTE: For constructor input parameters I like to start them with an underscore.
def __init__(self, _name, _age):
self.name = _name
self.age = _age
# second_student = Student(_name="Jane", _age="Doe")
# print(f"The student's name is {second_student.name} and her age is {second_student.age}.")
# ***************************************
# ****** SECTION 3 - OTHER METHODS ******
# ***************************************
# A class can (and usually does) have other methods besides the constructor
class Dog:
def __init__(self, _name, _breed, _color):
self.name = _name
self.breed = _breed
self.color = _color
self.position = 0
def run(self, distance=1):
self.position += distance
print(f"{self.name} ran {distance} meters and is now at position {self.position}.")
def bark(self):
if self.breed == "Lab":
print("Woof")
elif self.breed == "Terrier":
print("Yap")
else:
print("Bark")
def get_color(self):
return self.color
# my_dog = Dog(_name="Ellie", _breed="Lab", _color="Yellow")
# my_dog.run(5)
# my_dog.run(-2)
# my_dog.bark()
# print(f"My dog is {my_dog.color}.")
# *************************************
# ****** SECTION 3 - INHERITANCE ******
# *************************************
# For the sake of organization it is often useful to have one class inherit another.
# Usually the parent class is something generic and the child is one type of the parent class
class Animal:
def __init__(self):
self.position = 0
self.speed = 0
self.noise = "[silence]"
def run(self):
self.position += self.speed
print(f"The animal ran {self.speed} meters and is now at position {self.position}.")
def make_noise(self):
print(self.noise)
class Jaguar(Animal):
def __init__(self):
self.position = 0
self.speed = 10
self.noise = "growwwl"
class Horse(Animal):
def __init__(self):
self.position = 0
self.speed = 8
self.noise = "neigggh"
class Snake(Animal):
def __init__(self):
self.position = 0
self.speed = 1
self.noise = "hssss"
def run(self):
self.position += self.speed
print(f"The snake slithered {self.speed} meters and is now at position {self.position}.")
# jax = Jaguar()
# jax.run()
# jax.make_noise()
#
# harvey = Horse()
# harvey.run()
# harvey.make_noise()
#
# steve = Snake()
# steve.run()
# steve.make_noise()
# ******************************************************
# ****** SECTION 4 - S.O.L.I.D. DESIGN PRINCIPLES ******
# ******************************************************
# S.O.L.I.D is an acronym. If we follow the 5 recommendations our code
# will be easier to modify and maintain in the future
# S - Single Responsibility: Classes should have a singular purpose. If you try to do everything in onc class it
# gets cluttered and difficult to maintain.
# O - Open for extension, Closed for modification: A class should be able to be added onto at a later time,
# In general it should be generic enough that future situations don't cause you to
# change existing code in the class.
# L - Liskov Substitution: Any inherited class should be substitutable with its parent class. In our example above
# a Horse should be able to do whatever an Animal can do.
# I - Interface Segregation: This one basically says that if a child class doesn't fit in the parent class then
# make a new parent class. (For example if I wanted an animal like snail it might need
# its own parent class becuase it doesn't make noise and it doesnt really run).
# D - Dependency Inversion: Means that child classes can (and should) depend on their parent classes to define
# Their behavior. But a parent should never be dependent on a child class. For example,
# an Animal should not have any of their behavior defined by a snake because snake is
# an Animal. You could have a jaguar react to a snake, but not a generic Animal.
<file_sep>/challenge.py
# For this challenge I am NOT expecting your code to do anything when it runs.
# Instead your final submission will just be a series of classes that are never instantiated.
# I want to see that you can think about objects and what parameters are necessary to use them in code.
# The goal is to create a class for every object that would be necessary to build a game of MONOPOLY
# If you have not played Monopoly (the board game) feel free to ask me or just google it
# I'll start you with one example. Please note that I do not need to you to define the logic in each method
# but it would be nice if you at least give method names like I have in the example
class Player:
def __init__(self, _token):
self.money = 1500
self.token = _token
self.properties_owned = {}
self.current_location = "GO"
self.get_out_of_jail_cards_owned = 0
def pay_money(self):
pass # Notice I am not defining the logic of what these methods do. You do not need to either.
# The keyword "pass" just means it will not do anyting yet
def get_money(self):
pass
def buy_property(self):
pass
def mortgage_property(self):
pass
def pay_mortgage_on_property(self):
pass
def roll_dice(self):
pass
|
9b57849f1caf75ebc3d447c68f447671a45d756c
|
[
"Python"
] | 2
|
Python
|
sjameson-jhcs/classes
|
91c6e786d05b0288c5cf54e62befd204224c67a5
|
48f9d06f5ef2e49c71d3bbd676c21033219269e5
|
refs/heads/master
|
<repo_name>EdwardKinley/CC_w15_d2_music_homework<file_sep>/src/components/SongDetail.js
import React from 'react';
const SongDetail = function(props) {
return (
<tr className="table-row">
<td>#{props.position}</td>
<td><a href={props.previewLink} target="_blank"><img src={props.image} alt={props.title} /></a></td>
<td><a href={props.previewLink} target="_blank">{props.title}</a></td>
<td><a href={props.artistLink} target="_blank">{props.artist}</a></td>
<td>{props.price}</td>
</tr>
);
}
export default SongDetail;
<file_sep>/src/components/SongList.js
import React from 'react';
import SongDetail from './SongDetail.js';
class SongList extends React.Component {
render() {
const songComponents = this.props.songs.map((entry) => {
return (<SongDetail
position={this.props.songs.indexOf(entry)+1}
image={entry["im:image"][2].label}
previewLink={entry.link[1].attributes.href}
title={entry["im:name"].label}
artist={entry["im:artist"].label}
artistLink={entry["im:artist"].attributes.href}
price={entry["im:price"].label}
/>);
});
return (
<tbody>
{songComponents}
</tbody>
);
}
}
export default SongList;
|
d0a889e61bfa173556df2f8ff785a8ffa0c42959
|
[
"JavaScript"
] | 2
|
JavaScript
|
EdwardKinley/CC_w15_d2_music_homework
|
417ff150b04c8850738ae921ec966e7f51cf53d8
|
b5fd7e1fc6450e0480cb348e4fd8896eabd78b85
|
refs/heads/master
|
<file_sep>from dasg.DASG import DirectedAcyclicSequenceGraph
<file_sep>from pathlib import Path
from time import time
from typing import List, Hashable
class _DirectedAcyclicSequenceGraphNode:
def __init__(self, node_id):
"""
Represents a node in a DASG.
Contains an ID, a flag indicating whether the node is a leaf and a set of children.
:param int node_id: ID of node.
"""
# Assign ID and update class-counter
self.id = node_id
# Initialize
self.is_sequence_end = False
self.children = {}
def subtree_identity(self):
"""
Makes an immutable object representing the node, which can be used for comparing two
nodes for equal subtrees (all children are identical).
:return: str, str, str
"""
if self.children:
temp = [(str(edge), str(node.id), "1" if node.is_sequence_end else "0")
for (edge, node) in self.children.items()]
edge_string, id_string, status_string = \
zip(*temp)
else:
edge_string = id_string = status_string = ""
# Join with underscores
edge_string = "r_" + "_".join(edge_string)
id_string = "r_" + "_".join(id_string)
status_string = ("1_" if self.is_sequence_end else "0_") + "_".join(status_string)
return edge_string, id_string, status_string
def __hash__(self):
return self.subtree_identity().__hash__()
def __eq__(self, other):
return self.subtree_identity() == other.subtree_identity()
class _Check:
def __init__(self, node, element, next_node):
self.next_node = next_node
self.element = element
self.node = node
def __iter__(self):
return (item for item in (self.node, self.element, self.next_node))
class DirectedAcyclicSequenceGraph:
def __init__(self, sequences=None, verbose=False):
"""
Encodes a list of sequences into a Directed Acyclic Graph.
Can look up sequences with:
query in dasg
Can search for sequences related to query by editdistance:
dasg.edit_distance_search(query, max_cost=2)
:param list sequences: List of sequences.
:param bool verbose: Want prints?
"""
self._previous_sequence = None
self._sequence_count = 0
self._height = 0
self._next_id = 0
self._sequence_type = None
# Initialize root node
self._root = self._build_node()
# List of future checks for merging nodes with identical subtrees.
self._checks_to_do = [] # type: [_Check]
# Nodes in DASG.
self._nodes = {}
# Initialize if sequences are given
if sequences is not None:
self._build(sequences, verbose=verbose)
def __contains__(self, sequence):
# Start at root
node = self._root
# Go through elements
for element in sequence:
# If element is not found after current prefix return false
if element not in node.children:
return False
# Next element
node = node.children[element]
# Return sequence-end-status of node
return node.is_sequence_end
def __iter__(self):
# Search queue
search_nodes = [(0, edge, child) for edge, child in self._root.children.items()]
# search_nodes.sort()
search_nodes.reverse()
# Current position
current_sequence = []
# Go through queue
while search_nodes:
node_height, edge, node = search_nodes.pop()
# Check length of current sequence
current_sequence = current_sequence[:node_height] # type: list
# Add new element
current_sequence.append(edge)
# Check if node is end of sequence
if node.is_sequence_end:
yield self._convert_output(current_sequence)
# Add children
additions = [(node_height + 1, edge, child) for edge, child in node.children.items()]
# additions.sort()
additions.reverse()
search_nodes.extend(additions)
@property
def node_count(self):
return len(self._nodes)
@property
def edge_count(self):
count = 0
for node in self._nodes:
count += len(node.children)
return count
@property
def sequence_count(self):
return self._sequence_count
@property
def height(self):
return self._height
@staticmethod
def _common_prefix(sequence1, sequence2):
"""
Reports the length of the longest common prefix of two sequences.
:return: int
"""
i = 0
for elem1, elem2 in zip(sequence1, sequence2):
if elem1 != elem2:
return i
i += 1
# Return length of sequence if sequences are identical
return min(len(sequence1), len(sequence2))
def _build_node(self):
"""
Build a new node with a new ID.
:return: _DirectedAcyclicSequenceGraphNode
"""
self._next_id += 1
return _DirectedAcyclicSequenceGraphNode(self._next_id - 1)
def _build(self, sequences, verbose=False):
"""
Build DASG with a list of sequences.
:param list sequences:
:param bool verbose: Want prints?
"""
if verbose:
print(f"Creating {type(self).__name__}...")
# Type
self._sequence_type = type(sequences[0])
# Check if hashable
if not isinstance(sequences[0], Hashable):
sequences = [tuple(val) for val in sequences]
# Make sure sequences are list-type and sorted
sequences = sorted(list(set(sequences)))
# Insert all sequences
i = 0
start = time()
for sequence in sequences:
i += 1
self._insert(sequence)
self._finish()
if verbose:
print(
f"Creation of {type(self).__name__} with {self._sequence_count} sequences "
f"took {time() - start:.3f}s.\n")
def _insert(self, sequence):
if self._previous_sequence is not None:
# Check sequence-order consistency
if sequence < self._previous_sequence:
raise ValueError(f"{type(self).__name__}: Sequences must be ordered (comparable). "
f"{type(sequence).__name__} and {type(self._previous_sequence).__name__} are not")
# Find common prefix between sequence and previous sequence
common_prefix = self._common_prefix(sequence, self._previous_sequence)
else:
common_prefix = 0
# Reduce by merging nodes with equal subtrees
self._minimize(common_prefix)
# Add the suffix, starting from the correct node mid-way through the graph
if len(self._checks_to_do) == 0:
node = self._root
else:
node = self._checks_to_do[-1].next_node
# Go through elements after the common prefix
for element in sequence[common_prefix:]:
# Make new node
next_node = self._build_node()
# Create edge between nodes with element as identifier
node.children[element] = next_node
# Add unchecked node
self._checks_to_do.append(_Check(node, element, next_node))
# Move to next node
node = next_node
# Note that this node represents the end of a sequence
node.is_sequence_end = True
# Remember sequence for next insertion
self._previous_sequence = sequence
# Increment counter
self._sequence_count += 1
# Note longest sequence
self._height = max(self._height, len(sequence))
def _finish(self):
# Minimize all
self._minimize()
def _minimize(self, up_to=0):
"""
Check the unchecked_nodes for redundant nodes, proceeding from last one down to the common
prefix size. Then truncate the list at that point.
:param int up_to: Upper limit in height for minimization.
"""
# Split checks into those below upper-limit and those below
self._checks_to_do, checks_below = self._checks_to_do[:up_to], self._checks_to_do[up_to:]
# Handle checks below from bottom and up
for parent, element, child in reversed(checks_below):
# Check if there exists a minimized node identical to child (identical subtree)
if child in self._nodes:
# Replace child with minimized node
parent.children[element] = self._nodes[child]
else:
# Add chile to minimized nodes for later usage
self._nodes[child] = child
#########
# Searching
def _convert_output(self, current_elements):
if self._sequence_type == str:
return "".join(current_elements)
elif self._sequence_type == list or self._sequence_type == tuple:
return self._sequence_type(current_elements)
else:
NotImplementedError(f"Conversion from output type {type(current_elements).__name__} to "
f"{self._sequence_type} not implemented.")
def edit_distance_search(self, query_sequence, max_cost=1, sort=False, exclude_query=False,
exclusions=None):
"""
Searches for all sequences that have an edit-distance of at most "max_cost" from "query_sequence".
:param str | list | tuple query_sequence: The query sequence.
:param int max_cost: Maximum accepted edit-cost for search.
:param bool sort: If True, the output will be sorted with respect to the distance measure.
:param bool exclude_query: Don't output query_sequence as result.
:param set | list exclusions: Sequences to ignore.
:return: list[str]
"""
# Check for simple search
if max_cost == 0:
if query_sequence in self:
return [(query_sequence, 0)]
else:
return []
# Root node
root = self._root
# Build first row of dynamic cost-table
current_row = list(range(len(query_sequence) + 1))
# List of search-results
results = []
# Recursively search each branch of the trie
for element in root.children.keys():
child_results = self._edit_distance_search_recursion(node=root.children[element],
parent_elements=[],
current_element=element,
query_sequence=query_sequence,
previous_row=current_row,
max_cost=max_cost)
# Extend results
results.extend(child_results)
# Sort if needed
if sort:
results = sorted(results, key=lambda x: x[1])
# Attempt using set for quicker lookup
if exclusions is not None:
try:
exclusions = set(exclusions)
except TypeError:
pass
# Add query sequence to exclusions if wanted
if exclude_query:
if isinstance(exclusions, set):
exclusions.update(query_sequence)
elif isinstance(exclusions, list):
exclusions.append(query_sequence)
elif exclusions is None:
exclusions = [query_sequence]
else:
raise TypeError("Filtering of query-sequence not possible. ")
# Filter sequences
if exclusions is not None:
results = [sequence for sequence in results if sequence[0] not in exclusions]
# Return
return results
def _edit_distance_search_recursion(self, node, parent_elements, current_element, query_sequence,
previous_row, max_cost):
"""
Recursively searches for sequences that have an edit-distance of at most "max_cost" from "query_sequence".
:param _DirectedAcyclicSequenceGraphNode node: The current node in the search.
:param list parent_elements: The elements of parent sequence.
:param current_element: The element leading to this node.
:param str | list | tuple query_sequence: The query sequence.
:param list[int] previous_row: Previous row in dynamic cost-table.
:param int max_cost: Maximum accepted edit-cost for search.
"""
# Number of columns
columns = len(query_sequence) + 1
# Initialize current row
current_row = [None] * columns # type: List[int]
current_row[0] = previous_row[0] + 1
# Current elements
current_elements = parent_elements + [current_element]
# Build one row for the element, with a column for each element in the target
# sequence, plus one for the empty element at column 0
for column in range(1, columns):
# Current node can be reached from prefix by force-inserting the correct element
# The cost after this insertion
insert_cost = current_row[column - 1] + 1
# Current node can be reached by deleting the next search element.
# The cost after deletion is the current cost plus 1
delete_cost = previous_row[column] + 1
# Assuming neither deletion nor insertion, the current cost is
replace_cost = previous_row[column - 1]
if query_sequence[column - 1] != current_element:
replace_cost += 1
# Append the minimum value to the row
current_row[column] = min(insert_cost, delete_cost, replace_cost)
# Check if cost is acceptable and if node marks end of sequence
results = []
if current_row[-1] <= max_cost and node.is_sequence_end:
# Append result
sequence = self._convert_output(current_elements=current_elements)
results.append((sequence, current_row[-1]))
# Check if any cost in row is acceptable
if min(current_row) <= max_cost:
# Go through all children and search recursively
for child_element in node.children:
child_results = self._edit_distance_search_recursion(node=node.children[child_element],
parent_elements=current_elements,
current_element=child_element,
query_sequence=query_sequence,
previous_row=current_row,
max_cost=max_cost)
# Extend results
results.extend(child_results)
# Return
return results
<file_sep>from pathlib import Path
from dasg import DirectedAcyclicSequenceGraph
line = "-" * 75
#############################
# Non-string sequences
print("\n\n" + line)
print("Testing sequences of integers. ")
the_sequences = [list(range(idx, idx + 5)) for idx in range(10)]
the_dasg = DirectedAcyclicSequenceGraph(the_sequences)
query = list(range(6, 6 + 5))
if query in the_dasg:
print(f"\n'{query}' is in the DASG.")
else:
print(f"\n'{query}' not in DASG.")
print(f"\nSequences closest to '{query}':")
print(the_dasg.edit_distance_search(query_sequence=query, max_cost=2, sort=True, exclude_query=True))
print("\nPrint out of all sequences in DASG:")
for sequence in the_dasg:
print("\t", sequence)
#############################
# Text-file
print("\n\n" + line)
print("Analysing text-file.\n")
# Get test-text
text = "\n".join([line for line in Path("text.txt").open("r")])
# Words and query
all_words = text.split()
query = "pass"
# Make DASG
the_dasg = DirectedAcyclicSequenceGraph(all_words, verbose=True)
for word in all_words:
if word not in the_dasg:
print(f"'{word}' not in DASG")
# Print success
print(f"Read {the_dasg.sequence_count} words into {the_dasg.node_count} nodes and {the_dasg.edge_count} edges")
# Check if is in DASG
if query in the_dasg:
print(f"\n'{query}' is in the DASG.")
else:
print(f"\n'{query}' not in DASG.")
query = "chill"
print(f"\nWords closest to '{query}':")
print(the_dasg.edit_distance_search(query_sequence=query, max_cost=2, sort=True))
<file_sep># Directed Acyclic Sequence Graph
Implements a DAG which can be used for querying a set sequences.
After creating a graph for a set of sentences the class can quickly look up
existence and search for sequences using edit-distance measure.
Also called a Directed Acyclic Word Graph (although this implementation is not restricted to strings)
or a Deterministic Acyclic Finite State Automaton.
### Basic usage
The DASG has its advantage when working with large sets of sequences where one wants to query for related sequences
using edit-distance. The system is used as follows:
```Python
# 'the_sequences' is a list of sequences.
# 'query' is a single sequence.
the_dasg = DirectedAcyclicSequenceGraph(the_sequences)
related_sequences = the_dasg.edit_distance_search(query_sequence=query, max_cost=2, sort=True)
```
### Visual Example
<img src="https://github.com/North-Guard/dasg/blob/master/dasg.png" width="300">
### Comparison with `editdistance`
`editdistance` is a Python-library which can compute edit-distance between strings fairly fast.
Using this library to search for related sequences requires computing the distance from the query to all other
sequences, which scales linearly. A DASG can perform this search faster by travelling a graph. This search
has logarithmic complexity for exact search but has larger complexity when the edit-distance is set to higher values.
Below is a comparison of using a set to hold ones vocabulary and using `editdistance` to find similar words vs.
using a DASG. The setup is built on a quite large txt-file (1.1GB). The DASG is fastest if
more that about 10 queries are to be made (due to build time).
```
Analysing text-file.
---------------------------------------------------------------------------
DASG
Creating DirectedAcyclicSequenceGraph...
Creation of DirectedAcyclicSequenceGraph with 2712289 sequences took 159.042s.
Read 2712289 words into 1459827 nodes and 3243435 edges
'pass' is in the DASG.
Words closest to 'chill':
[('chill', 0), ('"hill', 1), ("'chill", 1), ("'hill", 1), ('Chill', 1), ('Schill', 1), ('Whill', 1), ('chiel', 1), ('child', 1), ('chile', 1), ('chili', 1), ('chill!', 1), ('chill"', 1), ("chill'", 1), ('chill)', 1), ('chill,', 1), ('chill.', 1), ('chill:', 1), ('chill;', 1), ('chill?', 1), ('chill_', 1), ('chills', 1), ('chilly', 1), ('chilt', 1), ('hill', 1), ('shill', 1), ('thill', 1), ('whill', 1), ('"Bill', 2), ('"Chill', 2), ('"Fill', 2), ('"Gill', 2), ('"Hill', 2), ('"Jill', 2), ('"Kill', 2), ('"Lill', 2), ('"Mill', 2), ('"Nill', 2), ('"Pill', 2), ('"Till', 2), ('"Vill', 2), ('"Will', 2), ('"_ill', 2), ('"bill', 2), ('"chil"', 2), ('"child', 2), ('"chill"', 2), ('"fill', 2), ('"hall', 2), ('"hell', 2), ('"hills', 2), ('"ill', 2), ('"kill', 2), ('"till', 2), ('"vill', 2), ('"will', 2), ("'Bill", 2), ("'Chill", 2), ("'Fill", 2), ("'Gill", 2), ("'Hill", 2), ("'Kill", 2), ("'Mill", 2), ("'Till", 2), ("'Will", 2), ("'bill", 2), ("'child", 2), ("'chill'", 2), ("'fill", 2), ("'haill", 2), ("'hall", 2), ("'hell", 2), ("'ill", 2), ("'kill", 2), ("'till", 2), ("'will", 2), ('(Bill', 2), ('(Hill', 2), ('(Kill', 2), ('(Mill', 2), ('(Till', 2), ('(Will', 2), ('(bill', 2), ('(child', 2), ('(ill', 2), ('(kill', 2), ('(till', 2), ('(will', 2), ('-Will', 2), ('-ill', 2), ('-will', 2), ('Achill.', 2), ('Achille', 2), ("Ah'll", 2), ('Aill', 2), ('Athill', 2), ('Bhil', 2), ('Bhil,', 2), ('Bhil.', 2), ('Bhil;', 2), ('Bhils', 2), ('Bill', 2), ('Brill', 2), ('Chil', 2), ('Chil!', 2), ('Chil,', 2), ('Child', 2), ('Chile', 2), ('Chili', 2), ('Chill,', 2), ('Chills', 2), ('Chilly', 2), ('Chilo', 2), ('Dill', 2), ('Drill', 2), ('Duill', 2), ('Fill', 2), ('Frill', 2), ('Ghyll', 2), ('Gill', 2), ('Grill', 2), ('Hill', 2), ('Ichil', 2), ('Jhil', 2), ('Jhil.', 2), ('Jill', 2), ('Khil;', 2), ('Kill', 2), ('Lill', 2), ('McGill', 2), ('Mill', 2), ('Mohill', 2), ('Neill', 2), ('Nihill', 2), ('Nill', 2), ('Ochil', 2), ('Ochils', 2), ('Phial', 2), ('Phil', 2), ('Phil!', 2), ('Phil,', 2), ('Phil.', 2), ('Phil:', 2), ('Phil;', 2), ('Phil?', 2), ('Phile', 2), ('Philly', 2), ('Philo', 2), ('Philp', 2), ('Pill', 2), ('Quhill', 2), ('Quill', 2), ('Rill', 2), ('STill', 2), ('Schall', 2), ('Schill!', 2), ('Schill,', 2), ('Scholl', 2), ('Shall', 2), ('Shell', 2), ('Shiel', 2), ('Shill,', 2), ('Shrill', 2), ('Sill', 2), ('Skill', 2), ('Spill', 2), ('Still', 2), ('Swill', 2), ('Thall', 2), ('Thrill', 2), ('Thull', 2), ('Till', 2), ('Twill', 2), ('Uphill', 2), ('Vill', 2), ('Weill', 2), ('While', 2), ('Whilk', 2), ('Whirl', 2), ('Will', 2), ('Yuill', 2), ('Zhall', 2), ('[Bill', 2), ('[Till', 2), ('[Will', 2), ('[hills', 2), ('[till', 2), ('[will', 2), ('_Bill', 2), ('_Chill', 2), ('_Hill', 2), ('_Jill', 2), ('_Mill', 2), ('_Rill', 2), ('_Till', 2), ('_Will', 2), ('_bill', 2), ('_chili', 2), ('_chill_', 2), ('_hill_', 2), ('_ill', 2), ('_kill', 2), ('_till', 2), ('_will', 2), ('`fill', 2), ('`will', 2), ("ah'll", 2), ('baill', 2), ('bill', 2), ('caill,', 2), ('caill.', 2), ('call', 2), ('ceil', 2), ('cell', 2), ("ch'al", 2), ('chail', 2), ('chail.', 2), ('chaille', 2), ('chal', 2), ('chale', 2), ('chalk', 2), ('chals', 2), ('chawl', 2), ("che'l", 2), ('cheild', 2), ('cheils', 2), ('chel', 2), ('chela', 2), ('chi', 2), ("chi'", 2), ('chi,', 2), ('chi-', 2), ('chic', 2), ('chic!', 2), ('chic)', 2), ('chic,', 2), ('chic.', 2), ('chic;', 2), ('chic?', 2), ('chica', 2), ('chice', 2), ('chick', 2), ('chid', 2), ('chid!', 2), ('chid,', 2), ('chid.', 2), ('chid;', 2), ('chide', 2), ('chief', 2), ('chiel!', 2), ('chiel"', 2), ("chiel'", 2), ('chiel,', 2), ('chiel.', 2), ('chiel;', 2), ('chield', 2), ('chiels', 2), ('chien', 2), ('chiep', 2), ("chil'd", 2), ('child!', 2), ('child"', 2), ("child'", 2), ('child)', 2), ('child,', 2), ('child-', 2), ('child.', 2), ('child:', 2), ('child;', 2), ('child?', 2), ('child]', 2), ('child_', 2), ('childe', 2), ('childly', 2), ('childs', 2), ('chile!', 2), ('chile,', 2), ('chile.', 2), ('chile;', 2), ('chile?', 2), ('chilen', 2), ('chiles', 2), ('chilis', 2), ('chill!"', 2), ("chill!'", 2), ('chill";', 2), ("chill'd", 2), ("chill's", 2), ('chill),', 2), ('chill,"', 2), ("chill,'", 2), ('chill--', 2), ('chill."', 2), ("chill.'", 2), ('chill.]', 2), ('chill._', 2), ('chill?"', 2), ("chill?'", 2), ('chilled', 2), ('chillen', 2), ('chiller', 2), ('chills!', 2), ('chills,', 2), ('chills.', 2), ('chills:', 2), ('chills;', 2), ('chills?', 2), ('chillum', 2), ('chillun', 2), ('chilly!', 2), ('chilly,', 2), ('chilly.', 2), ('chilly:', 2), ('chilly;', 2), ('chilly?', 2), ('chilt,', 2), ('chime', 2), ('chimla', 2), ('chimly', 2), ('chin', 2), ('chin!', 2), ('chin)', 2), ('chin,', 2), ('chin-', 2), ('chin.', 2), ('chin:', 2), ('chin;', 2), ('chin?', 2), ('chin]', 2), ('china', 2), ('chine', 2), ('ching', 2), ('chink', 2), ('chins', 2), ('chiny', 2), ('chip', 2), ('chip!', 2), ('chip,', 2), ('chip.', 2), ('chip;', 2), ('chip?', 2), ('chips', 2), ('chirk', 2), ('chirp', 2), ('chirr', 2), ('chise', 2), ('chisel', 2), ('chist', 2), ('chit', 2), ('chit!', 2), ('chit)', 2), ('chit,', 2), ('chit-', 2), ('chit.', 2), ('chit;', 2), ('chit?', 2), ('chits', 2), ('chiv', 2), ('chive', 2), ('chivy', 2), ('choilt', 2), ('cholla', 2), ('choly', 2), ('chowl', 2), ('churl', 2), ('chyle', 2), ('ciel', 2), ('cil', 2), ('cirl', 2), ('coil', 2), ('coil!', 2), ('coil,', 2), ('coil.', 2), ('coil:', 2), ('coil;', 2), ('coil?', 2), ('coils', 2), ('coll', 2), ('cull', 2), ('dholl', 2), ('dhrill', 2), ('dill', 2), ('drill', 2), ('ehall', 2), ('evill', 2), ('ewill', 2), ('fill', 2), ('frill', 2), ('ghila', 2), ('ghyll', 2), ('gill', 2), ('grill', 2), ('h-ll', 2), ('haill', 2), ('hall', 2), ('hell', 2), ("hi'll", 2), ('hil', 2), ('hil,', 2), ('hild', 2), ('hile', 2), ('hill!', 2), ('hill"', 2), ("hill'", 2), ('hill)', 2), ('hill,', 2), ('hill-', 2), ('hill.', 2), ('hill:', 2), ('hill;', 2), ('hill?', 2), ('hill]', 2), ('hills', 2), ('hilly', 2), ('hilp', 2), ('hilt', 2), ('holl', 2), ('hull', 2), ('ill', 2), ('jhil,', 2), ('jhils', 2), ('kill', 2), ('leill', 2), ('lill', 2), ('mill', 2), ('nill', 2), ('phial', 2), ('pill', 2), ('quhill', 2), ('quill', 2), ('rill', 2), ('schall', 2), ("sh'll", 2), ('shall', 2), ('shell', 2), ('shiel', 2), ('shild', 2), ('shill,', 2), ('shill:', 2), ('shill;', 2), ('shilly', 2), ('shily', 2), ('shll', 2), ('sholl', 2), ('shrill', 2), ('shtill', 2), ('shull', 2), ('sill', 2), ('skill', 2), ('spill', 2), ('still', 2), ('swill', 2), ('taill', 2), ('thall', 2), ('thell', 2), ('thilk', 2), ('thill,', 2), ('thrill', 2), ('thtill', 2), ('till', 2), ('toill', 2), ('trill', 2), ('twill', 2), ('uphill', 2), ('vhile', 2), ('vill', 2), ('weill', 2), ('while', 2), ('whilk', 2), ('whilly', 2), ('whirl', 2), ('whull', 2), ('will', 2), ('wrill', 2), ('yill', 2), ('zhall', 2), ('{will', 2)]
Querying of DASG: 0.351s
---------------------------------------------------------------------------
Set and editdistance
Creating vocabulary set
'pass' is in the vocabulary set.
Words closest to 'chill':
[('chill', 0), ('"hill', 1), ("'chill", 1), ("'hill", 1), ('Chill', 1), ('Schill', 1), ('Whill', 1), ('chiel', 1), ('child', 1), ('chile', 1), ('chili', 1), ('chill!', 1), ('chill"', 1), ("chill'", 1), ('chill)', 1), ('chill,', 1), ('chill.', 1), ('chill:', 1), ('chill;', 1), ('chill?', 1), ('chill_', 1), ('chills', 1), ('chilly', 1), ('chilt', 1), ('hill', 1), ('shill', 1), ('thill', 1), ('whill', 1), ('"Bill', 2), ('"Chill', 2), ('"Fill', 2), ('"Gill', 2), ('"Hill', 2), ('"Jill', 2), ('"Kill', 2), ('"Lill', 2), ('"Mill', 2), ('"Nill', 2), ('"Pill', 2), ('"Till', 2), ('"Vill', 2), ('"Will', 2), ('"_ill', 2), ('"bill', 2), ('"chil"', 2), ('"child', 2), ('"chill"', 2), ('"fill', 2), ('"hall', 2), ('"hell', 2), ('"hills', 2), ('"ill', 2), ('"kill', 2), ('"till', 2), ('"vill', 2), ('"will', 2), ("'Bill", 2), ("'Chill", 2), ("'Fill", 2), ("'Gill", 2), ("'Hill", 2), ("'Kill", 2), ("'Mill", 2), ("'Till", 2), ("'Will", 2), ("'bill", 2), ("'child", 2), ("'chill'", 2), ("'fill", 2), ("'haill", 2), ("'hall", 2), ("'hell", 2), ("'ill", 2), ("'kill", 2), ("'till", 2), ("'will", 2), ('(Bill', 2), ('(Hill', 2), ('(Kill', 2), ('(Mill', 2), ('(Till', 2), ('(Will', 2), ('(bill', 2), ('(child', 2), ('(ill', 2), ('(kill', 2), ('(till', 2), ('(will', 2), ('-Will', 2), ('-ill', 2), ('-will', 2), ('Achill.', 2), ('Achille', 2), ("Ah'll", 2), ('Aill', 2), ('Athill', 2), ('Bhil', 2), ('Bhil,', 2), ('Bhil.', 2), ('Bhil;', 2), ('Bhils', 2), ('Bill', 2), ('Brill', 2), ('Chil', 2), ('Chil!', 2), ('Chil,', 2), ('Child', 2), ('Chile', 2), ('Chili', 2), ('Chill,', 2), ('Chills', 2), ('Chilly', 2), ('Chilo', 2), ('Dill', 2), ('Drill', 2), ('Duill', 2), ('Fill', 2), ('Frill', 2), ('Ghyll', 2), ('Gill', 2), ('Grill', 2), ('Hill', 2), ('Ichil', 2), ('Jhil', 2), ('Jhil.', 2), ('Jill', 2), ('Khil;', 2), ('Kill', 2), ('Lill', 2), ('McGill', 2), ('Mill', 2), ('Mohill', 2), ('Neill', 2), ('Nihill', 2), ('Nill', 2), ('Ochil', 2), ('Ochils', 2), ('Phial', 2), ('Phil', 2), ('Phil!', 2), ('Phil,', 2), ('Phil.', 2), ('Phil:', 2), ('Phil;', 2), ('Phil?', 2), ('Phile', 2), ('Philly', 2), ('Philo', 2), ('Philp', 2), ('Pill', 2), ('Quhill', 2), ('Quill', 2), ('Rill', 2), ('STill', 2), ('Schall', 2), ('Schill!', 2), ('Schill,', 2), ('Scholl', 2), ('Shall', 2), ('Shell', 2), ('Shiel', 2), ('Shill,', 2), ('Shrill', 2), ('Sill', 2), ('Skill', 2), ('Spill', 2), ('Still', 2), ('Swill', 2), ('Thall', 2), ('Thrill', 2), ('Thull', 2), ('Till', 2), ('Twill', 2), ('Uphill', 2), ('Vill', 2), ('Weill', 2), ('While', 2), ('Whilk', 2), ('Whirl', 2), ('Will', 2), ('Yuill', 2), ('Zhall', 2), ('[Bill', 2), ('[Till', 2), ('[Will', 2), ('[hills', 2), ('[till', 2), ('[will', 2), ('_Bill', 2), ('_Chill', 2), ('_Hill', 2), ('_Jill', 2), ('_Mill', 2), ('_Rill', 2), ('_Till', 2), ('_Will', 2), ('_bill', 2), ('_chili', 2), ('_chill_', 2), ('_hill_', 2), ('_ill', 2), ('_kill', 2), ('_till', 2), ('_will', 2), ('`fill', 2), ('`will', 2), ("ah'll", 2), ('baill', 2), ('bill', 2), ('caill,', 2), ('caill.', 2), ('call', 2), ('ceil', 2), ('cell', 2), ("ch'al", 2), ('chail', 2), ('chail.', 2), ('chaille', 2), ('chal', 2), ('chale', 2), ('chalk', 2), ('chals', 2), ('chawl', 2), ("che'l", 2), ('cheild', 2), ('cheils', 2), ('chel', 2), ('chela', 2), ('chi', 2), ("chi'", 2), ('chi,', 2), ('chi-', 2), ('chic', 2), ('chic!', 2), ('chic)', 2), ('chic,', 2), ('chic.', 2), ('chic;', 2), ('chic?', 2), ('chica', 2), ('chice', 2), ('chick', 2), ('chid', 2), ('chid!', 2), ('chid,', 2), ('chid.', 2), ('chid;', 2), ('chide', 2), ('chief', 2), ('chiel!', 2), ('chiel"', 2), ("chiel'", 2), ('chiel,', 2), ('chiel.', 2), ('chiel;', 2), ('chield', 2), ('chiels', 2), ('chien', 2), ('chiep', 2), ("chil'd", 2), ('child!', 2), ('child"', 2), ("child'", 2), ('child)', 2), ('child,', 2), ('child-', 2), ('child.', 2), ('child:', 2), ('child;', 2), ('child?', 2), ('child]', 2), ('child_', 2), ('childe', 2), ('childly', 2), ('childs', 2), ('chile!', 2), ('chile,', 2), ('chile.', 2), ('chile;', 2), ('chile?', 2), ('chilen', 2), ('chiles', 2), ('chilis', 2), ('chill!"', 2), ("chill!'", 2), ('chill";', 2), ("chill'd", 2), ("chill's", 2), ('chill),', 2), ('chill,"', 2), ("chill,'", 2), ('chill--', 2), ('chill."', 2), ("chill.'", 2), ('chill.]', 2), ('chill._', 2), ('chill?"', 2), ("chill?'", 2), ('chilled', 2), ('chillen', 2), ('chiller', 2), ('chills!', 2), ('chills,', 2), ('chills.', 2), ('chills:', 2), ('chills;', 2), ('chills?', 2), ('chillum', 2), ('chillun', 2), ('chilly!', 2), ('chilly,', 2), ('chilly.', 2), ('chilly:', 2), ('chilly;', 2), ('chilly?', 2), ('chilt,', 2), ('chime', 2), ('chimla', 2), ('chimly', 2), ('chin', 2), ('chin!', 2), ('chin)', 2), ('chin,', 2), ('chin-', 2), ('chin.', 2), ('chin:', 2), ('chin;', 2), ('chin?', 2), ('chin]', 2), ('china', 2), ('chine', 2), ('ching', 2), ('chink', 2), ('chins', 2), ('chiny', 2), ('chip', 2), ('chip!', 2), ('chip,', 2), ('chip.', 2), ('chip;', 2), ('chip?', 2), ('chips', 2), ('chirk', 2), ('chirp', 2), ('chirr', 2), ('chise', 2), ('chisel', 2), ('chist', 2), ('chit', 2), ('chit!', 2), ('chit)', 2), ('chit,', 2), ('chit-', 2), ('chit.', 2), ('chit;', 2), ('chit?', 2), ('chits', 2), ('chiv', 2), ('chive', 2), ('chivy', 2), ('choilt', 2), ('cholla', 2), ('choly', 2), ('chowl', 2), ('churl', 2), ('chyle', 2), ('ciel', 2), ('cil', 2), ('cirl', 2), ('coil', 2), ('coil!', 2), ('coil,', 2), ('coil.', 2), ('coil:', 2), ('coil;', 2), ('coil?', 2), ('coils', 2), ('coll', 2), ('cull', 2), ('dholl', 2), ('dhrill', 2), ('dill', 2), ('drill', 2), ('ehall', 2), ('evill', 2), ('ewill', 2), ('fill', 2), ('frill', 2), ('ghila', 2), ('ghyll', 2), ('gill', 2), ('grill', 2), ('h-ll', 2), ('haill', 2), ('hall', 2), ('hell', 2), ("hi'll", 2), ('hil', 2), ('hil,', 2), ('hild', 2), ('hile', 2), ('hill!', 2), ('hill"', 2), ("hill'", 2), ('hill)', 2), ('hill,', 2), ('hill-', 2), ('hill.', 2), ('hill:', 2), ('hill;', 2), ('hill?', 2), ('hill]', 2), ('hills', 2), ('hilly', 2), ('hilp', 2), ('hilt', 2), ('holl', 2), ('hull', 2), ('ill', 2), ('jhil,', 2), ('jhils', 2), ('kill', 2), ('leill', 2), ('lill', 2), ('mill', 2), ('nill', 2), ('phial', 2), ('pill', 2), ('quhill', 2), ('quill', 2), ('rill', 2), ('schall', 2), ("sh'll", 2), ('shall', 2), ('shell', 2), ('shiel', 2), ('shild', 2), ('shill,', 2), ('shill:', 2), ('shill;', 2), ('shilly', 2), ('shily', 2), ('shll', 2), ('sholl', 2), ('shrill', 2), ('shtill', 2), ('shull', 2), ('sill', 2), ('skill', 2), ('spill', 2), ('still', 2), ('swill', 2), ('taill', 2), ('thall', 2), ('thell', 2), ('thilk', 2), ('thill,', 2), ('thrill', 2), ('thtill', 2), ('till', 2), ('toill', 2), ('trill', 2), ('twill', 2), ('uphill', 2), ('vhile', 2), ('vill', 2), ('weill', 2), ('while', 2), ('whilk', 2), ('whilly', 2), ('whirl', 2), ('whull', 2), ('will', 2), ('wrill', 2), ('yill', 2), ('zhall', 2), ('{will', 2)]
Querying of set and editdistance: 18.4s
```
|
bf33a5e5e3450d1d1c5bb4152c3bdb8472fa3787
|
[
"Markdown",
"Python"
] | 4
|
Python
|
NorthGuard/dasg
|
39654dad122fe0eaef267f70da8d7c26807115df
|
ba0c8da23fca6b4e8e73fd2b468faaf2beda7c56
|
refs/heads/master
|
<repo_name>hushlorentz/8080_emu<file_sep>/tests/src/rotate.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles operations that rotate the bits in the accumulator")
{
CPU cpu;
SECTION("A program can rotate the bits in the accumulator left")
{
uint8_t program[1] = { RLC };
cpu.registerA = 0xf2;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.registerA == 0xe5);
}
SECTION("A program can rotate the bits in the accumulator right")
{
uint8_t program[1] = { RRC };
cpu.registerA = 0xf2;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.registerA == 0x79);
}
SECTION("A program can rotate the bits in the accumulator left and consider the carry bit")
{
uint8_t program[1] = { RAL };
cpu.registerA = 0xb5;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.registerA == 0x6a);
}
SECTION("A program can rotate the bits in the accumulator left with the carry bit set")
{
uint8_t program[2] = { STC, RAL };
cpu.registerA = 0x03;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.registerA == 0x07);
}
SECTION("A program can rotate the bits in the accumulator right and consider the carry bit")
{
uint8_t program[1] = { RAR };
cpu.registerA = 0x6b;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.registerA == 0x35);
}
SECTION("A program can rotate the bits in the accumulator right with the carry bit set")
{
uint8_t program[2] = { STC, RAR };
cpu.registerA = 0x6a;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.registerA == 0xb5);
}
}
<file_sep>/src/space_invaders.cpp
#include "space_invaders.h"
using namespace std;
SpaceInvaders::SpaceInvaders() : registerX(0), shiftOffset(0), inputRegister(0x8)
{
}
uint8_t SpaceInvaders::inputPortHandler(uint8_t address)
{
switch (address)
{
case 0:
return 1;
break;
case 1:
return inputRegister;
break;
case 2:
return 0;
break;
case 3:
return registerX >> (8 - shiftOffset) & 0xff;
break;
}
return 0;
}
uint8_t SpaceInvaders::outputPortHandler(uint8_t address, uint8_t value)
{
switch (address)
{
case 2:
shiftOffset = value & 0x7;
break;
case 4:
registerX = registerX >> 8 | value << 8;
break;
}
return 0;
}
void SpaceInvaders::buttonPressed(uint8_t button)
{
inputRegister |= button;
}
void SpaceInvaders::buttonReleased(uint8_t button)
{
inputRegister &= ~button;
}
<file_sep>/tests/src/step.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/unhandled_op_code_exception.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU can step through one instruction at a time")
{
CPU cpu = CPU();
SECTION("The CPU executes one instruction at a time if stepping through")
{
uint8_t program[4] = { INR_B, INR_B, INR_B, INR_B };
cpu.stepThrough = true;
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x01);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x02);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x03);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x04);
}
SECTION("The CPU executes the rest of the program if stepping is disabled")
{
uint8_t program[4] = { INR_B, INR_B, INR_B, INR_B };
cpu.stepThrough = true;
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x01);
cpu.processProgram();
REQUIRE(cpu.registerB == 0x02);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerB == 0x04);
}
}
<file_sep>/src/cabinet.cpp
#include <chrono>
#include <cstdint>
#include <stdio.h>
#include <string>
#include <sys/time.h>
#include "cabinet.h"
#include "io.h"
#include "op_codes.h"
#define FILE_SIZE 8192
#define SCREEN_WIDTH 224
#define SCREEN_HEIGHT 256
using namespace std;
using namespace std::chrono;
Cabinet::Cabinet() : renderer(NULL)
{
}
void Cabinet::bootstrap()
{
loadROM();
initCPU();
initDisplay();
}
void Cabinet::loadROM()
{
uint8_t buffer[FILE_SIZE];
string inputFile = "data/invaders.bin";
memset(buffer, 0, FILE_SIZE);
if (openFile(inputFile, buffer, FILE_SIZE) == 0)
{
cpu.loadProgram(buffer, FILE_SIZE);
}
else
{
printf("Failed to load %s\n", inputFile.c_str());
exit(0);
}
}
void Cabinet::initCPU()
{
cpu.stepThrough = true;
cpu.setPortHandler(&hardware);
}
void Cabinet::initDisplay()
{
SDL_Window *window = NULL;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("Cannot init SDL: %s", SDL_GetError());
}
else
{
window = SDL_CreateWindow("Space Invaders", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!window)
{
printf("SDL Window could not be created: %s", SDL_GetError());
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer)
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError());
}
else
{
mainLoop();
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
}
void Cabinet::mainLoop()
{
bool running = true;
bool vsync1 = true;
SDL_Event event;
long long now = duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
long long last = now;
long long nextInterrupt = now + 8333;
int cyclesPerMicrosecond = 2;
while (running)
{
now = duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
if (now > nextInterrupt)
{
cpu.handleInterrupt(vsync1 ? RST_1 : RST_2);
vsync1 = !vsync1;
nextInterrupt = now + 8333;
}
uint32_t elapsedTime = now - last;
uint32_t targetCycles = elapsedTime * cyclesPerMicrosecond;
cpu.resetElapsedCycles();
while (cpu.elapsedCycles() < targetCycles)
{
cpu.processProgram();
}
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
running = false;
}
else if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_c:
hardware.buttonPressed(BUTTON_COIN);
break;
case SDLK_s:
hardware.buttonPressed(BUTTON_START);
break;
case SDLK_SPACE:
hardware.buttonPressed(BUTTON_SHOOT);
break;
case SDLK_LEFT:
hardware.buttonPressed(BUTTON_LEFT);
break;
case SDLK_RIGHT:
hardware.buttonPressed(BUTTON_RIGHT);
break;
}
}
else if (event.type == SDL_KEYUP)
{
switch (event.key.keysym.sym)
{
case SDLK_c:
hardware.buttonReleased(BUTTON_COIN);
break;
case SDLK_s:
hardware.buttonReleased(BUTTON_START);
break;
case SDLK_SPACE:
hardware.buttonReleased(BUTTON_SHOOT);
break;
case SDLK_LEFT:
hardware.buttonReleased(BUTTON_LEFT);
break;
case SDLK_RIGHT:
hardware.buttonReleased(BUTTON_RIGHT);
break;
}
}
}
SDL_RenderClear(renderer);
int index = 0;
for (vector<uint8_t>::iterator it = cpu.memory.begin() + (0x4000 - 1); it >= cpu.memory.begin() + 0x2400; --it) {
for (int p = 7; p >= 0; p--)
{
if (*it & (1 << p))
{
SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
}
else
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
}
int originalX = index % 256;
int originalY = index / 256;
int updatedX = originalY;
int updatedY = 256 - originalX;
SDL_Rect fillRect = { 224 - updatedX, 256 - updatedY, 1, 1 };
SDL_RenderFillRect(renderer, &fillRect);
index++;
}
}
SDL_RenderPresent(renderer);
last = now;
}
}
<file_sep>/src/unhandled_op_code_exception.h
#ifndef UNHANDLED_OP_CODE_EXCEPTION_H
#define UNHANDLED_OP_CODE_EXCEPTION_H
#include <exception>
#include <string>
using namespace std;
class UnhandledOpCodeException: public exception
{
public:
UnhandledOpCodeException(uint8_t opCode);
virtual const char *what() const throw();
private:
uint8_t opCode;
};
#endif
<file_sep>/tests/src/call.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
using namespace Catch;
TEST_CASE("Testing call op codes")
{
CPU cpu;
SECTION("A program can load a subroutine")
{
uint8_t program[3] = { CALL, 0x3b, 0x08 };
cpu.loadProgram(program, 3);
cpu.processProgram();
uint8_t mem = cpu.memory[0xfffe];
REQUIRE(cpu.programCounter == 0x083b);
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(mem == 3);
}
SECTION("CC performs a call to a subroutine if the carry bit is set")
{
uint8_t program[4] = { STC, CC, 0x21, 0xe3 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xe321);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CC does not perform a call to a subroutine if the carry bit is not set")
{
uint8_t program[3] = { CC, 0x21, 0xe3 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("CNC performs a call to a subroutine if the carry bit is not set")
{
uint8_t program[3] = { CNC, 0xaa, 0x10 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x10aa);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CNC does not perform a call to a subroutine if the carry bit is set")
{
uint8_t program[4] = { STC, CNC, 0x21, 0xe3 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 4);
}
SECTION("CZ performs a call to a subroutine if the zero bit is set")
{
uint8_t program[5] = { INR_C, DCR_C, CZ, 0x04, 0xc2 };
cpu.loadProgram(program, 5);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xc204);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CZ does not perform a call to a subroutine if the zero bit is not set")
{
uint8_t program[3] = { CZ, 0x21, 0xe3 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("CNZ performs a call to a subroutine if the zero bit is not set")
{
uint8_t program[3] = { CNZ, 0xa9, 0x9a };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x9aa9);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CNZ does not perform a call to a subroutine if the zero bit is set")
{
uint8_t program[5] = { INR_C, DCR_C, CNZ, 0x04, 0xc2 };
cpu.loadProgram(program, 5);
cpu.processProgram();
REQUIRE(cpu.programCounter == 5);
}
SECTION("CM performs a call to a subroutine if the sign bit is set")
{
uint8_t program[4] = { DCR_E, CM, 0xba, 0xab };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xabba);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CM does not perform a call to a subroutine if the sign bit is not set")
{
uint8_t program[3] = { CM, 0x04, 0xc2 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("CP performs a call to a subroutine if the sign bit is not set")
{
uint8_t program[3] = { CP, 0xca, 0xca };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xcaca);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CP does not perform a call to a subroutine if the sign bit is set")
{
uint8_t program[4] = { DCR_H, CP, 0x04, 0xc2 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 4);
}
SECTION("CPE performs a call to a subroutine if the parity bit is set")
{
uint8_t program[6] = { INR_L, INR_L, INR_L, CPE, 0x32, 0xb1 };
cpu.loadProgram(program, 6);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xb132);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CPE does not perform a call to a subroutine if the parity bit is not set")
{
uint8_t program[3] = { CPE, 0x04, 0xc2 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("CPO performs a call to a subroutine if the parity bit is not set")
{
uint8_t program[3] = { CPO, 0x04, 0xc2 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xc204);
REQUIRE(cpu.stackPointer == 0xfffe);
}
SECTION("CPO does not perform a call to a subroutine if the parity bit is set")
{
uint8_t program[6] = { INR_L, INR_L, INR_L, CPO, 0x32, 0xb1 };
cpu.loadProgram(program, 6);
cpu.processProgram();
REQUIRE(cpu.programCounter == 6);
}
}
<file_sep>/src/bit_ops.cpp
#include "bit_ops.h"
void setFlag(uint8_t *byte, uint8_t flag)
{
*byte |= flag;
}
void clearFlag(uint8_t *byte, uint8_t flag)
{
*byte &= ~flag;
}
bool hasFlag(uint8_t byte, uint8_t flag)
{
return (byte & flag) == flag;
}
uint8_t getLowerNibble(uint8_t byte)
{
return byte & 0x0F;
}
uint8_t getUpperNibble(uint8_t byte)
{
return (byte >> 4) & 0x0F;
}
bool hasCarryAtBitIndex(uint16_t b1, uint16_t b2, uint16_t index)
{
uint16_t masks[16] = { 0b0000000000000001,
0b0000000000000011,
0b0000000000000111,
0b0000000000001111,
0b0000000000011111,
0b0000000000111111,
0b0000000001111111,
0b0000000011111111,
0b0000000111111111,
0b0000001111111111,
0b0000011111111111,
0b0000111111111111,
0b0001111111111111,
0b0011111111111111,
0b0111111111111111,
0b1111111111111111
};
uint16_t b1Slice = b1 & masks[index];
uint16_t b2Slice = b2 & masks[index];
return b1Slice + b2Slice > masks[index];
}
<file_sep>/README.txt
An emulator for the 8080 processor
The Space Invaders front-end uses SDL. You can download the library from here https://www.libsdl.org/
The Space Invaders binary is not included in this repo, but is easily found on the internet. It's usually distributed in four parts: invaders.e, invaders.f, invaders.g, invaders.h. The loader expects the files to be concatenated into an invaders.bin file starting with invaders.h and working back to invaders.e.
This project has a badly written Makefile that builds two projects.
'make' will produce the 'emu' binary.
'make build_tests' will produce the 'run_tests' binary.
'make run_tests' will produce the 'run_tests' binary and run it.
There are a number of errors in the dependencies in the Makefile, such that editing cpu.cpp, and running make may lead to seg faults. Sorry, I'm terrible at make! Doing 'make clean && make' will always produce a correct binary.
The test framework I used is Catch. It is included in the project and documentation can be found here https://github.com/catchorg/Catch2
I followed this guide http://www.emulator101.com/ and the 8080 programming manual.
<file_sep>/src/status_bits.h
#ifndef STATUS_BITS_H
#define STATUS_BITS_H
#define CARRY_BIT 1
#define PARITY_BIT 4
#define AUXILIARY_CARRY_BIT 16
#define ZERO_BIT 64
#define SIGN_BIT 128
#define AUXILIARY_CARRY_SHIFT 3
#define CARRY_SHIFT 7
#endif
<file_sep>/tests/src/immediate.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/unhandled_op_code_exception.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles opcodes for operations with immediate instructions")
{
CPU cpu = CPU();
SECTION("A program can load a register pair with immediate data")
{
uint8_t program[3] = { LXI_B, 0xff, 0xaa };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.registerB == 0xaa);
REQUIRE(cpu.registerC == 0xff);
}
SECTION("A program can replace the stack pointer with immediate data")
{
uint8_t program[3] = { LXI_SP, 0x01, 0x10 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x1001);
}
SECTION("A program can replace the value of a register with immediate data")
{
uint8_t program[2] = { MVI_E, 0xa5 };
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerE == 0xa5);
}
SECTION("A program can replace a value in memory with immediate data")
{
uint8_t program[2] = { MVI_M, 0x6c };
cpu.registerH = 0x77;
cpu.registerL = 0x19;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.memory[0x7719] == 0x6c);
}
SECTION("A program can add immediate data to the accumulator")
{
uint8_t program[2] = { ADI, 0x73 };
cpu.registerA = 0x22;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x95);
}
SECTION("A program can add immediate data to the accumulator considering the carry")
{
uint8_t program[3] = { STC, ACI, 0x73 };
cpu.registerA = 0x22;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x96);
}
SECTION("A program can subtract immediate data from the accumulator")
{
uint8_t program[2] = { SUI, 0x44 };
cpu.registerA = 0x55;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x11);
}
SECTION("A program can subtract immediate data from the accumulator considering carry")
{
uint8_t program[3] = { STC, SBI, 0x01 };
cpu.registerA = 0x00;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xfe);
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.signBitSet());
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.parityBitSet());
REQUIRE(!cpu.auxiliaryCarryBitSet());
}
SECTION("A program can logically AND the immediate data with the accumulator")
{
uint8_t program[2] = { ANI, 0x0f };
cpu.registerA = 0x3a;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x0a);
}
SECTION("A program can logically XOR the immediate data with the accumulator")
{
uint8_t program[2] = { XRI, 0x81 };
cpu.registerA = 0x3b;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xba);
}
SECTION("A program can logically OR the immediate data with the accumulator")
{
uint8_t program[2] = { ORI, 0x0f };
cpu.registerA = 0xb5;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xbf);
}
SECTION("A program sets neither the zero bit nor the carry bit if the immediate data is less than the accumulator")
{
uint8_t program[2] = { CPI, 0x40 };
cpu.registerA = 0x4a;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
}
SECTION("A program sets the zero bit if the immediate data is equal to the accumulator")
{
uint8_t program[2] = { CPI, 0x4a };
cpu.registerA = 0x4a;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
}
SECTION("A program sets the carry bit if the immediate data is greater than the accumulator")
{
uint8_t program[2] = { CPI, 0x55 };
cpu.registerA = 0x4a;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.zeroBitSet());
REQUIRE(cpu.carryBitSet());
}
}
<file_sep>/src/io.h
#ifndef IO_H
#define IO_H
#include <string>
using namespace std;
int openFile(string filePath, unsigned char *buffer, int bufferSize);
#endif
<file_sep>/tests/src/accumulator.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles operations in the accumulator with operands from the registers and main memory")
{
CPU cpu;
SECTION("Register B can be added and stored in the accumulator")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0x0A;
uint8_t value = 0x0B;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value + initialValue);
}
SECTION("Adding 0x6c and 0x2e does not set zero and carry, but does set sign, parity and auxiliary flags")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0x6c;
uint8_t value = 0x2e;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value + initialValue);
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.parityBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(cpu.signBitSet());
}
SECTION("Adding 0 and 0 sets the zero flag")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0x0;
uint8_t value = 0x0;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value + initialValue);
REQUIRE(cpu.zeroBitSet());
}
SECTION("Adding 10 and -10 sets the zero flag")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0xf6;
uint8_t value = 0x0a;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == (uint8_t)(value + initialValue));
REQUIRE(cpu.zeroBitSet());
}
SECTION("Adding -10 and -10 sets the sign flag")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0xf6;
uint8_t value = 0xf6;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == (uint8_t)(value + initialValue));
REQUIRE(cpu.signBitSet());
}
SECTION("Adding 0xFF and 0xFF sets the carry bit")
{
uint8_t program[1] = { ADD_B };
uint8_t initialValue = 0xff;
uint8_t value = 0xff;
cpu.registerA = initialValue;
cpu.registerB = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == (uint8_t)(initialValue + value));
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
}
SECTION("Adding 0x6c and 0x2e from memory does not set zero and carry, but does set sign, parity and auxiliary flags")
{
uint8_t program[1] = { ADD_M };
uint8_t initialValue = 0x6c;
uint8_t value = 0x2e;
cpu.registerA = initialValue;
cpu.registerH = 0xbb;
cpu.registerL = 0xbb;
cpu.memory[0xbbbb] = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value + initialValue);
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.parityBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(cpu.signBitSet());
}
SECTION("Adding all registers (including the accumulator) results in two times the sum of all registers in the accumulator")
{
uint8_t program[8] = { ADD_B, ADD_C, ADD_D, ADD_E, ADD_H, ADD_L, ADD_M, ADD_A };
cpu.registerB = 0x01;
cpu.registerC = 0x02;
cpu.registerD = 0x03;
cpu.registerE = 0x04;
cpu.registerH = 0x05;
cpu.registerL = 0x06;
cpu.memory[0x0506] = 0x07;
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.registerA == 2 * (cpu.registerB + cpu.registerC + cpu.registerD + cpu.registerE + cpu.registerH + cpu.registerL + cpu.memory[0x0506]));
}
SECTION("If the carry bit is set, and the accumulator holds 0x42 and register D holds 0x3D, the accumulator will store 0x80 accounting for the carry.")
{
uint8_t program[2] = { STC, ADC_D };
cpu.registerA = 0x42;
cpu.registerD = 0x3d;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x80);
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
REQUIRE(!cpu.parityBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(cpu.signBitSet());
}
SECTION("If the carry bit is not set, and the accumulator holds 0x42 and register D holds 0x3D, the accumulator will store 0x7F accounting for the carry.")
{
uint8_t program[1] = { ADC_D };
cpu.registerA = 0x42;
cpu.registerD = 0x3d;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x7f);
}
SECTION("A program can subtract a register from the accumulator")
{
uint8_t program[1] = { SUB_H };
cpu.registerA = 0x0d;
cpu.registerH = 0x08;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x05);
}
SECTION("Subtracting 10 from 5 in the accumulator sets the sign flag")
{
uint8_t program[1] = { SUB_B };
cpu.registerA = 0x05;
cpu.registerB = 0x0a;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == (uint8_t)-5);
REQUIRE(cpu.signBitSet());
}
SECTION("If subtracting from the accumulator does not cause a carry, the carry flag is set")
{
uint8_t program[1] = { SUB_D };
cpu.registerA = 0x05;
cpu.registerD = 0x64;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == (uint8_t)(0x05 - 0x64));
REQUIRE(cpu.carryBitSet());
}
SECTION("If subtracting from the accumulator does cause a carry, the carry flag is not set")
{
uint8_t program[1] = { SUB_L };
cpu.registerA = 0x3e;
cpu.registerL = 0x3e;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
REQUIRE(!cpu.carryBitSet());
}
SECTION("Subtractions from the accumulator cause the zero flag to be set if the result is 0")
{
uint8_t program[1] = { SUB_C };
cpu.registerA = 0x06;
cpu.registerC = 0x06;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
REQUIRE(cpu.zeroBitSet());
}
SECTION("A program can subtract a value in main memory from the accumulator")
{
uint8_t program[1] = { SUB_M };
cpu.registerA = 0xcc;
cpu.registerH = 0xaa;
cpu.registerL = 0xaa;
cpu.memory[0xaaaa] = 0xbb;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x11);
}
SECTION("Subtracting the accumulator from itself always produces 0 and resets the carry bit")
{
uint8_t program[1] = { SUB_A };
cpu.registerA = 0xcc;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
REQUIRE(cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
}
SECTION("A program can subtract all the registers and main memory from the accumulator")
{
uint8_t program[7] = { SUB_B, SUB_C, SUB_D, SUB_E, SUB_H, SUB_L, SUB_M };
cpu.registerA = 0xff;
cpu.registerB = 0x1;
cpu.registerC = 0x2;
cpu.registerD = 0x3;
cpu.registerE = 0x4;
cpu.registerH = 0x5;
cpu.registerL = 0x6;
cpu.memory[0x0506] = 0x7;
uint8_t expectedResult = 0xff - (0x1 + 0x2 + 0x3 + 0x4 + 0x5 + 0x6 + 0x7);
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.registerA == expectedResult);
}
SECTION("A program can perform a subtraction with a borrow")
{
uint8_t program[2] = { STC, SBB_L };
cpu.registerA = 0x04;
cpu.registerL = 0x02;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x01);
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(!cpu.parityBitSet());
REQUIRE(!cpu.signBitSet());
}
SECTION("A program can perform a logical AND with a register and the accumulator")
{
uint8_t program[1] = { ANA_D };
cpu.registerA = 0x66;
cpu.registerD = 0x06;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x06);
}
SECTION("ANA ops set the correct status bits")
{
uint8_t program[2] = { STC, ANA_M };
cpu.registerA = 0xF6;
cpu.registerH = 0xaa;
cpu.registerL = 0xaa;
cpu.memory[0xaaaa] = 0xF0;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xF0);
REQUIRE(!cpu.carryBitSet());
REQUIRE(!cpu.zeroBitSet());
REQUIRE(cpu.parityBitSet());
REQUIRE(cpu.signBitSet());
}
SECTION("A program can perform a logical XOR with a register and the accumulator")
{
uint8_t program[1] = { XRA_E };
cpu.registerA = 0x66;
cpu.registerE = 0x66;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x0);
}
SECTION("XRA ops set the correct status bits")
{
uint8_t program[2] = { STC, XRA_M };
cpu.registerA = 0x06;
cpu.registerH = 0xcc;
cpu.registerL = 0xcc;
cpu.memory[0xcccc] = 0x60;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x66);
REQUIRE(!cpu.carryBitSet());
REQUIRE(!cpu.zeroBitSet());
REQUIRE(cpu.parityBitSet());
REQUIRE(!cpu.signBitSet());
}
SECTION("A program can perform a logical OR with a register and the accumulator")
{
uint8_t program[1] = { ORA_L };
cpu.registerA = 0xab;
cpu.registerL = 0x11;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xbb);
}
SECTION("ORA ops set the correct status bits")
{
uint8_t program[2] = { STC, ORA_M };
cpu.registerA = 0x33;
cpu.registerH = 0xff;
cpu.registerL = 0xff;
cpu.memory[0xffff] = 0x0F;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x3F);
REQUIRE(!cpu.carryBitSet());
REQUIRE(!cpu.zeroBitSet());
REQUIRE(cpu.parityBitSet());
REQUIRE(!cpu.signBitSet());
}
SECTION("The CMP_H opcode sets the zero bit if the contents of H equal the accumulator")
{
uint8_t program[1] = { CMP_H };
cpu.registerA = 0xb5;
cpu.registerH = 0xb5;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
}
SECTION("The CMP_B opcode sets the carry bit if register b is greater than the accumulator")
{
uint8_t program[1] = { CMP_B };
cpu.registerA = -0x1b;
cpu.registerB = -0x05;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.zeroBitSet());
REQUIRE(cpu.carryBitSet());
}
SECTION("The CMP_M opcode sets neither the carry bit nor the zero bit if the value in memory is less than the accumulator")
{
uint8_t program[1] = { CMP_M };
cpu.registerA = 0xff;
cpu.memory[0] = 0xfe;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.zeroBitSet());
REQUIRE(!cpu.carryBitSet());
}
}
<file_sep>/src/cpu.cpp
#include <iostream>
#include <string>
#include "bit_ops.h"
#include "cpu.h"
#include "op_codes.h"
#include "status_bits.h"
#include "unhandled_op_code_exception.h"
using namespace std;
#define REGISTER_A 7
#define REGISTER_B 0
#define REGISTER_C 1
#define REGISTER_D 2
#define REGISTER_E 3
#define REGISTER_H 4
#define REGISTER_L 5
#define REGISTER_M 6
#define REGISTER_PAIR_B 0
#define REGISTER_PAIR_D 1
#define REGISTER_PAIR_H 2
#define REGISTER_PAIR_A 3
#define MAX_MEMORY 65536
#define NO_INTERRUPT 0xff
CPU::CPU() : followJumps(true), runProgram(true), registerA(0), registerB(0), registerC(0), registerD(0), registerE(0), registerH(0), registerL(0), stackPointer(MAX_MEMORY), status(0x02), programCounter(0), stepThrough(false), interruptToHandle(NO_INTERRUPT), programLength(0), ignoreInterrupts(false), halt(false), portHandler(NULL), cycles(0)
{
memory.resize(MAX_MEMORY);
registerMap[REGISTER_B] = ®isterB;
registerMap[REGISTER_C] = ®isterC;
registerMap[REGISTER_D] = ®isterD;
registerMap[REGISTER_E] = ®isterE;
registerMap[REGISTER_H] = ®isterH;
registerMap[REGISTER_L] = ®isterL;
registerMap[REGISTER_A] = ®isterA;
registerPairB.push_back(®isterB);
registerPairB.push_back(®isterC);
registerPairD.push_back(®isterD);
registerPairD.push_back(®isterE);
registerPairH.push_back(®isterH);
registerPairH.push_back(®isterL);
registerPairA.push_back(®isterA);
registerPairA.push_back(&status);
registerPairMap[REGISTER_PAIR_B] = ®isterPairB;
registerPairMap[REGISTER_PAIR_D] = ®isterPairD;
registerPairMap[REGISTER_PAIR_H] = ®isterPairH;
registerPairMap[REGISTER_PAIR_A] = ®isterPairA;
}
bool CPU::carryBitSet()
{
return hasFlag(status, CARRY_BIT);
}
bool CPU::parityBitSet()
{
return hasFlag(status, PARITY_BIT);
}
bool CPU::signBitSet()
{
return hasFlag(status, SIGN_BIT);
}
bool CPU::zeroBitSet()
{
return hasFlag(status, ZERO_BIT);
}
bool CPU::auxiliaryCarryBitSet()
{
return hasFlag(status, AUXILIARY_CARRY_BIT);
}
void CPU::loadProgram(uint8_t *program, uint16_t programSize)
{
programCounter = 0;
programLength = programSize;
memcpy(memory.data(), program, programSize);
}
void CPU::processProgram()
{
do
{
handleNextInstruction();
}
while (programCounter < programLength && runProgram && !stepThrough);
}
void CPU::handleNextInstruction()
{
if (halt)
{
return;
}
if (interruptToHandle != NO_INTERRUPT)
{
programCounter = interruptToHandle;
interruptToHandle = NO_INTERRUPT;
ignoreInterrupts = false;
}
switch (memory[programCounter])
{
case LXI_B:
case LXI_D:
case LXI_H:
case LXI_SP:
case STA:
case LDA:
case SHLD:
case LXLD:
handle3ByteOp(memory[programCounter], memory[programCounter + 1], memory[programCounter + 2]);
programCounter += 3;
break;
case MVI_B:
case MVI_C:
case MVI_D:
case MVI_E:
case MVI_H:
case MVI_L:
case MVI_M:
case MVI_A:
case ADI:
case ACI:
case SUI:
case SBI:
case ANI:
case XRI:
case ORI:
case CPI:
case IN:
case OUT:
handle2ByteOp(memory[programCounter], memory[programCounter + 1]);
programCounter += 2;
break;
case PCHL:
programCounter = followJumps ? handleJumpByteOp() : programCounter + 1;
cycles += 5;
break;
case JC:
case JNC:
case JZ:
case JNZ:
case JMP:
case JM:
case JP:
case JPE:
case JPO:
programCounter = followJumps ? handleJump3ByteOp(memory[programCounter], memory[programCounter + 1], memory[programCounter + 2]) : programCounter + 3;
break;
case CALL:
case CC:
case CNC:
case CZ:
case CNZ:
case CM:
case CP:
case CPE:
case CPO:
programCounter = followJumps ? handleCall3ByteOp(memory[programCounter], memory[programCounter + 1], memory[programCounter + 2]) : programCounter + 3;
break;
case RET:
case RC:
case RNC:
case RZ:
case RNZ:
case RM:
case RP:
case RPE:
case RPO:
programCounter = followJumps ? handleReturnOp(memory[programCounter]) : programCounter + 1;
break;
case QUIT:
runProgram = false;
break;
case RST_0:
case RST_1:
case RST_2:
case RST_3:
case RST_4:
case RST_5:
case RST_6:
case RST_7:
handleInterrupt(memory[programCounter]);
break;
default:
handleByteOp(memory[programCounter]);
programCounter++;
break;
}
}
void CPU::handleByteOp(uint8_t opCode)
{
switch (opCode)
{
case MOV_B_B:
case MOV_C_C:
case MOV_D_D:
case MOV_E_E:
case MOV_H_H:
case MOV_L_L:
case MOV_A_A:
case NOP:
cycles += 4;
break;
case INR_B:
incrementRegister(®isterB);
cycles += 5;
break;
case INR_C:
incrementRegister(®isterC);
cycles += 5;
break;
case INR_D:
incrementRegister(®isterD);
cycles += 5;
break;
case INR_E:
incrementRegister(®isterE);
cycles += 5;
break;
case INR_H:
incrementRegister(®isterH);
cycles += 5;
break;
case INR_L:
incrementRegister(®isterL);
cycles += 5;
break;
case INR_A:
incrementRegister(®isterA);
cycles += 5;
break;
case INR_M:
incrementRegisterM();
cycles += 10;
break;
case STC:
setStatus(CARRY_BIT);
cycles += 4;
break;
case DCR_B:
decrementRegister(®isterB);
cycles += 5;
break;
case DCR_C:
decrementRegister(®isterC);
cycles += 5;
break;
case DCR_D:
decrementRegister(®isterD);
cycles += 5;
break;
case DCR_E:
decrementRegister(®isterE);
cycles += 5;
break;
case DCR_H:
decrementRegister(®isterH);
cycles += 5;
break;
case DCR_L:
decrementRegister(®isterL);
cycles += 5;
break;
case DCR_A:
decrementRegister(®isterA);
cycles += 5;
break;
case DCR_M:
decrementRegisterM();
cycles += 10;
break;
case CMC:
flipStatusBit(CARRY_BIT);
cycles += 4;
break;
case CMA:
complimentAccumulator();
cycles += 4;
break;
case DAA:
decimalAdjustAccumulator();
cycles += 4;
break;
case MOV_B_C:
case MOV_B_D:
case MOV_B_E:
case MOV_B_H:
case MOV_B_L:
case MOV_B_M:
case MOV_B_A:
case MOV_C_B:
case MOV_C_D:
case MOV_C_E:
case MOV_C_H:
case MOV_C_L:
case MOV_C_M:
case MOV_C_A:
case MOV_D_B:
case MOV_D_C:
case MOV_D_E:
case MOV_D_H:
case MOV_D_L:
case MOV_D_M:
case MOV_D_A:
case MOV_E_B:
case MOV_E_C:
case MOV_E_D:
case MOV_E_H:
case MOV_E_L:
case MOV_E_M:
case MOV_E_A:
case MOV_H_B:
case MOV_H_C:
case MOV_H_D:
case MOV_H_E:
case MOV_H_L:
case MOV_H_M:
case MOV_H_A:
case MOV_L_B:
case MOV_L_C:
case MOV_L_D:
case MOV_L_E:
case MOV_L_H:
case MOV_L_M:
case MOV_L_A:
case MOV_M_B:
case MOV_M_C:
case MOV_M_D:
case MOV_M_E:
case MOV_M_H:
case MOV_M_L:
case MOV_M_A:
case MOV_A_B:
case MOV_A_C:
case MOV_A_D:
case MOV_A_E:
case MOV_A_H:
case MOV_A_L:
case MOV_A_M:
moveRegisterToRegister(opCode);
break;
case LDX_B:
moveMemoryToAccumulator(registerB, registerC);
cycles += 7;
break;
case LDX_D:
moveMemoryToAccumulator(registerD, registerE);
cycles += 7;
break;
case STAX_B:
moveAccumulatorToMemory(registerB, registerC);
cycles += 7;
break;
case STAX_D:
moveAccumulatorToMemory(registerD, registerE);
cycles += 7;
break;
case ADD_B:
case ADD_C:
case ADD_D:
case ADD_E:
case ADD_H:
case ADD_L:
case ADD_A:
addValueToAccumulator(*registerMap[opCode & 7], 0);
cycles += 4;
break;
case ADD_M:
addValueToAccumulator(registerM(), 0);
cycles += 7;
break;
case ADC_B:
case ADC_C:
case ADC_D:
case ADC_E:
case ADC_H:
case ADC_L:
case ADC_A:
addValueToAccumulator(registerValueFromOpCode(opCode), carryBitSet() ? 1 : 0);
cycles += 4;
break;
case ADC_M:
addValueToAccumulator(registerM(), carryBitSet() ? 1 : 0);
cycles += 7;
break;
case SUB_B:
case SUB_C:
case SUB_D:
case SUB_E:
case SUB_H:
case SUB_L:
case SUB_A:
subtractValueFromAccumulator(registerValueFromOpCode(opCode));
cycles += 4;
break;
case SUB_M:
subtractValueFromAccumulator(registerM());
cycles += 7;
break;
case SBB_B:
case SBB_C:
case SBB_D:
case SBB_E:
case SBB_H:
case SBB_L:
case SBB_A:
subtractValueFromAccumulator(registerValueFromOpCode(opCode) + (carryBitSet() ? 1 : 0));
cycles += 4;
break;
case SBB_M:
subtractValueFromAccumulator(registerM() + (carryBitSet() ? 1 : 0));
cycles += 7;
break;
case ANA_B:
case ANA_C:
case ANA_D:
case ANA_E:
case ANA_H:
case ANA_L:
case ANA_A:
logicalANDWithAccumulator(registerValueFromOpCode(opCode));
cycles += 4;
break;
case ANA_M:
logicalANDWithAccumulator(registerM());
cycles += 7;
break;
case XRA_B:
case XRA_C:
case XRA_D:
case XRA_E:
case XRA_H:
case XRA_L:
case XRA_A:
logicalXORWithAccumulator(registerValueFromOpCode(opCode));
cycles += 4;
break;
case XRA_M:
logicalXORWithAccumulator(registerM());
cycles += 7;
break;
case ORA_B:
case ORA_C:
case ORA_D:
case ORA_E:
case ORA_H:
case ORA_L:
case ORA_A:
logicalORWithAccumulator(registerValueFromOpCode(opCode));
cycles += 4;
break;
case ORA_M:
logicalORWithAccumulator(registerM());
cycles += 7;
break;
case CMP_B:
case CMP_C:
case CMP_D:
case CMP_E:
case CMP_H:
case CMP_L:
case CMP_A:
compareValueToAccumulator(registerValueFromOpCode(opCode));
cycles += 4;
break;
case CMP_M:
compareValueToAccumulator(registerM());
cycles += 7;
break;
case RLC:
rotateAccumulatorLeft();
cycles += 4;
break;
case RRC:
rotateAccumulatorRight();
cycles += 4;
break;
case RAL:
rotateAccumulatorLeftWithCarry();
cycles += 4;
break;
case RAR:
rotateAccumulatorRightWithCarry();
cycles += 4;
break;
case PUSH_B:
case PUSH_D:
case PUSH_H:
case PUSH_PSW:
pushRegisterPairOnStack(registerPairFromOpCode(opCode));
cycles += 11;
break;
case POP_B:
case POP_D:
case POP_H:
popStackToRegisterPair(registerPairFromOpCode(opCode));
cycles += 10;
break;
case POP_PSW:
popStackToAccumulatorAndStatusPair();
cycles += 10;
break;
case DAD_B:
case DAD_D:
case DAD_H:
addValueToRegisterPairH(valueOfRegisterPair(registerPairFromOpCode(opCode)));
cycles += 10;
break;
case DAD_SP:
addValueToRegisterPairH(stackPointer);
cycles += 10;
break;
case INX_B:
case INX_D:
case INX_H:
incrementRegisterPair(registerPairFromOpCode(opCode));
cycles += 5;
break;
case INX_SP:
stackPointer++;
cycles += 5;
break;
case DCX_B:
case DCX_D:
case DCX_H:
decrementRegisterPair(registerPairFromOpCode(opCode));
cycles += 5;
break;
case DCX_SP:
stackPointer--;
cycles += 5;
break;
case XCHG:
exchangeRegisterPairs(registerPairMap[REGISTER_PAIR_D], registerPairMap[REGISTER_PAIR_H]);
cycles += 4;
break;
case XTHL:
exchangeRegistersAndMemory();
cycles += 18;
break;
case SPHL:
stackPointer = registerH << 8 | registerL;
cycles += 5;
break;
case DI:
ignoreInterrupts = true;
cycles += 4;
break;
case EI:
ignoreInterrupts = false;
cycles += 4;
break;
case HLT:
halt = true;
cycles += 7;
break;
default:
throw UnhandledOpCodeException(opCode);
break;
}
}
void CPU::setStatus(uint8_t bit)
{
setFlag(&(status), bit);
}
void CPU::clearStatus(uint8_t bit)
{
clearFlag(&(status), bit);
}
void CPU::flipStatusBit(uint8_t bit)
{
status = (status & bit) ? status & ~bit : status |= bit;
}
bool CPU::allClear()
{
return status == 0x02 && stackPointer == MAX_MEMORY && registerB == 0 && registerC == 0 &&
registerD == 0 && registerE == 0 && registerH == 0 &&
registerL == 0 && registerA == 0;
}
void CPU::incrementRegister(uint8_t *reg)
{
setAuxiliaryCarryBitFromRegisterAndOperand(*reg, 1);
(*reg)++;
setStatusFromRegister(*reg);
}
void CPU::setStatusFromRegister(uint8_t reg)
{
setParityBitFromRegister(reg);
setZeroBitFromRegister(reg);
setSignBitFromRegister(reg);
}
void CPU::setParityBitFromRegister(uint8_t reg)
{
reg ^= reg >> 4;
reg &= 0xf;
((0x9669 >> reg) & 1) ? setStatus(PARITY_BIT) : clearStatus(PARITY_BIT);
}
void CPU::setZeroBitFromRegister(uint8_t reg)
{
reg == 0 ? setStatus(ZERO_BIT) : clearStatus(ZERO_BIT);
}
void CPU::setSignBitFromRegister(uint8_t reg)
{
(int8_t)reg < 0 ? setStatus(SIGN_BIT) : clearStatus(SIGN_BIT);
}
void CPU::setAuxiliaryCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand)
{
checkAuxiliaryCarryBitFromRegisterAndOperand(reg, operand) ? setStatus(AUXILIARY_CARRY_BIT) : clearStatus(AUXILIARY_CARRY_BIT);
}
bool CPU::checkAuxiliaryCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand)
{
return hasCarryAtBitIndex(reg, operand, AUXILIARY_CARRY_SHIFT);
}
void CPU::decrementRegister(uint8_t *reg)
{
(*reg)--;
setStatusFromRegister(*reg);
}
void CPU::incrementRegisterM()
{
uint16_t memory_address = currentMemoryAddress();
uint8_t sum = memory[memory_address] + 1;
setAuxiliaryCarryBitFromRegisterAndOperand(memory[memory_address], 1);
memory[memory_address] = sum;
setStatusFromRegister(registerM());
}
void CPU::decrementRegisterM()
{
uint16_t memory_address = currentMemoryAddress();
uint8_t sum = memory[memory_address] - 1;
memory[memory_address] = sum;
setStatusFromRegister(registerM());
}
uint8_t CPU::registerM()
{
return memory[currentMemoryAddress()];
}
uint16_t CPU::currentMemoryAddress()
{
return registerH << 8 | registerL;
}
void CPU::complimentAccumulator()
{
registerA = ~registerA;
}
void CPU::decimalAdjustAccumulator()
{
uint8_t lower_bits = getLowerNibble(registerA);
uint8_t operand = 6;
if (lower_bits > 9 || auxiliaryCarryBitSet())
{
setAuxiliaryCarryBitFromRegisterAndOperand(registerA, operand);
registerA += operand;
}
uint8_t upper_bits = getUpperNibble(registerA);
if (upper_bits > 9 || carryBitSet())
{
checkAuxiliaryCarryBitFromRegisterAndOperand(upper_bits, operand) ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
upper_bits += operand;
}
registerA &= 0x0F;
registerA |= upper_bits << 4;
}
void CPU::setCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand)
{
checkCarryBitFromRegisterAndOperand(reg, operand) ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
}
bool CPU::checkCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand)
{
return hasCarryAtBitIndex(reg, operand, CARRY_SHIFT);
}
void CPU::moveRegisterToRegister(uint8_t opCode)
{
uint8_t dst = opCode >> 3 & 7;
uint8_t src = opCode & 7;
if (dst == REGISTER_M)
{
memory[currentMemoryAddress()] = *registerMap[src];
cycles += 7;
}
else if (src == REGISTER_M)
{
*registerMap[dst] = memory[currentMemoryAddress()];
cycles += 7;
}
else
{
*registerMap[dst] = *registerMap[src];
cycles += 5;
}
}
void CPU::moveMemoryToAccumulator(uint8_t upperBitsAddress, uint8_t lowerBitsAddress)
{
registerA = memory[upperBitsAddress << 8 | lowerBitsAddress];
}
void CPU::moveAccumulatorToMemory(uint8_t upperBitsAddress, uint8_t lowerBitsAddress)
{
memory[upperBitsAddress << 8 | lowerBitsAddress] = registerA;
}
void CPU::addValueToAccumulator(uint8_t value, uint8_t carry)
{
setAuxiliaryCarryBitFromRegisterAndOperand(registerA, value);
setCarryBitFromRegisterAndOperand(registerA, value);
registerA += value;
setStatusFromRegister(registerA);
if (carry)
{
addValueToAccumulator(1, 0);
}
}
void CPU::subtractValueFromAccumulator(uint8_t value)
{
checkCarryBitFromRegisterAndOperand(registerA, ~value + 1) ? clearStatus(CARRY_BIT) : setStatus(CARRY_BIT);
checkAuxiliaryCarryBitFromRegisterAndOperand(registerA, ~value + 1) ? setStatus(AUXILIARY_CARRY_BIT) : clearStatus(AUXILIARY_CARRY_BIT);
registerA += (~value + 1);
setStatusFromRegister(registerA);
}
uint8_t CPU::registerValueFromOpCode(uint8_t opCode)
{
return *registerMap[opCode & 7];
}
void CPU::logicalANDWithAccumulator(uint8_t value)
{
clearStatus(CARRY_BIT);
registerA &= value;
setStatusFromRegister(registerA);
}
void CPU::logicalXORWithAccumulator(uint8_t value)
{
clearStatus(CARRY_BIT);
registerA ^= value;
setStatusFromRegister(registerA);
}
void CPU::logicalORWithAccumulator(uint8_t value)
{
clearStatus(CARRY_BIT);
registerA |= value;
setStatusFromRegister(registerA);
}
void CPU::compareValueToAccumulator(uint8_t value)
{
checkCarryBitFromRegisterAndOperand(registerA, ~value + 1) ? clearStatus(CARRY_BIT) : setStatus(CARRY_BIT);
checkAuxiliaryCarryBitFromRegisterAndOperand(registerA, ~value + 1) ? setStatus(AUXILIARY_CARRY_BIT) : clearStatus(AUXILIARY_CARRY_BIT);
uint8_t diff = registerA + (~value + 1);
setStatusFromRegister(diff);
}
void CPU::rotateAccumulatorLeft()
{
bool highBitSet = (registerA >> CARRY_SHIFT & 1) == 1;
highBitSet ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
registerA <<= 1;
registerA |= highBitSet ? 1 : 0;
}
void CPU::rotateAccumulatorRight()
{
bool lowBitSet = (registerA & 1) == 1;
lowBitSet ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
registerA >>= 1;
registerA |= lowBitSet ? 1 << CARRY_SHIFT : 0;
}
void CPU::rotateAccumulatorLeftWithCarry()
{
bool carrySet = carryBitSet();
(registerA >> CARRY_SHIFT & 1) == 1 ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
registerA <<= 1;
registerA |= carrySet ? 1 : 0;
}
void CPU::rotateAccumulatorRightWithCarry()
{
bool carrySet = carryBitSet();
(registerA & 1) == 1 ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
registerA >>= 1;
registerA |= carrySet ? 1 << CARRY_SHIFT : 0;
}
vector<uint8_t *> * CPU::registerPairFromOpCode(uint8_t opCode)
{
return registerPairMap[(opCode >> 4) & 0x3];
}
void CPU::pushRegisterPairOnStack(vector<uint8_t *> * pair)
{
memory[stackPointer - 1] = *((*pair)[0]);
memory[stackPointer - 2] = *((*pair)[1]);
stackPointer -= 2;
}
void CPU::popStackToRegisterPair(vector<uint8_t *> * pair)
{
*((*pair)[0]) = memory[stackPointer + 1];
*((*pair)[1]) = memory[stackPointer];
stackPointer += 2;
}
void CPU::popStackToAccumulatorAndStatusPair()
{
registerA = memory[stackPointer + 1];
setStatusRegister(memory[stackPointer]);
stackPointer += 2;
}
void CPU::setStatusRegister(uint8_t value)
{
status = value;
status |= 0x02;
status &= 0xd7;
}
uint16_t CPU::valueOfRegisterPair(vector<uint8_t *> * pair)
{
return *(*pair)[0] << 8 | *(*pair)[1];
}
void CPU::addValueToRegisterPairH(uint16_t value)
{
vector<uint8_t *> * hlPair = registerPairMap[REGISTER_PAIR_H];
uint16_t HLValue = *(*hlPair)[0] << 8 | *(*hlPair)[1];
hasCarryAtBitIndex(HLValue, value, 15) ? setStatus(CARRY_BIT) : clearStatus(CARRY_BIT);
uint16_t sum = HLValue + value;
registerH = sum >> 8;
registerL = sum & 0xff;
}
void CPU::incrementRegisterPair(vector<uint8_t *> * pair)
{
uint16_t value = *(*pair)[0] << 8 | *(*pair)[1];
value++;
*(*pair)[0] = value >> 8;
*(*pair)[1] = value & 0xff;
}
void CPU::decrementRegisterPair(vector<uint8_t *> * pair)
{
uint16_t value = *(*pair)[0] << 8 | *(*pair)[1];
value--;
*(*pair)[0] = value >> 8;
*(*pair)[1] = value & 0xff;
}
void CPU::exchangeRegisterPairs(vector<uint8_t *> * p1, vector<uint8_t *> * p2)
{
uint8_t tempHighBits = *(*p1)[0];
uint8_t tempLowBits = *(*p1)[1];
*(*p1)[0] = *(*p2)[0];
*(*p1)[1] = *(*p2)[1];
*(*p2)[0] = tempHighBits;
*(*p2)[1] = tempLowBits;
}
void CPU::exchangeRegistersAndMemory()
{
uint8_t tempHighBits = registerL;
uint8_t tempLowBits = registerH;
registerL = memory[stackPointer];
registerH = memory[stackPointer + 1];
memory[stackPointer] = tempHighBits;
memory[stackPointer + 1] = tempLowBits;
}
void CPU::handle3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes)
{
uint16_t bytes = highBytes << 8 | lowBytes;
switch (opCode)
{
case LXI_B:
case LXI_D:
case LXI_H:
replaceRegisterPair(registerPairFromOpCode(opCode), highBytes, lowBytes);
cycles += 10;
break;
case LXI_SP:
stackPointer = bytes;
cycles += 10;
break;
case STA:
memory[bytes] = registerA;
cycles += 13;
break;
case LDA:
registerA = memory[bytes];
cycles += 13;
break;
case SHLD:
memory[bytes] = registerL;
memory[bytes + 1] = registerH;
cycles += 16;
break;
case LXLD:
registerL = memory[bytes];
registerH = memory[bytes + 1];
cycles += 16;
break;
}
}
void CPU::replaceRegisterPair(vector<uint8_t *> * pair, uint8_t highBytes, uint8_t lowBytes)
{
*(*pair)[0] = highBytes;
*(*pair)[1] = lowBytes;
}
void CPU::handle2ByteOp(uint8_t opCode, uint8_t value)
{
switch (opCode)
{
case MVI_B:
case MVI_C:
case MVI_D:
case MVI_E:
case MVI_H:
case MVI_L:
case MVI_A:
*(registerMap[opCode >> 3 & 7]) = value;
cycles += 7;
break;
case MVI_M:
memory[currentMemoryAddress()] = value;
cycles += 10;
break;
case ADI:
addValueToAccumulator(value, 0);
cycles += 7;
break;
case ACI:
addValueToAccumulator(value, carryBitSet() ? 1 : 0);
cycles += 7;
break;
case SUI:
subtractValueFromAccumulator(value);
cycles += 7;
break;
case SBI:
subtractValueFromAccumulator(value + (carryBitSet() ? 1 : 0));
cycles += 7;
break;
case ANI:
logicalANDWithAccumulator(value);
cycles += 7;
break;
case XRI:
logicalXORWithAccumulator(value);
cycles += 7;
break;
case ORI:
logicalORWithAccumulator(value);
cycles += 7;
break;
case CPI:
compareValueToAccumulator(value);
cycles += 7;
break;
case IN:
handleInputFromPort(memory[programCounter + 1]);
cycles += 10;
break;
case OUT:
handleOutputToPort(memory[programCounter + 1]);
cycles += 10;
break;
}
}
uint16_t CPU::handleJumpByteOp()
{
uint16_t address = registerH << 8 | registerL;
return address;
}
uint16_t CPU::handleJump3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes)
{
uint16_t bytes = highBytes << 8 | lowBytes;
uint16_t jumpMemoryLocation = 0;
switch (opCode)
{
case JC:
jumpMemoryLocation = carryBitSet() ? bytes : programCounter + 3;
break;
case JNC:
jumpMemoryLocation = carryBitSet() ? programCounter + 3 : bytes;
break;
case JZ:
jumpMemoryLocation = zeroBitSet() ? bytes : programCounter + 3;
break;
case JNZ:
jumpMemoryLocation = zeroBitSet() ? programCounter + 3 : bytes;
break;
case JM:
jumpMemoryLocation = signBitSet() ? bytes : programCounter + 3;
break;
case JP:
jumpMemoryLocation = signBitSet() ? programCounter + 3 : bytes;
break;
case JPE:
jumpMemoryLocation = parityBitSet() ? bytes : programCounter + 3;
break;
case JPO:
jumpMemoryLocation = parityBitSet() ? programCounter + 3 : bytes;
break;
case JMP:
jumpMemoryLocation = bytes;
break;
}
cycles += 10;
return jumpMemoryLocation;
}
void CPU::push2ByteValueOnStack(uint16_t value)
{
memory[stackPointer - 1] = value >> 8;
memory[stackPointer - 2] = value & 0xff;
stackPointer -= 2;
}
uint16_t CPU::handleCall3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes)
{
uint16_t bytes = highBytes << 8 | lowBytes;
uint16_t jumpMemoryLocation = 0;
switch (opCode)
{
case CALL:
jumpMemoryLocation = performCallOperation(bytes);
cycles += 17;
break;
case CC:
jumpMemoryLocation = carryBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += carryBitSet() ? 17 : 11;
break;
case CNC:
jumpMemoryLocation = !carryBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += !carryBitSet() ? 17 : 11;
break;
case CZ:
jumpMemoryLocation = zeroBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += zeroBitSet() ? 17 : 11;
break;
case CNZ:
jumpMemoryLocation = !zeroBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += !zeroBitSet() ? 17 : 11;
break;
case CM:
jumpMemoryLocation = signBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += signBitSet() ? 17 : 11;
break;
case CP:
jumpMemoryLocation = !signBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += !signBitSet() ? 17 : 11;
break;
case CPE:
jumpMemoryLocation = parityBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += parityBitSet() ? 17 : 11;
break;
case CPO:
jumpMemoryLocation = !parityBitSet() ? performCallOperation(bytes) : programCounter + 3;
cycles += !parityBitSet() ? 17 : 11;
break;
}
return jumpMemoryLocation;
}
uint16_t CPU::performCallOperation(uint16_t memoryOffset)
{
push2ByteValueOnStack(programCounter + 3);
return memoryOffset;
}
uint16_t CPU::handleReturnOp(uint8_t opCode)
{
uint16_t jumpMemoryLocation = 0;
switch (opCode)
{
case RET:
jumpMemoryLocation = pop2ByteValueFromStack();
cycles += 10;
break;
case RC:
jumpMemoryLocation = carryBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += carryBitSet() ? 11 : 5;
break;
case RNC:
jumpMemoryLocation = !carryBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += !carryBitSet() ? 11 : 5;
break;
case RZ:
jumpMemoryLocation = zeroBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += zeroBitSet() ? 11 : 5;
break;
case RNZ:
jumpMemoryLocation = !zeroBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += !zeroBitSet() ? 11 : 5;
break;
case RM:
jumpMemoryLocation = signBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += signBitSet() ? 11 : 5;
break;
case RP:
jumpMemoryLocation = !signBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += !signBitSet() ? 11 : 5;
break;
case RPE:
jumpMemoryLocation = parityBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += parityBitSet() ? 11 : 5;
break;
case RPO:
jumpMemoryLocation = !parityBitSet() ? pop2ByteValueFromStack() : programCounter + 1;
cycles += !parityBitSet() ? 11 : 5;
break;
}
return jumpMemoryLocation;
}
uint16_t CPU::pop2ByteValueFromStack()
{
uint8_t highBits = memory[stackPointer + 1];
uint8_t lowBits = memory[stackPointer];
stackPointer += 2;
return highBits << 8 | lowBits;
}
void CPU::handleInterrupt(uint8_t opCode)
{
if (ignoreInterrupts)
{
return;
}
push2ByteValueOnStack(programCounter);
interruptToHandle = opCode & 0x38;
halt = false;
ignoreInterrupts = true;
cycles += 11;
}
void CPU::setPortHandler(PortHandler *handler)
{
portHandler = handler;
}
void CPU::handleInputFromPort(uint8_t portAddress)
{
if (!portHandler)
{
throw runtime_error("No input port handler attached!");
}
registerA = portHandler->inputPortHandler(portAddress);
}
void CPU::handleOutputToPort(uint8_t portAddress)
{
if (!portHandler)
{
throw runtime_error("No output port handler attached!");
}
portHandler->outputPortHandler(portAddress, registerA);
}
uint32_t CPU::elapsedCycles()
{
return cycles;
}
void CPU::resetElapsedCycles()
{
cycles = 0;
}
<file_sep>/tests/src/data_transfer.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "catch.hpp"
using namespace Catch;
bool checkRegisterTransfer(CPU *cpu, uint8_t *program, uint8_t *src, uint8_t *dst)
{
uint8_t value = 0x20;
*src = value;
cpu->loadProgram(program, 1);
cpu->processProgram();
return *dst == value;
}
bool checkRegisterTransferToM(CPU *cpu, uint8_t *program, uint8_t *src)
{
uint8_t value = 0x20;
*src = value;
cpu->loadProgram(program, 1);
cpu->processProgram();
return cpu->registerM() == value;
}
bool checkRegisterTransferFromM(CPU *cpu, uint8_t *program, uint8_t *dst)
{
uint8_t value = 0x20;
cpu->registerH = 0xaa;
cpu->registerL = 0xaa;
cpu->memory[0xaaaa] = value;
cpu->loadProgram(program, 1);
cpu->processProgram();
return *dst == value;
}
TEST_CASE("The CPU handles data transfer correctly")
{
CPU cpu = CPU();
SECTION("A program can transfer a register to itself")
{
uint8_t program[1] = { MOV_B_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerB));
}
SECTION("A program can transfer register C to register B")
{
uint8_t program[1] = { MOV_B_C };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerC, &cpu.registerB));
}
SECTION("A program can transfer register D to register B")
{
uint8_t program[1] = { MOV_B_D };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerD, &cpu.registerB));
}
SECTION("A program can transfer register E to register B")
{
uint8_t program[1] = { MOV_B_E };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerE, &cpu.registerB));
}
SECTION("A program can transfer register H to register B")
{
uint8_t program[1] = { MOV_B_H };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerH, &cpu.registerB));
}
SECTION("A program can transfer register L to register B")
{
uint8_t program[1] = { MOV_B_L };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerL, &cpu.registerB));
}
SECTION("A program can transfer register M to register B")
{
uint8_t program[1] = { MOV_B_M };
REQUIRE(checkRegisterTransferFromM(&cpu, program, &cpu.registerB));
}
SECTION("A program can transfer register A to register B")
{
uint8_t program[1] = { MOV_B_A };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerA, &cpu.registerB));
}
SECTION("A program can transfer register B to register C")
{
uint8_t program[1] = { MOV_C_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerC));
}
SECTION("A program can transfer register B to register D")
{
uint8_t program[1] = { MOV_D_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerD));
}
SECTION("A program can transfer register B to register E")
{
uint8_t program[1] = { MOV_E_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerE));
}
SECTION("A program can transfer register B to register H")
{
uint8_t program[1] = { MOV_H_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerH));
}
SECTION("A program can transfer register B to register L")
{
uint8_t program[1] = { MOV_L_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerL));
}
SECTION("A program can transfer register B to register A")
{
uint8_t program[1] = { MOV_A_B };
REQUIRE(checkRegisterTransfer(&cpu, program, &cpu.registerB, &cpu.registerA));
}
SECTION("A program can transfer register B to register M")
{
uint8_t program[1] = { MOV_M_B };
REQUIRE(checkRegisterTransferToM(&cpu, program, &cpu.registerB));
}
SECTION("A program can store the memory location addressed by registers BC in the accumulator")
{
uint8_t program[1] = { LDX_B };
uint8_t value = 0xAF;
cpu.registerB = 0x0A;
cpu.registerC = 0xF0;
cpu.memory[0x0AF0] = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value);
}
SECTION("A program can store the memory location addressed by registers DE in the accumulator")
{
uint8_t program[1] = { LDX_D };
uint8_t value = 0xAF;
cpu.registerD = 0xA0;
cpu.registerE = 0x0F;
cpu.memory[0xA00F] = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == value);
}
SECTION("A program can store the accumulator in the memory location addressed by registers BC")
{
uint8_t program[1] = { STAX_B };
uint8_t value = 0xAF;
cpu.registerB = 0x0C;
cpu.registerC = 0x55;
cpu.registerA = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.memory[0x0C55] == value);
}
SECTION("A program can store the accumulator in the memory location addressed by registers DE")
{
uint8_t program[1] = { STAX_D };
uint8_t value = 0xAF;
cpu.registerD = 0xB1;
cpu.registerE = 0x49;
cpu.registerA = value;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.memory[0xB149] == value);
}
}
<file_sep>/tests/src/pair_register.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/unhandled_op_code_exception.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles opcodes for operations on register pairs correctly")
{
CPU cpu = CPU();
SECTION("A program can push data onto the stack")
{
uint8_t program[1] = { PUSH_B };
cpu.registerB = 0x06;
cpu.registerC = 0x15;
cpu.stackPointer = 0xbbaa;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.memory[0xbbaa - 0x0001] == cpu.registerB);
REQUIRE(cpu.memory[0xbbaa - 0x0002] == cpu.registerC);
}
SECTION("Register pair A uses the bits from the status register")
{
uint8_t program[2] = { STC, PUSH_PSW };
cpu.registerA = 0xf5;
cpu.stackPointer = 0x0045;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.memory[0x0045 - 0x0001] == cpu.registerA);
REQUIRE(cpu.memory[0x0045 - 0x0002] == cpu.status);
}
SECTION("A program can pop data off the stack and restore to register pairs")
{
uint8_t program[1] = { POP_D };
cpu.memory[0x0a] = 0xe5;
cpu.memory[0x09] = 0x11;
cpu.stackPointer = 0x09;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerD == 0xe5);
REQUIRE(cpu.registerE == 0x11);
}
SECTION("POP_PSW sets the status register directly")
{
uint8_t program[1] = { POP_PSW };
cpu.memory[0x1a] = 0xff;
cpu.memory[0x19] = 0xff;
cpu.stackPointer = 0x19;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xff);
REQUIRE(cpu.status == 0xd7);
REQUIRE(cpu.signBitSet());
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(cpu.zeroBitSet());
REQUIRE(cpu.parityBitSet());
}
SECTION("A program can add a 16-bit number spread across two registers")
{
uint8_t program[1] = { DAD_D };
cpu.registerD = 0x33;
cpu.registerE = 0x9f;
cpu.registerH = 0xa1;
cpu.registerL = 0x7b;
uint16_t HLValue = cpu.registerH << 8 | cpu.registerL;
uint16_t DEValue = cpu.registerD << 8 | cpu.registerE;
uint16_t sum = HLValue + DEValue;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(sum == 0xd51a);
REQUIRE((cpu.registerH << 8 | cpu.registerL) == sum);
}
SECTION("A 16-bit addition with a carry sets the carry bit")
{
uint8_t program[1] = { DAD_B };
cpu.registerB = 0xf0;
cpu.registerC = 0x00;
cpu.registerH = 0xf0;
cpu.registerL = 0x00;
uint16_t HLValue = cpu.registerH << 8 | cpu.registerL;
uint16_t BCValue = cpu.registerB << 8 | cpu.registerC;
uint16_t sum = HLValue + BCValue;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
REQUIRE((cpu.registerH << 8 | cpu.registerL) == sum);
}
SECTION("DAD_SP uses the stack pointer as the operand")
{
uint8_t program[1] = { DAD_SP };
cpu.stackPointer = 0x55a4;
cpu.registerH = 0xc4;
cpu.registerL = 0x88;
uint16_t HLValue = cpu.registerH << 8 | cpu.registerL;
uint16_t sum = HLValue + cpu.stackPointer;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
REQUIRE((cpu.registerH << 8 | cpu.registerL) == sum);
}
SECTION("A program can increment a 16-bit register pair")
{
uint8_t program[1] = { INX_H };
cpu.registerH = 0x0;
cpu.registerL = 0xff;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE((cpu.registerH << 8 | cpu.registerL) == 0x0100);
}
SECTION("A program can increment the stack pointer")
{
uint8_t program[1] = { INX_SP };
cpu.stackPointer = 0xffff;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
}
SECTION("A program can decrement a 16-bit register pair")
{
uint8_t program[1] = { DCX_D };
cpu.registerD = 0xee;
cpu.registerE = 0xdd;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE((cpu.registerD << 8 | cpu.registerE) == 0xeedc);
}
SECTION("A program can decrement the stack pointer")
{
uint8_t program[1] = { DCX_SP };
cpu.stackPointer = 1;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x0);
}
SECTION("A program can exchange the DE and HL register pairs")
{
uint8_t program[1] = { XCHG };
cpu.registerD = 0x33;
cpu.registerE = 0x55;
cpu.registerH = 0x00;
cpu.registerL = 0xff;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerD == 0x00);
REQUIRE(cpu.registerE == 0xff);
REQUIRE(cpu.registerH == 0x33);
REQUIRE(cpu.registerL == 0x55);
}
SECTION("A program can exchange the HL register pair with memory referenced by the stack pointer")
{
uint8_t program[1] = { XTHL };
cpu.registerH = 0x0b;
cpu.registerL = 0x3c;
cpu.stackPointer = 0x10ad;
cpu.memory[0x10ad] = 0x51;
cpu.memory[0x10ae] = 0x67;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerH == 0x67);
REQUIRE(cpu.registerL == 0x51);
REQUIRE(cpu.memory[0x10ad] == 0x3c);
REQUIRE(cpu.memory[0x10ae] == 0x0b);
}
SECTION("A program can replace the stack pointer with the HL register pair")
{
uint8_t program[1] = { SPHL };
cpu.registerH = 0x33;
cpu.registerL = 0x44;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x3344);
}
}
<file_sep>/tests/src/return.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
using namespace Catch;
TEST_CASE("Testing return op codes")
{
CPU cpu;
SECTION("A program can return from a subroutine")
{
uint8_t program[8] = { CALL, 0x04, 0x00, QUIT, INR_B, INR_B, INR_B, RET };
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerB == 3);
REQUIRE(!cpu.runProgram);
}
SECTION("RC returns if the carry flag is set")
{
uint8_t program[8] = { STC, CALL, 0x06, 0x00, INR_C, QUIT, INR_C, RC };
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerC == 2);
REQUIRE(!cpu.runProgram);
}
SECTION("RC does not return if the carry flag is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_C, QUIT, INR_C, RC };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerC == 1);
REQUIRE(cpu.runProgram);
}
SECTION("RNC performs a return if the carry bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_D, QUIT, INR_D, RNC };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerD == 2);
REQUIRE(!cpu.runProgram);
}
SECTION("RNC does not perform a return if the carry bit is set")
{
uint8_t program[8] = { STC, CALL, 0x06, 0x00, INR_D, QUIT, INR_D, RNC };
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerD == 1);
REQUIRE(cpu.runProgram);
}
SECTION("RZ performs a return if the zero bit is set")
{
uint8_t program[8] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, DCR_E, RZ };
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerE == 1);
REQUIRE(!cpu.runProgram);
}
SECTION("RZ does not perform a return if the zero bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, RZ };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerE == 1);
REQUIRE(cpu.runProgram);
}
SECTION("RNZ performs a return if the zero bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_B, QUIT, INR_B, RNZ };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerB == 2);
REQUIRE(!cpu.runProgram);
}
SECTION("RNZ does not perform a return if the zero bit is set")
{
uint8_t program[8] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, DCR_E, RNZ };
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerE == 0);
REQUIRE(cpu.runProgram);
}
SECTION("RM performs a return if the sign bit is set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_C, QUIT, DCR_C, RM };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerC == 0);
REQUIRE(!cpu.runProgram);
}
SECTION("RM does not perform a return if the sign bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_C, QUIT, INR_C, RM };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerC == 1);
REQUIRE(cpu.runProgram);
}
SECTION("RP performs a return if the sign bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_D, QUIT, INR_D, RP };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerD == 2);
REQUIRE(!cpu.runProgram);
}
SECTION("RP does not perform a return if the sign bit is set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_D, QUIT, DCR_D, RP };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerD == 0xff);
REQUIRE(cpu.runProgram);
}
SECTION("RPE performs a return if the parity bit is set")
{
uint8_t program[9] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, INR_E, INR_E, RPE };
cpu.loadProgram(program, 9);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerE == 4);
REQUIRE(!cpu.runProgram);
}
SECTION("RPE does not perform a return if the parity bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, RPE };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerE == 0x01);
REQUIRE(cpu.runProgram);
}
SECTION("RPO performs a return if the parity bit is not set")
{
uint8_t program[7] = { CALL, 0x05, 0x00, INR_B, QUIT, INR_B, RPO };
cpu.loadProgram(program, 7);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0x10000);
REQUIRE(cpu.registerB == 0x02);
REQUIRE(!cpu.runProgram);
}
SECTION("RPO does not perform a return if the parity bit is set")
{
uint8_t program[9] = { CALL, 0x05, 0x00, INR_E, QUIT, INR_E, INR_E, INR_E, RPO };
cpu.loadProgram(program, 9);
cpu.processProgram();
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.registerE == 3);
REQUIRE(cpu.runProgram);
}
}
<file_sep>/src/bit_ops.h
#ifndef BIT_OPS_H
#define BIT_OPS_H
#include <cstdint>
void setFlag(uint8_t *byte, uint8_t flag);
void clearFlag(uint8_t *byte, uint8_t flag);
bool hasFlag(uint8_t byte, uint8_t flag);
uint8_t getLowerNibble(uint8_t byte);
uint8_t getUpperNibble(uint8_t byte);
bool hasCarryAtBitIndex(uint16_t b1, uint16_t b2, uint16_t index);
#endif
<file_sep>/src/io.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int openFile(string filePath, unsigned char *buffer, int bufferSize)
{
ifstream input;
input.open(filePath, ios::out | ios::binary);
if (input) {
input.read((char *)buffer, bufferSize);
input.close();
if (input.gcount() != bufferSize) {
printf("Number of bytes read does not match number expected!\n");
return 1;
}
} else {
printf("Failed to open %s\n", buffer);
return 1;
}
return 0;
}
<file_sep>/tests/src/port_handling.cpp
#include "../../src/space_invaders.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The Space Invaders port handlers")
{
SpaceInvaders invaders = SpaceInvaders();
SECTION("Writing to port 2 sets the shift offset")
{
invaders.outputPortHandler(2, 0x04);
REQUIRE(invaders.shiftOffset == 0x04);
}
SECTION("Reading From port 3 returns 8 bits of registerX shifted by shiftOffset")
{
invaders.outputPortHandler(4, 0xff);
invaders.outputPortHandler(2, 0x02);
REQUIRE(invaders.inputPortHandler(3) == 0xfc);
}
SECTION("Writing to port 4 shifts contents right 8 bits and ors the new value")
{
invaders.outputPortHandler(4, 0xff);
REQUIRE(invaders.registerX == 0xff00);
}
}
<file_sep>/tests/src/input_output.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/port_handler.h"
using namespace Catch;
class MockPortHandler : public PortHandler
{
public:
uint8_t value;
virtual uint8_t inputPortHandler(uint8_t portAddress)
{
return portAddress;
}
virtual uint8_t outputPortHandler(uint8_t portAddress, uint8_t value)
{
this->value = value;
return 3;
}
};
TEST_CASE("Testing input / output op codes")
{
CPU cpu;
MockPortHandler portHandler;
SECTION("An exeternal function can write bytes to register A")
{
uint8_t program[2] = { IN, 0xab };
cpu.setPortHandler(&portHandler);
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0xab);
}
SECTION("An exception is thrown if no input port handler is hooked up")
{
uint8_t program[2] = { IN, 0 };
cpu.loadProgram(program, 2);
REQUIRE_THROWS_WITH(cpu.processProgram(), Contains("No input port handler attached!"));
}
SECTION("An exeternal function can read bytes from the CPU")
{
uint8_t program[4] = { INR_A, INR_A, OUT, 0 };
cpu.setPortHandler(&portHandler);
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(portHandler.value == cpu.registerA);
}
SECTION("An exception is thrown if no output port handler is hooked up")
{
uint8_t program[2] = { OUT, 0 };
cpu.loadProgram(program, 2);
REQUIRE_THROWS_WITH(cpu.processProgram(), Contains("No output port handler attached!"));
}
}
<file_sep>/tests/src/operations.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
using namespace Catch;
TEST_CASE("Testing operational opcodes")
{
CPU cpu;
SECTION("A program can quit with the QUIT op code")
{
uint8_t program[3] = { QUIT, INR_B, DCR_D };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.allClear());
}
}
<file_sep>/src/cabinet.h
#ifndef CABINET_H
#define CABINET_H
#include <SDL2/SDL.h>
#include "space_invaders.h"
class Cabinet
{
public:
Cabinet();
void bootstrap();
private:
SpaceInvaders hardware;
CPU cpu;
SDL_Renderer *renderer;
void loadROM();
void initDisplay();
void initCPU();
void mainLoop();
};
#endif
<file_sep>/tests/src/single_register.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/unhandled_op_code_exception.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles all the OpCodes correctly")
{
CPU cpu = CPU();
SECTION("The CPU starts in a cleared state")
{
REQUIRE(cpu.allClear());
}
SECTION("An unhandled OpCode throws an exception")
{
uint8_t program[1] = {0x20};
cpu.loadProgram(program, 1);
REQUIRE_THROWS_WITH(cpu.processProgram(), Contains("Unhandled Op Code: 0x20"));
}
SECTION("A program with only NOP, doesn't change the state of the CPU")
{
uint8_t program[1] = {NOP};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.allClear());
}
SECTION("A program can set the Carry Bit")
{
uint8_t program[1] = {STC};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
}
SECTION("A program can flip the Carry Bit")
{
uint8_t program[1] = {CMC};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.carryBitSet());
}
SECTION("A program can reset the Carry Bit by flipping it twice")
{
uint8_t program[2] = {CMC, CMC};
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.carryBitSet());
}
SECTION("A program can increment the registers")
{
uint8_t program[8] = {INR_A, INR_B, INR_C, INR_D, INR_E, INR_H, INR_L, INR_M};
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE(cpu.registerA == 1);
REQUIRE(cpu.registerB == 1);
REQUIRE(cpu.registerC == 1);
REQUIRE(cpu.registerD == 1);
REQUIRE(cpu.registerE == 1);
REQUIRE(cpu.registerH == 1);
REQUIRE(cpu.registerL == 1);
REQUIRE(cpu.registerM() == 1);
}
SECTION("Incrementing an 8-bit register once does not set the parity flag")
{
uint8_t program[1] = {INR_B};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.parityBitSet());
}
SECTION("Incrementing an 8-bit register three times sets the parity flag")
{
uint8_t program[3] = {INR_B, INR_B, INR_B};
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.parityBitSet());
}
SECTION("Incrementing a 16-bit register once does not set the parity flag")
{
uint8_t program[1] = {INR_M};
cpu.registerH = 0xaa;
cpu.registerL = 0xaa;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.parityBitSet());
}
SECTION("Incrementing a 16-bit register three times sets the parity flag")
{
uint8_t program[3] = {INR_M, INR_M, INR_M};
cpu.registerH = 0xaa;
cpu.registerL = 0xaa;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.parityBitSet());
}
SECTION("A program can decrement all registers")
{
uint8_t program[8] = {DCR_A, DCR_B, DCR_C, DCR_D, DCR_E, DCR_H, DCR_L, DCR_M};
cpu.loadProgram(program, 8);
cpu.processProgram();
REQUIRE((int8_t)cpu.registerA == -1);
REQUIRE((int8_t)cpu.registerB == -1);
REQUIRE((int8_t)cpu.registerC == -1);
REQUIRE((int8_t)cpu.registerD == -1);
REQUIRE((int8_t)cpu.registerE == -1);
REQUIRE((int8_t)cpu.registerH == -1);
REQUIRE((int8_t)cpu.registerL == -1);
REQUIRE((int8_t)cpu.registerM() == -1);
}
SECTION("Decrementing a register and then incrementing it sets the zero flag")
{
uint8_t program[2] = {DCR_B, INR_B};
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.zeroBitSet());
}
SECTION("Incrementing register M and then decrementing it sets the zero flag")
{
uint8_t program[2] = {INR_M, DCR_M};
cpu.registerH = 0xee;
cpu.registerL = 0xee;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.zeroBitSet());
}
SECTION("Decrementing a register passed 0 sets the sign flag")
{
uint8_t program[1] = {DCR_B};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.signBitSet());
}
SECTION("Decrementing a register passed 0 and then incrementing resets the sign flag")
{
uint8_t program[2] = {DCR_B, INR_B};
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(!cpu.signBitSet());
}
SECTION("Incrementing a register containing 14 does not set the auxiliary carry flag")
{
cpu.registerD = 14;
uint8_t program[1] = {INR_D};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.auxiliaryCarryBitSet());
}
SECTION("Incrementing a register containing 15 sets the auxiliary carry flag")
{
cpu.registerD = 15;
uint8_t program[1] = {INR_D};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.auxiliaryCarryBitSet());
}
SECTION("Incrementing register M containing 17 does not set the auxiliary carry flag")
{
cpu.memory[0] = 17;
uint8_t program[1] = {INR_M};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(!cpu.auxiliaryCarryBitSet());
}
SECTION("Incrementing register M containing 15 sets the auxiliary carry flag")
{
cpu.registerH = 0xaa;
cpu.registerL = 0xaa;
cpu.memory[0xaaaa] = 15;
uint8_t program[1] = {INR_M};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.auxiliaryCarryBitSet());
}
SECTION("A program can set the accumulator to its compliment")
{
uint8_t program[1] = {CMA};
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE((int8_t)cpu.registerA == -1);
}
SECTION("If the accumulator holds 0, DAA will not change its value")
{
uint8_t program[1] = {DAA};
cpu.registerA = 0;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
}
SECTION("If the accumulator holds 0xA, it will hold 0x10 after a DAA op code and the auxiliary flag will be set")
{
uint8_t program[1] = {DAA};
cpu.registerA = 10;
REQUIRE(cpu.registerA == 10);
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 16);
REQUIRE(cpu.auxiliaryCarryBitSet());
REQUIRE(!cpu.carryBitSet());
}
SECTION("If the accumulator holds 0x9A and a program calls the DAA Op Code, the accumulator will hold 1 and the Auxiliary Carry and Carry flags will be set.")
{
uint8_t program[1] = {DAA};
cpu.registerA = 0x9B;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.registerA == 1);
REQUIRE(cpu.carryBitSet());
REQUIRE(cpu.auxiliaryCarryBitSet());
}
SECTION("If the accumulator holds 0, and the program sets the carry bit and does a DAA, the accumulator will hold 0xA0 and the carry flag will be unset.")
{
uint8_t program[2] = {STC, DAA};
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x60);
REQUIRE(!cpu.carryBitSet());
}
SECTION("If the accumulator holds 0XF and a program does a INR_A and DAA, the accumulator will hold 0x06 and the auxiliary carry flag will be unset.")
{
uint8_t program[2] = {INR_A, DAA};
cpu.registerA = 0xF;
cpu.loadProgram(program, 2);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x16);
REQUIRE(!cpu.auxiliaryCarryBitSet());
}
}
<file_sep>/Makefile
EXE = emu
TEST_EXE = run_tests
CC = g++
CFLAGS = -Wall -std=c++11 -g -F /Library/Frameworks
LFLAGS = -framework SDL2 -F /Library/Frameworks -I /Library/Frameworks/SDL2.framework/Headers
SRC_DIR = src
OBJ_DIR = obj
TEST_DIR = tests
TEST_OBJ_DIR = $(TEST_DIR)/obj
OBJ = $(addprefix $(OBJ_DIR)/, bit_ops.o cabinet.o cpu.o io.o space_invaders.o unhandled_op_code_exception.o)
TEST_OBJ = $(addprefix $(TEST_OBJ_DIR)/, bit_ops.o cpu.o io.o space_invaders.o unhandled_op_code_exception.o)
TEST_SPECIFIC_OBJ = $(addprefix $(TEST_OBJ_DIR)/, accumulator.o bit_operations.o bootstrap.o call.o data_transfer.o direct.o immediate.o interrupts.o input_output.o jump.o operations.o op_codes.o pair_register.o port_handling.o return.o rotate.o single_register.o step.o)
$(EXE): $(OBJ) $(OBJ_DIR)/main.o
$(CC) $(CFLAGS) $^ -o $@ $(LFLAGS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(SRC_DIR)/%.h
@ mkdir -p $(OBJ_DIR)
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ_DIR)/main.o: $(SRC_DIR)/main.cpp
$(CC) $(CFLAGS) -c $< -o $@
build_tests: $(TEST_OBJ) $(TEST_SPECIFIC_OBJ)
$(CC) $(CFLAGS) $^ -o $(TEST_EXE)
$(TEST_EXE): build_tests
./$(TEST_EXE)
$(TEST_OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(SRC_DIR)/%.h
@ mkdir -p $(TEST_OBJ_DIR)
$(CC) $(CFLAGS) -c $< -o $@
$(TEST_OBJ_DIR)/%.o: $(TEST_DIR)/src/%.cpp $(SRC_DIR)/cpu.cpp $(SRC_DIR)/space_invaders.cpp
@ mkdir -p $(TEST_OBJ_DIR)
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJ_DIR)/*.o $(TEST_OBJ_DIR)/*.o $(EXE) $(TEST_EXE)
<file_sep>/src/space_invaders.h
#ifndef SPACE_INVADERS_H
#define SPACE_INVADERS_H
#include "cpu.h"
#include "port_handler.h"
#define BUTTON_COIN 1
#define BUTTON_START 4
#define BUTTON_SHOOT 16
#define BUTTON_LEFT 32
#define BUTTON_RIGHT 64
class SpaceInvaders : public PortHandler
{
public:
SpaceInvaders();
virtual uint8_t outputPortHandler(uint8_t address, uint8_t value);
virtual uint8_t inputPortHandler(uint8_t address);
uint16_t registerX;
uint8_t shiftOffset;
uint8_t inputRegister;
void buttonPressed(uint8_t button);
void buttonReleased(uint8_t button);
};
#endif
<file_sep>/tests/src/bit_operations.cpp
#include <cstdint>
#include "../../src/bit_ops.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("Bit operations are performed correctly")
{
SECTION("The lower nibble of 01010101 is 0101 (5)")
{
uint8_t byte = 0x55;
REQUIRE(getLowerNibble(byte) == 0x5);
}
SECTION("The upper nibble of 10101010 is 1010 (10)")
{
uint8_t byte = 0xAA;
REQUIRE(getUpperNibble(byte) == 0xA);
}
SECTION("Adding 0 and 1 does not produce a carry in the 0th position")
{
uint8_t b1 = 0x0;
uint8_t b2 = 0x1;
REQUIRE(!hasCarryAtBitIndex(b1, b2, 0));
}
SECTION("Adding 1 and 1 does produce a carry in the 0th position")
{
uint8_t b1 = 0x1;
uint8_t b2 = 0x1;
REQUIRE(hasCarryAtBitIndex(b1, b2, 0));
}
SECTION("Adding 1 and 1 does not produce a carry in the 1st position")
{
uint8_t b1 = 0x1;
uint8_t b2 = 0x1;
REQUIRE(!hasCarryAtBitIndex(b1, b2, 1));
}
SECTION("Adding 3 and 3 produces a carry in the 0th and 1st position")
{
uint8_t b1 = 0x03;
uint8_t b2 = 0x03;
REQUIRE(hasCarryAtBitIndex(b1, b2, 0));
REQUIRE(hasCarryAtBitIndex(b1, b2, 1));
}
}
<file_sep>/tests/src/jump.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
using namespace Catch;
TEST_CASE("Testing jump op codes")
{
CPU cpu;
SECTION("A program can set the program counter to the value of HL")
{
uint8_t program[1] = { PCHL };
cpu.registerH = 0x72;
cpu.registerL = 0x1d;
cpu.loadProgram(program, 1);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x721d);
}
SECTION("A program can set the program counter to the value of the immediate data")
{
uint8_t program[3] = { JMP, 0x3b, 0x22 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x223b);
}
SECTION("JC jumps if the carry bit is set")
{
uint8_t program[4] = { STC, JC, 0xe9, 0xa6 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xa6e9);
}
SECTION("JC does not jump if the carry bit is not set")
{
uint8_t program[3] = { JC, 0xe9, 0xa6 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("JNC jumps if the carry bit is not set")
{
uint8_t program[3] = { JNC, 0xf4, 0x69 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x69f4);
}
SECTION("JNC does not jump if the carry bit is set")
{
uint8_t program[4] = { STC, JNC, 0xff, 0xff };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 4);
}
SECTION("JZ jumps if the zero bit is set")
{
uint8_t program[4] = { SBB_A, JZ, 0xaa, 0x11 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x11aa);
}
SECTION("JZ does not jump if the zero bit is not set")
{
uint8_t program[3] = { JZ, 0xff, 0xff };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("JNZ jumps if the zero bit is not set")
{
uint8_t program[3] = { JNZ, 0x40, 0xd2 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xd240);
}
SECTION("JNZ does not jump if the zero bit is set")
{
uint8_t program[4] = { SBB_A, JNZ, 0xff, 0xff };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 4);
}
SECTION("JM jumps if the sign bit is set")
{
uint8_t program[4] = { DCR_A, JM, 0x30, 0x03 };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x0330);
}
SECTION("JM does not jump if the sign bit is not set")
{
uint8_t program[3] = { JM, 0xff, 0xff };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("JP jumps if the sign bit is not set")
{
uint8_t program[3] = { JP, 0xff, 0xff };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xffff);
}
SECTION("JP does not jump if the sign bit is set")
{
uint8_t program[4] = { DCR_A, JP, 0xff, 0xff };
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 4);
}
SECTION("JPE jumps if the parity bit is set")
{
uint8_t program[6] = { INR_B, INR_B, INR_B, JPE, 0xad, 0xde };
cpu.loadProgram(program, 6);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0xdead);
}
SECTION("JPE does not jump if the parity bit is not set")
{
uint8_t program[3] = { JPE, 0xff, 0xff };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
}
SECTION("JPO jumps if the parity bit is not set")
{
uint8_t program[3] = { JPO, 0x34, 0x09 };
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.programCounter == 0x0934);
}
SECTION("JPO does not jump if the parity bit is set")
{
uint8_t program[6] = { INR_D, INR_D, INR_D, JPO, 0xff, 0xff };
cpu.loadProgram(program, 6);
cpu.processProgram();
REQUIRE(cpu.programCounter == 6);
}
}
<file_sep>/src/port_handler.h
#ifndef PORT_HANDLER_H
#define PORT_HANDLER_H
#include <cstdint>
class PortHandler
{
public:
virtual uint8_t inputPortHandler(uint8_t address) = 0;
virtual uint8_t outputPortHandler(uint8_t address, uint8_t value) = 0;
};
#endif
<file_sep>/src/unhandled_op_code_exception.cpp
#include <iomanip>
#include <sstream>
#include "unhandled_op_code_exception.h"
UnhandledOpCodeException::UnhandledOpCodeException(uint8_t opCode) : opCode(opCode)
{
}
const char *UnhandledOpCodeException::what() const throw()
{
stringstream stream;
string message = "Unhandled Op Code: 0x";
stream << hex << setfill('0') << setw(2) << (int)opCode;
return (message + stream.str()).c_str();
}
<file_sep>/src/op_codes.h
#ifndef OP_CODES_H
#define OP_CODES_H
#define NOP 0x00
#define LXI_B 0x01
#define STAX_B 0x02
#define INX_B 0x03
#define INR_B 0x04
#define DCR_B 0x05
#define MVI_B 0x06
#define RLC 0x07
#define QUIT 0x08
#define DAD_B 0x09
#define LDX_B 0x0a
#define DCX_B 0x0b
#define INR_C 0x0c
#define DCR_C 0x0d
#define MVI_C 0x0e
#define RRC 0x0f
#define LXI_D 0x11
#define STAX_D 0x12
#define INX_D 0x13
#define INR_D 0x14
#define DCR_D 0x15
#define MVI_D 0x16
#define RAL 0x17
#define DAD_D 0x19
#define LDX_D 0x1a
#define DCX_D 0x1b
#define INR_E 0x1c
#define DCR_E 0x1d
#define MVI_E 0x1e
#define RAR 0x1f
#define LXI_H 0x21
#define SHLD 0x22
#define INX_H 0x23
#define INR_H 0x24
#define DCR_H 0x25
#define MVI_H 0x26
#define DAA 0x27
#define DAD_H 0x29
#define LXLD 0x2a
#define DCX_H 0x2b
#define INR_L 0x2c
#define DCR_L 0x2d
#define MVI_L 0x2e
#define CMA 0x2f
#define LXI_SP 0x31
#define STA 0x32
#define INX_SP 0x33
#define INR_M 0x34
#define DCR_M 0x35
#define MVI_M 0x36
#define STC 0x37
#define DAD_SP 0x39
#define LDA 0x3a
#define DCX_SP 0x3b
#define INR_A 0x3c
#define DCR_A 0x3d
#define MVI_A 0x3e
#define CMC 0x3f
#define MOV_B_B 0x40
#define MOV_B_C 0x41
#define MOV_B_D 0x42
#define MOV_B_E 0x43
#define MOV_B_H 0x44
#define MOV_B_L 0x45
#define MOV_B_M 0x46
#define MOV_B_A 0x47
#define MOV_C_B 0x48
#define MOV_C_C 0x49
#define MOV_C_D 0x4a
#define MOV_C_E 0x4b
#define MOV_C_H 0x4c
#define MOV_C_L 0x4d
#define MOV_C_M 0x4e
#define MOV_C_A 0x4f
#define MOV_D_B 0x50
#define MOV_D_C 0x51
#define MOV_D_D 0x52
#define MOV_D_E 0x53
#define MOV_D_H 0x54
#define MOV_D_L 0x55
#define MOV_D_M 0x56
#define MOV_D_A 0x57
#define MOV_E_B 0x58
#define MOV_E_C 0x59
#define MOV_E_D 0x5a
#define MOV_E_E 0x5b
#define MOV_E_H 0x5c
#define MOV_E_L 0x5d
#define MOV_E_M 0x5e
#define MOV_E_A 0x5f
#define MOV_H_B 0x60
#define MOV_H_C 0x61
#define MOV_H_D 0x62
#define MOV_H_E 0x63
#define MOV_H_H 0x64
#define MOV_H_L 0x65
#define MOV_H_M 0x66
#define MOV_H_A 0x67
#define MOV_L_B 0x68
#define MOV_L_C 0x69
#define MOV_L_D 0x6a
#define MOV_L_E 0x6b
#define MOV_L_H 0x6c
#define MOV_L_L 0x6d
#define MOV_L_M 0x6e
#define MOV_L_A 0x6f
#define MOV_M_B 0x70
#define MOV_M_C 0x71
#define MOV_M_D 0x72
#define MOV_M_E 0x73
#define MOV_M_H 0x74
#define MOV_M_L 0x75
#define HLT 0x76
#define MOV_M_A 0x77
#define MOV_A_B 0x78
#define MOV_A_C 0x79
#define MOV_A_D 0x7a
#define MOV_A_E 0x7b
#define MOV_A_H 0x7c
#define MOV_A_L 0x7d
#define MOV_A_M 0x7e
#define MOV_A_A 0x7f
#define ADD_B 0x80
#define ADD_C 0x81
#define ADD_D 0x82
#define ADD_E 0x83
#define ADD_H 0x84
#define ADD_L 0x85
#define ADD_M 0x86
#define ADD_A 0x87
#define ADC_B 0x88
#define ADC_C 0x89
#define ADC_D 0x8a
#define ADC_E 0x8b
#define ADC_H 0x8c
#define ADC_L 0x8d
#define ADC_M 0x8e
#define ADC_A 0x8f
#define SUB_B 0x90
#define SUB_C 0x91
#define SUB_D 0x92
#define SUB_E 0x93
#define SUB_H 0x94
#define SUB_L 0x95
#define SUB_M 0x96
#define SUB_A 0x97
#define SBB_B 0x98
#define SBB_C 0x99
#define SBB_D 0x9a
#define SBB_E 0x9b
#define SBB_H 0x9c
#define SBB_L 0x9d
#define SBB_M 0x9e
#define SBB_A 0x9f
#define ANA_B 0xa0
#define ANA_C 0xa1
#define ANA_D 0xa2
#define ANA_E 0xa3
#define ANA_H 0xa4
#define ANA_L 0xa5
#define ANA_M 0xa6
#define ANA_A 0xa7
#define XRA_B 0xa8
#define XRA_C 0xa9
#define XRA_D 0xaa
#define XRA_E 0xab
#define XRA_H 0xac
#define XRA_L 0xad
#define XRA_M 0xae
#define XRA_A 0xaf
#define ORA_B 0xb0
#define ORA_C 0xb1
#define ORA_D 0xb2
#define ORA_E 0xb3
#define ORA_H 0xb4
#define ORA_L 0xb5
#define ORA_M 0xb6
#define ORA_A 0xb7
#define CMP_B 0xb8
#define CMP_C 0xb9
#define CMP_D 0xba
#define CMP_E 0xbb
#define CMP_H 0xbc
#define CMP_L 0xbd
#define CMP_M 0xbe
#define CMP_A 0xbf
#define RNZ 0xc0
#define POP_B 0xc1
#define JNZ 0xc2
#define JMP 0xc3
#define CNZ 0xc4
#define PUSH_B 0xc5
#define ADI 0xc6
#define RST_0 0xc7
#define RZ 0xc8
#define RET 0xc9
#define JZ 0xca
#define CZ 0xcc
#define CALL 0xcd
#define ACI 0xce
#define RST_1 0xcf
#define RNC 0xd0
#define POP_D 0xd1
#define JNC 0xd2
#define OUT 0xd3
#define CNC 0xd4
#define PUSH_D 0xd5
#define SUI 0xd6
#define RST_2 0xd7
#define RC 0xd8
#define JC 0xda
#define IN 0xdb
#define CC 0xdc
#define SBI 0xde
#define RST_3 0xdf
#define RPO 0xe0
#define POP_H 0xe1
#define JPO 0xe2
#define XTHL 0xe3
#define CPO 0xe4
#define PUSH_H 0xe5
#define ANI 0xe6
#define RST_4 0xe7
#define RPE 0xe8
#define PCHL 0xe9
#define JPE 0xea
#define XCHG 0xeb
#define CPE 0xec
#define XRI 0xee
#define RST_5 0xef
#define RP 0xf0
#define POP_PSW 0xf1
#define JP 0xf2
#define DI 0xf3
#define CP 0xf4
#define PUSH_PSW 0xf5
#define ORI 0xf6
#define RST_6 0xf7
#define RM 0xf8
#define SPHL 0xf9
#define JM 0xfa
#define EI 0xfb
#define CM 0xfc
#define CPI 0xfe
#define RST_7 0xff
#endif
<file_sep>/tests/src/interrupts.cpp
#include "catch.hpp"
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
using namespace Catch;
TEST_CASE("Testing interrupt op codes")
{
CPU cpu;
SECTION("Calling an interrupt sets the stack pointer to the interrupt's location in memory")
{
uint8_t program[11] = { NOP, INR_D, QUIT, NOP, NOP, NOP, NOP, NOP, INR_C, INR_C, RET };
cpu.stepThrough = true;
cpu.loadProgram(program, 11);
cpu.processProgram();
cpu.handleInterrupt(RST_1);
REQUIRE(cpu.stackPointer == 0xfffe);
REQUIRE(cpu.memory[0xfffe] == 0x1);
REQUIRE(cpu.memory[0xffff] == 0);
cpu.processProgram();
REQUIRE(cpu.registerC == 0x1);
cpu.processProgram();
REQUIRE(cpu.registerC == 0x2);
REQUIRE(cpu.registerD == 0x0);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerD == 0x1);
REQUIRE(cpu.registerC == 0x2);
}
SECTION("RST_2 runs the subroutine at address 0x10")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x10] = INR_E;
cpu.memory[0x11] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_2);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerE == 0x1);
}
SECTION("RST_3 runs the subroutine at address 0x18")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x18] = INR_A;
cpu.memory[0x19] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_3);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerA == 0x1);
}
SECTION("RST_4 runs the subroutine at address 0x20")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x20] = INR_B;
cpu.memory[0x21] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_4);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerB == 0x1);
}
SECTION("RST_5 runs the subroutine at address 0x28")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x28] = INR_C;
cpu.memory[0x29] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_5);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerC == 0x1);
}
SECTION("RST_6 runs the subroutine at address 0x30")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x30] = INR_D;
cpu.memory[0x31] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_6);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerD == 0x1);
}
SECTION("RST_7 runs the subroutine at address 0x38")
{
uint8_t program[3] = { NOP, NOP, QUIT };
cpu.memory[0x38] = INR_E;
cpu.memory[0x39] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_7);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerE == 0x1);
}
SECTION("RST_0 sets the programCounter to address 0")
{
uint8_t program[4] = { NOP, NOP, NOP, QUIT };
cpu.stepThrough = true;
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.programCounter == 1);
cpu.processProgram();
REQUIRE(cpu.programCounter == 2);
cpu.processProgram();
REQUIRE(cpu.programCounter == 3);
cpu.handleInterrupt(RST_0);
cpu.processProgram();
REQUIRE(cpu.programCounter == 1);
}
SECTION("A DI opcode makes the CPU ignore future interrupt requests")
{
uint8_t program[3] = { DI, NOP, QUIT };
cpu.memory[0x10] = INR_E;
cpu.memory[0x11] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.handleInterrupt(RST_2);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerE == 0);
}
SECTION("An EI opcode after a DI makes the CPU accept interrupt requests")
{
uint8_t program[3] = { DI, EI, QUIT };
cpu.memory[0x10] = INR_E;
cpu.memory[0x11] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 3);
cpu.processProgram();
cpu.processProgram();
cpu.handleInterrupt(RST_2);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerE == 1);
}
SECTION("A HLT opcode makes the CPU wait until an interrupt is processed")
{
uint8_t program[4] = { NOP, HLT, INR_A, QUIT };
cpu.memory[0x10] = RET;
cpu.stepThrough = true;
cpu.loadProgram(program, 4);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
cpu.processProgram();
REQUIRE(cpu.registerA == 0);
cpu.handleInterrupt(RST_2);
cpu.stepThrough = false;
cpu.processProgram();
REQUIRE(cpu.registerA == 0x1);
}
}
<file_sep>/src/main.cpp
#include "cabinet.h"
int main(void)
{
Cabinet cabinet;
cabinet.bootstrap();
return 0;
}
<file_sep>/tests/src/direct.cpp
#include "../../src/cpu.h"
#include "../../src/op_codes.h"
#include "../../src/unhandled_op_code_exception.h"
#include "catch.hpp"
using namespace Catch;
TEST_CASE("The CPU handles opcodes for operations with direct memory instructions")
{
CPU cpu = CPU();
SECTION("A program can store the accumulator in the referenced memory")
{
uint8_t program[3] = { STA, 0xff, 0xaa };
cpu.registerA = 0x93;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.memory[0xaaff] == 0x93);
}
SECTION("A program can store the referenced memory location in the accumulator")
{
uint8_t program[3] = { LDA, 0xff, 0xaa };
cpu.memory[0xaaff] = 0x93;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.registerA == 0x93);
}
SECTION("A program can store the values of H and L in the referenced memory")
{
uint8_t program[3] = { SHLD, 0x24, 0x81 };
cpu.registerH = 0xae;
cpu.registerL = 0x29;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.memory[0x8124] == 0x29);
REQUIRE(cpu.memory[0x8125] == 0xae);
}
SECTION("A program can load referenced memory into registers H and L")
{
uint8_t program[3] = { LXLD, 0x01, 0x10 };
cpu.memory[0x1001] = 0x05;
cpu.memory[0x1002] = 0xe2;
cpu.loadProgram(program, 3);
cpu.processProgram();
REQUIRE(cpu.registerH == 0xe2);
REQUIRE(cpu.registerL == 0x05);
}
}
<file_sep>/src/cpu.h
#ifndef CPU_H
#define CPU_H
#include "port_handler.h"
#include <cstdint>
#include <map>
#include <vector>
using namespace std;
class CPU
{
public:
CPU();
bool followJumps;
bool carryBitSet();
bool parityBitSet();
bool signBitSet();
bool zeroBitSet();
bool auxiliaryCarryBitSet();
bool allClear();
bool runProgram;
void loadProgram(uint8_t *program, uint16_t programSize);
void processProgram();
uint8_t registerA;
uint8_t registerB;
uint8_t registerC;
uint8_t registerD;
uint8_t registerE;
uint8_t registerH;
uint8_t registerL;
uint8_t registerM();
uint32_t stackPointer;
uint8_t status;
uint16_t programCounter;
bool stepThrough;
uint8_t *executingProgram;
vector<uint8_t *> registerPairB;
vector<uint8_t *> registerPairD;
vector<uint8_t *> registerPairH;
vector<uint8_t *> registerPairA;
vector<uint8_t> memory;
map<uint8_t, uint8_t *> registerMap;
map<uint8_t, vector<uint8_t *> *> registerPairMap;
void handleInterrupt(uint8_t opCode);
void setPortHandler(PortHandler *handler);
uint32_t elapsedCycles();
void resetElapsedCycles();
private:
uint8_t interruptToHandle;
uint16_t programLength;
bool ignoreInterrupts;
bool halt;
PortHandler *portHandler;
uint32_t cycles;
void handleByteOp(uint8_t opCode);
void setStatus(uint8_t bit);
void clearStatus(uint8_t bit);
void flipStatusBit(uint8_t bit);
void incrementRegister(uint8_t *reg);
void incrementRegisterM();
void decrementRegister(uint8_t *reg);
void decrementRegisterM();
uint16_t currentMemoryAddress();
void setStatusFromRegister(uint8_t reg);
void setParityBitFromRegister(uint8_t reg);
void setZeroBitFromRegister(uint8_t reg);
void setSignBitFromRegister(uint8_t reg);
bool checkAuxiliaryCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand);
bool checkCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand);
void setAuxiliaryCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand);
void setCarryBitFromRegisterAndOperand(uint8_t reg, uint8_t operand);
void complimentAccumulator();
void decimalAdjustAccumulator();
void moveRegisterToRegister(uint8_t opCode);
void moveMemoryToAccumulator(uint8_t upperBitsAddress, uint8_t lowerBitsAddress);
void moveAccumulatorToMemory(uint8_t upperbitsAddress, uint8_t lowerBitsAddress);
void addValueToAccumulator(uint8_t value, uint8_t carry);
uint8_t registerValueFromOpCode(uint8_t opCode);
void subtractValueFromAccumulator(uint8_t value);
void logicalANDWithAccumulator(uint8_t value);
void logicalXORWithAccumulator(uint8_t value);
void logicalORWithAccumulator(uint8_t value);
void compareValueToAccumulator(uint8_t value);
void rotateAccumulatorLeft();
void rotateAccumulatorRight();
void rotateAccumulatorLeftWithCarry();
void rotateAccumulatorRightWithCarry();
vector<uint8_t *> * registerPairFromOpCode(uint8_t opCode);
void pushRegisterPairOnStack(vector<uint8_t *> * pair);
void popStackToRegisterPair(vector<uint8_t *> * pair);
void popStackToAccumulatorAndStatusPair();
void setStatusRegister(uint8_t value);
uint16_t valueOfRegisterPair(vector<uint8_t *> * pair);
void addValueToRegisterPairH(uint16_t value);
void incrementRegisterPair(vector<uint8_t *> * pair);
void decrementRegisterPair(vector<uint8_t *> * pair);
void exchangeRegisterPairs(vector<uint8_t *> * p1, vector<uint8_t *> * p2);
void exchangeRegistersAndMemory();
void handle3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes);
void replaceRegisterPair(vector<uint8_t *> * pair, uint8_t highBytes, uint8_t lowBytes);
void handle2ByteOp(uint8_t opCode, uint8_t value);
uint16_t handleJumpByteOp();
uint16_t handleJump3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes);
uint16_t handleCall3ByteOp(uint8_t opCode, uint8_t lowBytes, uint8_t highBytes);
void push2ByteValueOnStack(uint16_t value);
uint16_t performCallOperation(uint16_t memoryOffset);
uint16_t handleReturnOp(uint8_t opCode);
uint16_t pop2ByteValueFromStack();
void handleNextInstruction();
void handleInputFromPort(uint8_t portAddress);
void handleOutputToPort(uint8_t portAddress);
};
#endif
|
1d7d99edd5b151b2914c143b774fef9ea466efc0
|
[
"Makefile",
"C",
"Text",
"C++"
] | 34
|
C++
|
hushlorentz/8080_emu
|
540091c1a5bccd4d3740e86313ddce53105a38f9
|
91a78ee33898cbcbe92710a4059325299b221dc5
|
refs/heads/master
|
<repo_name>rinuthomaz/Bale-Back<file_sep>/src/main/java/com/wm/brta/service/SupplierService.java
package com.wm.brta.service;
import java.util.HashSet;
import com.wm.brta.domain.Customer;
import com.wm.brta.domain.Supplier;
import com.wm.brta.domain.SupplierSite;
public interface SupplierService
{
public HashSet<Supplier>getAllSuppliersByBuyCustomer(Customer customer);
public HashSet<SupplierSite> getAllSupplierSitesBySupplier(Supplier supplier);
}
<file_sep>/src/main/webapp/resources/js/angular/app/storemanagement.js
brtaApp
.controller(
"storeManagementController",
function(applicationContextURL, $scope, $rootScope, $http,
$filter, userService, customerService, supplierService,
balepickupService, storeConfigService,
pickupAssignmentService) {
$scope.storeFilteredItems=[];
$scope.storeListView = true;
$scope.storeListCheckAllBtn=true;
$scope.storeListAllAssignBtn=true;
$scope.setFrequencyPopup = false;
$scope.loaderActiveStoreManagement = false;
$scope.loaderActiveActivityList = false;
$scope.supplierSite = {};
$scope.material = {};
$scope.setFrequencyBtn = true;
$scope.setDataApplyBtn= true;
$scope.assignBtn = true;
$scope.assignActivityPopupBtn = true;
$scope.storeListViewBtn = true;
$scope.assignActivityBtn = true;
customerService.getAllBuyCustomers().then(
function(response) {
$scope.buyCustomers = response;
$rootScope.buyCustomers=response;
});
customerService.getAllSuppliersWithBuyCustomer().then(
function(response) {
$scope.suppliersForCustomerSelected=[];
$scope.suppliersWithCustomer = response;
angular.forEach($scope.suppliersWithCustomer, function(value, key) {
$scope.suppliersForCustomerSelected.push(value);
$scope.suppliersForCustomerSelected=[].concat.apply([], $scope.suppliersForCustomerSelected);
$rootScope.allSuppliers=$scope.suppliersForCustomerSelected;
});
});
$scope.getBuyCustomerDetails = function(buyCustomer) {
$scope.loaderStoreListView = true;
$scope.loaderAssignActivity = true;
$scope.dropdown.errorDropDownVendorFlag = false;
if(buyCustomer != null){
if($scope.suppliersWithCustomer != undefined){
angular.forEach($scope.suppliersWithCustomer, function(value, key) {
if(key == buyCustomer.customerId){
$scope.suppliersForCustomerSelected= value;
}
});
} else{
customerService.getAllSuppliersWithBuyCustomer().then(
function(response) {
$scope.suppliersWithCustomer = response;
angular.forEach($scope.suppliersWithCustomer, function(value, key) {
if(key == buyCustomer.customerId){
$scope.suppliersForCustomerSelected= value;
}
});
});
}
}else{
$scope.suppliersForCustomerSelected=$rootScope.allSuppliers;
}
$scope.loaderStoreListView = false;
$scope.loaderAssignActivity = false;
}
$scope.selectedCustomerSites = [];
$scope.addToSelectedCustomerSites = function(customerSite) {
if (customerSite.checked){
$scope.selectedCustomerSites.push(customerSite);
$scope.setFrequencyBtn= false;
}
else if($scope.selectall == true){
$scope.selectedCustomerSites.splice(
$scope.selectedCustomerSites
.indexOf(customerSite), 1);
$scope.setFrequencyBtn= false;
}else{
$scope.selectedCustomerSites.splice(
$scope.selectedCustomerSites
.indexOf(customerSite), 1);
$scope.setFrequencyBtn=true;
}
}
$scope.getAllUsersForSupplier = function() {
userService.getAllUsersForSupplierSite(
$scope.supplierSelectedAct).then(
function(response) {
$scope.drivers = response;
})
}
/*$scope.week1 = {};
$scope.week2 = {};
$scope.week3 = {};
$scope.week4 = {};
$scope.week5 = {};*/
$scope.day = {};
$scope.day.weeklymon = false;
$scope.day.weeklytue = false;
$scope.day.weeklywed = false;
$scope.day.weeklythu = false;
$scope.day.weeklyfri = false;
$scope.day.weeklysat = false;
$scope.day.weeklysun = false;
/*
* $scope.frequency =
* {"week1":{"day1":false,"day2":false,"day3":false,"day4":false,"day5":false,"day6":false,"day7":false},
* "week2":{"day1":false,"day2":false,"day3":false,"day4":false,"day5":false,"day6":false,"day7":false},
* "week3":{"day1":false,"day2":false,"day3":false,"day4":false,"day5":false,"day6":false,"day7":false},
* "week4":{"day1":false,"day2":false,"day3":false,"day4":false,"day5":false,"day6":false,"day7":false},
* "week5":{"day1":false,"day2":false,"day3":false,"day4":false,"day5":false,"day6":false,"day7":false} }
*/
$scope.dropdown = {};
$scope.errorDropdown = false;
$scope.checkAssignDataPopupBtn = function() {
if (($scope.popParams.driverSelectedinPopup != undefined)
&& ($scope.popParams.destinatonSelectedinPopup != undefined)
&& ($scope.popParams.destinatonSiteSelectedinPopup != undefined)) {
$scope.assignActivityPopupBtn = false;
}else if(($scope.popParams.driverSelectedinPopup == undefined)
|| ($scope.popParams.destinatonSelectedinPopup == undefined)
|| ($scope.popParams.destinatonSiteSelectedinPopup == undefined)){
$scope.assignActivityPopupBtn = true;
}
}
$scope.setSupplierSiteValue = [];
$scope.setMaterialValue = [];
$scope.checkSetDataPopupBtn = function() {
if (($scope.setDatapopup.supplierSiteSelected != undefined && $scope.setDatapopup.supplierSiteSelected.length > 0)
&& ($scope.setDatapopup.materialSelected != undefined && $scope.setDatapopup.materialSelected.length > 0)
&& ($scope.setDatapopup.balePickupStartDate != undefined)) {
var btnName = "setDataApplyBtn_"
+ $scope.customerSiteIdForBtn
$scope[btnName] = false;
}else if(($scope.setDatapopup.supplierSiteSelected == undefined || $scope.setDatapopup.supplierSiteSelected.length == 0)
|| ($scope.setDatapopup.materialSelected == undefined || $scope.setDatapopup.materialSelected.length == 0)
|| ($scope.setDatapopup.balePickupStartDate = undefined)){
var btnName = "setDataApplyBtn_"
+ $scope.customerSiteIdForBtn
$scope[btnName] = true;
}
}
$scope.checkStoreListViewBtn = function() {
if (($scope.buyCustomerSelected != undefined)
&& ($scope.supplierSelected != undefined)) {
$scope.storeListViewBtn = false;
}
}
$scope.checkAssignActivitySubmitBtn = function() {
if (($scope.buyCustomerSelectedAct != undefined)
&& ($scope.supplierSelectedAct != undefined)) {
$scope.assignActivityBtn = false;
// $scope.assignBtn = false;
}
}
$scope.getCustomerSites = function(buyCustomer, supplier,states) {
$scope.loaderActiveStoreManagement = true;
$scope.setFrequencyBtn = true;
$scope.selectall == false;
$scope.storeListCheckAllBtn=true;
var storeDto={};
storeDto.buyCustomer=buyCustomer;
storeDto.state=states;
customerService.getCustomerSitesForBuyCustomer(storeDto).then(function(response) {
$scope.loaderActiveStoreManagement = false;
$scope.storeListCheckAllBtn=false;
$scope.customerSites = response;
});
supplierService.getAllSupplierSites(supplier).then(
function(response) {
$scope.supplierSites = response;
});
customerService.getMatrialsForBuyCustomer(buyCustomer)
.then(function(response) {
$scope.materials = response;
})
}
$scope.pageSize = 10;
$scope.currentPage = 1;
$scope.pageChangeHandlerStore = function(num) {
$scope.currentPage = num;
$scope.selectall=false;
};
$scope.addresses = [
{'state':'AL'},
{'state':'AK'},
{'state':'AZ'},
{'state':'AR'},
{'state':'CA'},
{'state':'CO'},
{'state':'CT'},
{'state':'DE'},
{'state':'FL'},
{'state':'GA'},
{'state':'HI'},
{'state':'ID'},
{'state':'IL'},
{'state':'IN'},
{'state':'IA'},
{'state':'KS'},
{'state':'KY'},
{'state':'LA'},
{'state':'ME'},
{'state':'MD'},
{'state':'MA'},
{'state':'MI'},
{'state':'MN'},
{'state':'MS'},
{'state':'MO'},
{'state':'MT'},
{'state':'NE'},
{'state':'NV'},
{'state':'NH'},
{'state':'NJ'},
{'state':'NM'},
{'state':'NY'},
{'state':'NC'},
{'state':'ND'},
{'state':'OH'},
{'state':'OK'},
{'state':'OR'},
{'state':'PA'},
{'state':'RI'},
{'state':'SC'},
{'state':'SD'},
{'state':'TN'},
{'state':'TX'},
{'state':'UT'},
{'state':'VT'},
{'state':'VA'},
{'state':'WA'},
{'state':'WV'},
{'state':'WI'},
{'state':'WY'}
];
$scope.lov_state = [
{'lookupCode':'AL', 'description': 'Alabama - AL'},
{'lookupCode':'AK', 'description': 'Alaska - AK'},
{'lookupCode':'AZ', 'description': 'Arizona - AZ'},
{'lookupCode':'AR', 'description': 'Arkansas - AR'},
{'lookupCode':'CA', 'description': 'California - CA'},
{'lookupCode':'CO', 'description': 'Colorado - CO'},
{'lookupCode':'CT', 'description': 'Connecticut - CT'},
{'lookupCode':'DE', 'description': 'Delaware - DE'},
{'lookupCode':'FL', 'description': 'Florida - FL'},
{'lookupCode':'GA', 'description': 'Georgia - GA'},
{'lookupCode':'HI', 'description': 'Hawaii - HI'},
{'lookupCode':'ID', 'description': 'Idaho - ID'},
{'lookupCode':'IL', 'description': 'Illinois - IL'},
{'lookupCode':'IN', 'description': 'Indiana - IN'},
{'lookupCode':'IA', 'description': 'Iowa - IA'},
{'lookupCode':'KS', 'description': 'Kansas - KS'},
{'lookupCode':'KY', 'description': 'Kentucky - KY'},
{'lookupCode':'LA', 'description': 'Louisiana - LA'},
{'lookupCode':'ME', 'description': 'Maine - ME'},
{'lookupCode':'MD', 'description': 'Maryland - MD'},
{'lookupCode':'MA', 'description': 'Massachusetts - MA'},
{'lookupCode':'MI', 'description': 'Michigan - MI'},
{'lookupCode':'MN', 'description': 'Minnesota - MN'},
{'lookupCode':'MS', 'description': 'Mississippi - MS'},
{'lookupCode':'MO', 'description': 'Missouri - MO'},
{'lookupCode':'MT', 'description': 'Montana - MT'},
{'lookupCode':'NE', 'description': 'Nebraska - NE'},
{'lookupCode':'NV', 'description': 'Nevada - NV'},
{'lookupCode':'NH', 'description': 'New Hampshire - NH'},
{'lookupCode':'NJ', 'description': 'New Jersey - NJ'},
{'lookupCode':'NM', 'description': 'New Mexico - NM'},
{'lookupCode':'NY', 'description': 'New York - NY'},
{'lookupCode':'NC', 'description': 'North Carolina - NC'},
{'lookupCode':'ND', 'description': 'North Dakota - ND'},
{'lookupCode':'OH', 'description': 'Ohio - OH'},
{'lookupCode':'OK', 'description': 'Oklahoma - OK'},
{'lookupCode':'OR', 'description': 'Oregon - OR'},
{'lookupCode':'PA', 'description': 'Pennsylvania - PA'},
{'lookupCode':'RI', 'description': 'Rhode Island - RI'},
{'lookupCode':'SC', 'description': 'South Carolina - SC'},
{'lookupCode':'SD', 'description': 'South Dakota - SD'},
{'lookupCode':'TN', 'description': 'Tennessee - TN'},
{'lookupCode':'TX', 'description': 'Texas - TX'},
{'lookupCode':'UT', 'description': 'Utah - UT'},
{'lookupCode':'VT', 'description': 'Vermont - VT'},
{'lookupCode':'VA', 'description': 'Virginia - VA'},
{'lookupCode':'WA', 'description': 'Washington - WA'},
{'lookupCode':'WV', 'description': 'West Virginia - WV'},
{'lookupCode':'WI', 'description': 'Wisconsin - WI'},
{'lookupCode':'WY', 'description': 'Wyoming - WY'}
];
$scope.checkAll = function() {
console.log("===value==="+$scope.searchTextStoreManagementGrid);
console.log("===hello====="+$scope.storeFilteredItems.length);
$scope.customerSitesSorted =[];
if($scope.searchTextStoreManagementGrid != undefined && $scope.searchTextStoreManagementGrid != ''){
$scope.customerSitesSorted = $filter('orderBy')(
$scope.storeFilteredItems, 'siteName');
}else{
$scope.customerSitesSorted = $filter('orderBy')(
$scope.customerSites, 'siteName');
}
var customerSiteLength=customerSiteLength=$scope.customerSitesSorted.length;
var startRange = ($scope.currentPage - 1) * 10;
var endRange = ($scope.currentPage) * 10
if(endRange >= customerSiteLength){
endRange= customerSiteLength;
}
for (var i = 0; i < $scope.customerSitesSorted.length; i++) {
if ((i >= ($scope.currentPage - 1) * 10)
&& (i < ($scope.currentPage * 10))) {
if ($scope.selectall == true) {
$scope.setFrequencyBtn= false;
if($scope.customerSitesSorted[i].balePickupStartDate !=null
&& $scope.customerSitesSorted[i].configuredSupplierSites !=''
&& $scope.customerSitesSorted[i].configuredSupplierSites !='' ){
$scope.customerSitesSorted[i].checked = true;
$scope.addToSelectedCustomerSites($scope.customerSitesSorted[i]);
}
} else {
$scope.customerSitesSorted[i].checked = false;
$scope.selectall = false;
$scope.setFrequencyBtn= true;
$scope.addToSelectedCustomerSites($scope.customerSitesSorted[i]);
}
}
}
console.log("===length===="+JSON.stringify($scope.selectedCustomerSites.length));
$scope.selectedCustomerSites=$scope.removeDuplicateObj($scope.selectedCustomerSites,"customerSiteId");
console.log("===length===="+JSON.stringify($scope.selectedCustomerSites.length));
};
$scope.removeDuplicateObj= function(collection,keyname){
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
}
$scope.pageSize = 10;
$scope.currentPageAssign = 1;
$scope.pageChangeHandlerAssign = function(numa) {
$scope.currentPageAssign = numa;
};
$scope.checkAllAssign = function() {
// console.log("===valuegrid===="+$scope.searchTextActivityGrid);
// console.log("===hello====="+$scope.assignFilteredItems.length);
$scope.baleAssignmentsSortedAssign =[];
if($scope.searchTextActivityGrid != undefined && $scope.searchTextActivityGrid != ''){
$scope.baleAssignmentsSortedAssign = $filter('orderBy')(
$scope.assignFilteredItems, 'buyCustomerSite.siteName');
}else{
$scope.baleAssignmentsSortedAssign = $filter('orderBy')(
$scope.baleAssignments, 'buyCustomerSite.siteName');
}
var baleAssignmentsSortedLength = $scope.baleAssignmentsSortedAssign.length;
var start=($scope.currentPageAssign - 1) * 10;
var end = ($scope.currentPageAssign) * 10;
if(end >= baleAssignmentsSortedLength){
end= baleAssignmentsSortedLength;
}
for (var i = 0; i < $scope.baleAssignmentsSortedAssign.length; i++) {
if ((i >= start)
&& (i < end)) {
if ($scope.selectallassign == true) {
$scope.baleAssignmentsSortedAssign[i].checked = true;
$scope.assignBtn=false;
$scope.addToAssignmentList($scope.baleAssignmentsSortedAssign[i]);
} else {
$scope.baleAssignmentsSortedAssign[i].checked = false;
$scope.selectallassign = false;
$scope.assignBtn= true;
$scope.addToAssignmentList($scope.baleAssignmentsSortedAssign[i]);
}
}
}
console.log("===length===="+JSON.stringify($scope.assignmentList.length));
// console.log("===objects coming first console===="+JSON.stringify($scope.assignmentList));
$scope.assignmentList=$scope.removeDuplicates($scope.assignmentList,"balePickupAssignmentId");
console.log("===length===="+JSON.stringify($scope.assignmentList.length));
// console.log("===objects coming last console===="+JSON.stringify($scope.assignmentList));
};
$scope.removeDuplicates= function(data,value){
var assign = [],
assignmentkeys = [];
angular.forEach(data, function(item) {
var key = item[value];
if(assignmentkeys.indexOf(key) === -1) {
assignmentkeys.push(key);
assign.push(item);
}
});
return assign;
}
$scope.frequency = {};
$scope.generateFrequeny = function() {
$scope.listOfAssignments = [];
$scope.customerSiteIdList=[];
angular
.forEach(
$scope.selectedCustomerSites,
function(value, key) {
$scope.customerSiteIdList.push(value.customerSiteId);
if ($scope.frequency.weeklySelected == true) {
var weeklySelected = $scope.frequency.weekly
var weeklySelectedDays = [];
for ( var key in weeklySelected) {
if (weeklySelected[key] == false) {
delete weeklySelected[key]
}
}
weeklySelectedDays = Object
.keys(weeklySelected);
for (var k = 0; k < weeklySelectedDays.length; k++) {
for (var i = 1; i <= 5; i++) {
var assignment = {};
assignment.weekNumber = i;
assignment.frequency = 1;
assignment.day = weeklySelectedDays[k];
assignment.buyCustomerSite = value;
assignment.supplier = $scope.supplierSelected;
$scope.listOfAssignments
.push(assignment);
}
}
}
if ($scope.frequency.monthlySelected == true) {
var monthlySelected = $scope.frequency.monthlySelected
if ($scope.frequency.monthWeek1Selected == true) {
if ($scope.frequency.monthWeek1 != undefined) {
var weeklySelectedDays = $scope
.getSelectedDays($scope.frequency.monthWeek1);
$scope
.createAssignmentObj(
weeklySelectedDays,
1, 2,
value)
}
}
if ($scope.frequency.monthWeek2Selected == true) {
var weeklySelectedDays = $scope
.getSelectedDays($scope.frequency.monthWeek2);
$scope.createAssignmentObj(
weeklySelectedDays,
2, 2, value)
}
if ($scope.frequency.monthWeek3Selected == true) {
var weeklySelectedDays = $scope
.getSelectedDays($scope.frequency.monthWeek3);
$scope.createAssignmentObj(
weeklySelectedDays,
3, 2, value)
}
if ($scope.frequency.monthWeek4Selected == true) {
var weeklySelectedDays = $scope
.getSelectedDays($scope.frequency.monthWeek4);
$scope.createAssignmentObj(
weeklySelectedDays,
4, 2, value)
}
if ($scope.frequency.monthWeek5Selected == true) {
var weeklySelectedDays = $scope
.getSelectedDays($scope.frequency.monthWeek5);
$scope.createAssignmentObj(
weeklySelectedDays,
5, 2, value)
}
}
if ($scope.frequency.oncall) {
var assignment = {};
assignment.weekNumber = -1;
assignment.frequency = 3;
assignment.day = -1;
assignment.buyCustomerSite = value;
assignment.supplier = $scope.supplierSelected;
$scope.listOfAssignments
.push(assignment);
}
});
var balePickupAssignmentDTO = {};
if ($scope.editOperation == true) {
balePickupAssignmentDTO.action = "delete";
balePickupAssignmentDTO.oldAssignments = $scope.balePickupAssignments;
balePickupAssignmentDTO.assignments = $scope.listOfAssignments;
balePickupAssignmentDTO.customerSiteIdList = $scope.customerSiteIdList;
} else if ($scope.editOperation == false
|| $scope.editOperation == undefined) {
balePickupAssignmentDTO.assignments = $scope.listOfAssignments;
balePickupAssignmentDTO.action = "set";
balePickupAssignmentDTO.oldAssignments = [];
balePickupAssignmentDTO.customerSiteIdList = $scope.customerSiteIdList;
}
pickupAssignmentService
.addAssignmentList(balePickupAssignmentDTO)
.then(
function(response) {
$scope.setFrequencyclose();
$scope.showAddFrequencySuccessMessage = true;
$scope.getCustomerSites(
$scope.buyCustomerSelected,
$scope.supplierSelected);
});
}
$scope.getSelectedDays = function(selectedDays) {
var weeklySelectedDays = [];
for ( var key in selectedDays) {
if (selectedDays[key] == false) {
delete selectedDays[key]
}
}
weeklySelectedDays = Object.keys(selectedDays);
return weeklySelectedDays;
}
$scope.createAssignmentObj = function(weeklySelectedDays,
weekNo, frequency, buyCustomerSite) {
for (var k = 0; k < weeklySelectedDays.length; k++) {
var assignment = {};
assignment.weekNumber = weekNo;
assignment.frequency = frequency;
assignment.day = weeklySelectedDays[k];
assignment.buyCustomerSite = buyCustomerSite;
assignment.supplier = $scope.supplierSelected;
$scope.listOfAssignments.push(assignment);
}
}
$scope.editConfigurationData = function(customerSite) {
/*
* angular.forEach(customerSite.configuredSuppliers,function(value,key){
* })
*/
}
$scope.balePickUpSupplierSiteConfig = {};
$scope.balePickUpMaterialConfig = {}
$scope.setDatapopup = {};
$scope.applyConfigurationData = function() {
/* $rootScope.BodyOverflow = false; */
var configData = {}
var supplierSite = {};
$scope.balePickupSupplierSiteConfigList = [];
$scope.materialConfigList = [];
$scope.error = {};
$scope.errorPopupFlag = false;
if ($scope.setDatapopup.balePickupStartDate == undefined
|| $scope.setDatapopup.balePickupStartDate == null
|| $scope.setDatapopup.balePickupStartDate == "") {
$scope.error.errorDateFlag = true;
$scope.errorPopupFlag = true;
}
if ($scope.setDatapopup.supplierSiteSelected == undefined
|| $scope.setDatapopup.supplierSiteSelected == null
|| $scope.setDatapopup.supplierSiteSelected == "") {
$scope.error.errorServiceProviderFlag = true;
$scope.errorPopupFlag = true;
}
if ($scope.setDatapopup.materialSelected == undefined
|| $scope.setDatapopup.materialSelected == null
|| $scope.setDatapopup.materialSelected == "") {
$scope.error.errorMaterialFlag = true;
$scope.errorPopupFlag = true;
}
if (!$scope.errorPopupFlag) {
$scope.error.errorDateFlag = false;
$scope.error.errorServiceProviderFlag = false;
$scope.error.errorMaterialFlag = false;
$scope.setDatapopup.balePickupStartDate = $filter(
'date')
(
new Date(
$scope.setDatapopup.balePickupStartDate),
'MM-dd-yyyy')
for (var i = 0; i < $scope.setDatapopup.supplierSiteSelected.length; i++) {
$scope.balePickUpSupplierSiteConfig = {};
$scope.balePickUpSupplierSiteConfig.supplierSite = $scope.setDatapopup.supplierSiteSelected[i];
$scope.customerSite.balePickupStartDate = new Date(
$scope.setDatapopup.balePickupStartDate);
$scope.balePickUpSupplierSiteConfig.customerSite = $scope.customerSite;
$scope.balePickUpSupplierSiteConfig.customerSite.buyCustomerSiteId = $scope.customerSite.customerSiteId;
$scope.balePickupSupplierSiteConfigList
.push($scope.balePickUpSupplierSiteConfig);
}
for (var i = 0; i < $scope.setDatapopup.materialSelected.length; i++) {
$scope.balePickUpMaterialConfig = {};
$scope.balePickUpMaterialConfig.material = $scope.setDatapopup.materialSelected[i];
$scope.balePickUpMaterialConfig.customerSite = $scope.customerSite;
$scope.balePickUpMaterialConfig.avgBaleWeight = $scope.setDatapopup.materialSelected[i].avgBaleWeight;
$scope.balePickUpMaterialConfig.customerSite.buyCustomerSiteId = $scope.customerSite.customerSiteId;
$scope.materialConfigList
.push($scope.balePickUpMaterialConfig);
}
configData.supplierSiteConfig = $scope.balePickupSupplierSiteConfigList;
configData.materialConfig = $scope.materialConfigList;
configData.editAction = $scope.editAction;
storeConfigService
.addConfigurationData(configData)
.then(
function(response) {
$scope.setDatapopup.materialSelected = [];
$scope.setDatapopup.supplierSiteSelected = [];
$scope.setDataPopupContentClose();
$scope.showAddDataSuccessMessage = true;
$scope.getCustomerSites(
$scope.buyCustomerSelected,
$scope.supplierSelected);
})
}
}
$scope.setFrequency = function() {
$scope.setFrequencyPopupContent = true;
};
$scope.setfrequencyPopupRow = function(customerSiteRow,
action) {
$scope.frequency = {};
$scope.frequency.weekly = {};
$scope.day = {};
$scope.editOperation = false;
if (action == 'set') {
$scope.setFrequencyPopupContent = true;
$scope.customerSiteRow = customerSiteRow;
$scope.selectedCustomerSites = [];
$scope.selectedCustomerSites.push(customerSiteRow);
}
if (action == 'edit') {
$scope.editOperation = true;
$scope.customerSiteRow = customerSiteRow;
$scope.selectedCustomerSites = [];
$scope.selectedCustomerSites.push(customerSiteRow);
$scope.frequency.weekly = {};
$scope.frequency.monthWeek1Selected = {};
$scope.frequency.monthWeek2Selected = {};
$scope.frequency.monthWeek3Selected = {};
$scope.frequency.monthWeek4Selected = {};
$scope.frequency.monthWeek5Selected = {};
$scope.frequency.monthWeek1 = {};
$scope.frequency.monthWeek2 = {};
$scope.frequency.monthWeek3 = {};
$scope.frequency.monthWeek4 = {};
$scope.frequency.monthWeek5 = {};
pickupAssignmentService
.getAssignmentsByCustomerSite(
customerSiteRow)
.then(
function(response) {
balePickupAssignments = response.data;
$scope.balePickupAssignments = balePickupAssignments;
angular
.forEach(
balePickupAssignments,
function(value,
key) {
if (value.frequency == 1) {
$scope.frequency.weeklySelected = true;
if (value.day == 1) {
$scope.frequency.weekly[1] = true;
}
if (value.day == 2) {
$scope.frequency.weekly[2] = true;
}
if (value.day == 3) {
$scope.frequency.weekly[3] = true;
}
if (value.day == 4) {
$scope.frequency.weekly[4] = true;
}
if (value.day == 5) {
$scope.frequency.weekly[5] = true;
}
if (value.day == 6) {
$scope.frequency.weekly[6] = true;
}
if (value.day == 7) {
$scope.frequency.weekly[7] = true;
}
}
if (value.frequency == 2) {
$scope.frequency.monthlySelected = true;
if (value.weekNumber == 1
&& value.day == 1) {
$scope.frequency.monthWeek1Selected = true;
$scope.frequency.monthWeek1[1] = true;
}
if (value.weekNumber == 1
&& value.day == 2) {
$scope.frequency.monthWeek1Selected = true;
$scope.frequency.monthWeek1[2] = true;
}
if (value.weekNumber == 1
&& value.day == 3) {
$scope.frequency.monthWeek1Selected = true;
$scope.frequency.monthWeek1[3] = true;
}
if (value.weekNumber == 1
&& value.day == 4) {
$scope.frequency.monthWeek1Selected = true;
$scope.frequency.monthWeek1[4] = true;
}
if (value.weekNumber == 1
&& value.day == 5) {
$scope.frequency.monthWeek1Selected = true;
$scope.frequency.monthWeek1[5] = true;
}
if (value.weekNumber == 1
&& value.day == 6) {
$scope.frequency.monthWeek1Selected = true;
// $scope.frequency.monthly.monthWeek1[5]
// =
// true;
$scope.frequency.monthWeek1[6] = true;
}
if (value.weekNumber == 1
&& value.day == 7) {
$scope.frequency.monthWeek1Selected = true;
// $scope.frequency.monthly.monthWeek1[7]
// =
// true;
$scope.frequency.monthWeek1[7] = true;
}
// Week
// 2
if (value.weekNumber == 2
&& value.day == 1) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[1]=
// true;
$scope.frequency.monthWeek2[1] = true;
}
if (value.weekNumber == 2
&& value.day == 2) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[2]
// =
// true;
$scope.frequency.monthWeek2[2] = true;
}
if (value.weekNumber == 2
&& value.day == 3) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[3]
// =
// true;
$scope.frequency.monthWeek2[3] = true;
}
if (value.weekNumber == 2
&& value.day == 4) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[4]
// =
// true;
$scope.frequency.monthWeek2[4] = true;
}
if (value.weekNumber == 2
&& value.day == 5) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[5]
// =
// true;
$scope.frequency.monthWeek2[5] = true;
}
if (value.weekNumber == 2
&& value.day == 6) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[6]
// =
// true;
$scope.frequency.monthWeek2[6] = true;
}
if (value.weekNumber == 2
&& value.day == 7) {
$scope.frequency.monthWeek2Selected = true;
// $scope.frequency.monthly.monthWeek2[7]=
// true;
$scope.frequency.monthWeek2[7] = true;
}
// Week
// 3
if (value.weekNumber == 3
&& value.day == 1) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[1] = true;
}
if (value.weekNumber == 3
&& value.day == 2) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[2] = true;
}
if (value.weekNumber == 3
&& value.day == 3) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[3] = true;
}
if (value.weekNumber == 3
&& value.day == 4) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[4] = true;
}
if (value.weekNumber == 3
&& value.day == 5) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[5] = true;
}
if (value.weekNumber == 3
&& value.day == 6) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[6] = true;
}
if (value.weekNumber == 3
&& value.day == 7) {
$scope.frequency.monthWeek3Selected = true;
$scope.frequency.monthWeek3[7] = true;
}
// Week4
if (value.weekNumber == 4
&& value.day == 1) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[1] = true;
}
if (value.weekNumber == 4
&& value.day == 2) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[2] = true;
}
if (value.weekNumber == 4
&& value.day == 3) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[3] = true;
}
if (value.weekNumber == 4
&& value.day == 4) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[4] = true;
}
if (value.weekNumber == 4
&& value.day == 5) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[5] = true;
}
if (value.weekNumber == 4
&& value.day == 6) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[6] = true;
}
if (value.weekNumber == 4
&& value.day == 7) {
$scope.frequency.monthWeek4Selected = true;
$scope.frequency.monthWeek4[7] = true;
}
// Week5
if (value.weekNumber == 5
&& value.day == 1) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[1] = true;
}
if (value.weekNumber == 5
&& value.day == 2) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[2] = true;
}
if (value.weekNumber == 5
&& value.day == 3) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[3] = true;
}
if (value.weekNumber == 5
&& value.day == 4) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[4] = true;
}
if (value.weekNumber == 5
&& value.day == 5) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[5] = true;
}
if (value.weekNumber == 5
&& value.day == 6) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[6] = true;
}
if (value.weekNumber == 5
&& value.day == 7) {
$scope.frequency.monthWeek5Selected = true;
$scope.frequency.monthWeek5[7] = true;
}
}
if (value.frequency == 3) {
$scope.frequency.oncall = true;
}
})
});
$scope.setFrequencyPopupContent = true;
}
}
$scope.setFrequencyDataPopup = function() {
$scope.setFrequencyPopup = true;
}
$scope.setdataPopup = function(customerSite, action) {
$rootScope.BodyOverflow = true;
$scope.customerSiteIdForBtn = customerSite.customerSiteId
var btnName = "setDataApplyBtn_"+ $scope.customerSiteIdForBtn
$scope[btnName] = true;
if (action == 'set') {
$scope.editAction = false;
}
if (action == 'edit') {
$scope.setDatapopup.balePickupStartDate = customerSite.balePickupStartDate;
$scope.editAction = true;
angular
.forEach(
$scope.supplierSites,
function(value, key) {
angular
.forEach(
customerSite.configuredSupplierSites,
function(
valueChild,
keyChild) {
if (value.siteName == valueChild) {
value.checked = true;
$scope.updateSupplierSite(value);
}
})
})
angular
.forEach(
$scope.materials,
function(value, key) {
angular
.forEach(
customerSite.configuredMaterials,
function(
valueChild,
keyChild) {
if (valueChild
.includes(value.description)) {
value.checked = true;
var init = valueChild
.indexOf('(');
var fin = valueChild
.indexOf(' lbs');
value.avgBaleWeight = valueChild
.substr(
init + 1,
fin
- init
- 1);
console
.log(value.avgBaleWeight);
$scope
.updateMaterial(value);
}
})
})
$scope.checkSetDataPopupBtn();
}
$scope.customerSite = customerSite;
$scope.setDataPopup = true;
}
$scope.setDataPopupContentClose = function() {
$rootScope.BodyOverflow = false;
angular.forEach($scope.materials, function(value, key) {
value.checked = false;
value.avgBaleWeight = "";
})
angular.forEach($scope.supplierSites, function(value,
key) {
value.checked = false;
})
$scope.setDatapopup.supplierSiteSelected = [];
$scope.setDatapopup.materialSelected = [];
$scope.setDataPopup = false; // Popup Close function
}
$scope.setfrequencyPopup = function() {
$scope.editOperation = true;
$scope.frequency = {};
$scope.day = {};
$scope.frequency.weekly = {};
$scope.frequency.monthWeek1Selected = {};
$scope.frequency.monthWeek2Selected = {};
$scope.frequency.monthWeek3Selected = {};
$scope.frequency.monthWeek4Selected = {};
$scope.frequency.monthWeek5Selected = {};
$scope.frequency.monthWeek1 = {};
$scope.frequency.monthWeek2 = {};
$scope.frequency.monthWeek3 = {};
$scope.frequency.monthWeek4 = {};
$scope.frequency.monthWeek5 = {};
$scope.setFrequencyPopupContent = true;
};
$scope.setFrequencyclose = function() {
$scope.setFrequencyPopupContent = false;
};
$scope.selectedStores = [];
$scope.toggleSelection = function toggleSelection(
customerSite) {
var idx = $scope.selectedStores.indexOf(customerSite);
// Is currently selected
if (idx > -1) {
$scope.selectedStores.splice(idx, 1);
}
// Is newly selected
else {
$scope.selectedStores.push(customerSite);
}
};
// Assign Activity
$scope.singleSelect1Value = "Select Driver Name";
$scope.showSingleSelect1 = function() {
$scope.ss3 = false;
$scope.ss2 = false;
$scope.ss1 = !$scope.ss1;
}
$scope.singleChange = function(singleSelect1) {
$scope.singleSelect1Value = singleSelect1;
}
$scope.singlecustomerValue = "Select Sell Customer";
$scope.showSinglecustomer = function() {
$scope.ss1 = false;
$scope.ss3 = false;
$scope.ss2 = !$scope.ss2;
}
$scope.singleChangeoncustomer = function(customerlist) {
$scope.singlecustomerValue = customerlist;
}
$scope.singledestinationValue = "Select Destination";
$scope.selectdestination = function() {
$scope.ss1 = false;
$scope.ss2 = false;
$scope.ss3 = !$scope.ss3;
}
$scope.selectdestinationpart = function(destination) {
$scope.singledestinationValue = destination;
}
$scope.assignactivity = function() {
$scope.ss1 = false;
$scope.ss2 = false;
$scope.ss3 = false;
$scope.AssignActivityPopup = true;
}
$scope.assignactivityclose = function() {
$scope.AssignActivityPopup = false;
}
$scope.setFrequencyNumber = function(number) {
if (number == 1) {
$scope.frequency.monthly = undefined;
$scope.frequency.oncall = undefined;
}
else if (number == 2) {
$scope.frequency.weeklyfilter = undefined;
$scope.frequency.oncall = undefined;
} else if (number == 3) {
$scope.frequency.oncall = {
"3" : true
};
$scope.frequency.weeklyfilter = undefined;
$scope.frequency.monthly = undefined;
}
}
$scope.getAllAssignmentsWithFilters = function() {
$scope.showSuccessMessageActivity = false;
$scope.dropdown.errorDropDownAssignVendorFlag = false;
$scope.assignBtn = true;
$scope.storeListAllAssignBtn=true;
$scope.dropdown = {};
$scope.loaderActiveActivityList = true;
if ($scope.frequency != undefined) {
var weekly = $scope.frequency.weeklyfilter
var monthly =$scope.frequency.monthly
var oncall = $scope.frequency.oncall
var dayList = [];
var monthWeekList = [];
if (weekly != undefined) {
var frequency = '1';
for ( var key in weekly) {
if (weeklyfilter[key] == false) {
delete weekly[key]
}
}
dayList = Object.keys(weeklyfilter);
} else if (monthly != undefined) {
var frequency = '2';
for ( var key in monthly) {
if (monthly[key] == false) {
delete monthly[key]
}
}
monthWeekList = Object.keys(monthly);
} else if (oncall != undefined) {
var frequency = '3';
}
}
var assignmentFilterDTO = {};
assignmentFilterDTO.buyCustomer = $scope.buyCustomerSelectedAct;
assignmentFilterDTO.supplier = $scope.supplierSelectedAct;
assignmentFilterDTO.user = $scope.driverSelected;
assignmentFilterDTO.destination = $scope.destinatonSelected;
assignmentFilterDTO.frequency = frequency;
assignmentFilterDTO.dayList = dayList;
assignmentFilterDTO.monthWeekList = monthWeekList;
assignmentFilterDTO.state= $scope.state;
pickupAssignmentService.getAllAssignments(
assignmentFilterDTO).then(function(response) {
$scope.baleAssignments = response.data;
$scope.loaderActiveActivityList = false;
$scope.storeListAllAssignBtn=false;
})
}
$scope.assignmentList = [];
$scope.addToAssignmentList = function(assignment) {
console.log("==assignment==="+JSON.stringify(assignment))
if (assignment.checked) {
$scope.assignmentList.push(assignment);
$scope.assignBtn= false;
} else if($scope.selectallassign == true){
$scope.assignmentList.splice($scope.assignmentList
.indexOf(assignment), 1)
$scope.assignBtn= false;
}else{
$scope.assignmentList.splice($scope.assignmentList
.indexOf(assignment), 1)
$scope.assignBtn= true;
}
}
$scope.popParams = {};
$scope.getDestinationSites = function() {
$scope.loaderActiveActivityList = true;
customerService
.getCustomerSitesForBuyCustomer(
$scope.popParams.destinatonSelectedinPopup)
.then(
function(response) {
$scope.destinationSitesForDestinationSelected = response;
$scope.loaderActiveActivityList = false;
});
}
$scope.updateFieldsForAssignActivity = function() {
$scope.errorAssignPopup = {};
$scope.errorAssignPopupFlag = false;
if ($scope.popParams.driverSelectedinPopup == undefined
|| $scope.popParams.driverSelectedinPopup == null
|| $scope.popParams.driverSelectedinPopup == "") {
$scope.errorAssignPopup.errorAssignDriverFlag = true;
$scope.errorAssignPopupFlag = true;
}
if ($scope.popParams.destinatonSelectedinPopup == undefined
|| $scope.popParams.destinatonSelectedinPopup == null
|| $scope.popParams.destinatonSelectedinPopup == "") {
$scope.errorAssignPopup.errorAssignSellCustomerFlag = true;
$scope.errorAssignPopupFlag = true;
console.log("------value---"+ $scope.errorAssignPopup.errorAssignSellCustomerFlag);
}
if ($scope.popParams.destinatonSiteSelectedinPopup == undefined
|| $scope.popParams.destinatonSiteSelectedinPopup == null
|| $scope.popParams.destinatonSiteSelectedinPopup == "") {
$scope.errorAssignPopup.errorAssignDestinationFlag = true;
$scope.errorAssignPopupFlag = true;
}
if (!$scope.errorAssignPopupFlag) {
$scope.errorAssignPopup.errorAssignDriverFlag = false;
$scope.errorAssignPopup.errorAssignSellCustomerFlag = false;
$scope.errorAssignPopup.errorAssignDestinationFlag = false;
angular
.forEach(
$scope.assignmentList,
function(value, key) {
value.user = $scope.popParams.driverSelectedinPopup;
value.sellCustomerSite = $scope.popParams.destinatonSiteSelectedinPopup;
})
pickupAssignmentService
.assignActivityToUser($scope.assignmentList)
.then(
function(response) {
$scope.assignactivityclose();
$scope.assignmentList = [];
$scope.showSuccessMessageActivity = true;
$scope.getAllAssignmentsWithFilters();
})
}
}
$scope.StartDateFun = function() {
$scope.StartDate.opened = true;
$scope.dateOptionsStart = {
datepickerMode : 'day',
minMode : 'day',
// maxDate: new Date(2020, 5, 22),
//minDate: new Date(2017, 4, 22),
startingDay : 1,
showWeeks : false,
formatMonth : 'MMM',
formatYear : 'yyyy',
monthColumns : 4,
}
};
$scope.StartDate = {
opened : false
};
$scope.PickupDateFun = function() {
$scope.PickupDate.opened = true;
$scope.dateOptionPickup = {
datepickerMode : 'day',
minMode : 'day',
// maxDate: new Date(2020, 5, 22),
//minDate: new Date(2017, 4, 22),
startingDay : 1,
showWeeks : false,
formatMonth : 'MMM',
formatYear : 'yyyy',
monthColumns : 4,
}
};
$scope.PickupDate = {
opened : false
};
$scope.showAssignDriverPopup = function(assignment) {
$scope.assignmentForNewDriver = assignment;
$scope.assignNewDriver = true;
$scope.otherdrivers = [];
userService
.getAllActiveUsersForSupplierSite(
$scope.supplierSelectedAct)
.then(
function(response) {
$scope.drivers = response;
angular
.forEach(
$scope.drivers,
function(value, key) {
if (assignment.user.userId != value.userId) {
$scope.otherdrivers
.push(value);
}
})
})
}
$scope.closeAssignNewDriverPopup = function() {
$scope.assignNewDriver = false;
}
$scope.addDivertedUserToAssignment = function(assignment) {
assignment.divertDate = new Date(assignment.nextPickupDate);
console.log("======"+JSON.stringify(assignment));
balepickupService.addNewDriver(assignment).then(
function() {
$scope.assignNewDriver = false;
});
}
$scope.addresses = [
{'state':'AL'},
{'state':'AK'},
{'state':'AZ'},
{'state':'AR'},
{'state':'CA'},
{'state':'CO'},
{'state':'CT'},
{'state':'DE'},
{'state':'FL'},
{'state':'GA'},
{'state':'HI'},
{'state':'ID'},
{'state':'IL'},
{'state':'IN'},
{'state':'IA'},
{'state':'KS'},
{'state':'KY'},
{'state':'LA'},
{'state':'ME'},
{'state':'MD'},
{'state':'MA'},
{'state':'MI'},
{'state':'MN'},
{'state':'MS'},
{'state':'MO'},
{'state':'MT'},
{'state':'NE'},
{'state':'NV'},
{'state':'NH'},
{'state':'NJ'},
{'state':'NM'},
{'state':'NY'},
{'state':'NC'},
{'state':'ND'},
{'state':'OH'},
{'state':'OK'},
{'state':'OR'},
{'state':'PA'},
{'state':'RI'},
{'state':'SC'},
{'state':'SD'},
{'state':'TN'},
{'state':'TX'},
{'state':'UT'},
{'state':'VT'},
{'state':'VA'},
{'state':'WA'},
{'state':'WV'},
{'state':'WI'},
{'state':'WY'}
];
$scope.lov_state = [
{'lookupCode':'AL', 'description': 'Alabama - AL'},
{'lookupCode':'AK', 'description': 'Alaska - AK'},
{'lookupCode':'AZ', 'description': 'Arizona - AZ'},
{'lookupCode':'AR', 'description': 'Arkansas - AR'},
{'lookupCode':'CA', 'description': 'California - CA'},
{'lookupCode':'CO', 'description': 'Colorado - CO'},
{'lookupCode':'CT', 'description': 'Connecticut - CT'},
{'lookupCode':'DE', 'description': 'Delaware - DE'},
{'lookupCode':'FL', 'description': 'Florida - FL'},
{'lookupCode':'GA', 'description': 'Georgia - GA'},
{'lookupCode':'HI', 'description': 'Hawaii - HI'},
{'lookupCode':'ID', 'description': 'Idaho - ID'},
{'lookupCode':'IL', 'description': 'Illinois - IL'},
{'lookupCode':'IN', 'description': 'Indiana - IN'},
{'lookupCode':'IA', 'description': 'Iowa - IA'},
{'lookupCode':'KS', 'description': 'Kansas - KS'},
{'lookupCode':'KY', 'description': 'Kentucky - KY'},
{'lookupCode':'LA', 'description': 'Louisiana - LA'},
{'lookupCode':'ME', 'description': 'Maine - ME'},
{'lookupCode':'MD', 'description': 'Maryland - MD'},
{'lookupCode':'MA', 'description': 'Massachusetts - MA'},
{'lookupCode':'MI', 'description': 'Michigan - MI'},
{'lookupCode':'MN', 'description': 'Minnesota - MN'},
{'lookupCode':'MS', 'description': 'Mississippi - MS'},
{'lookupCode':'MO', 'description': 'Missouri - MO'},
{'lookupCode':'MT', 'description': 'Montana - MT'},
{'lookupCode':'NE', 'description': 'Nebraska - NE'},
{'lookupCode':'NV', 'description': 'Nevada - NV'},
{'lookupCode':'NH', 'description': 'New Hampshire - NH'},
{'lookupCode':'NJ', 'description': 'New Jersey - NJ'},
{'lookupCode':'NM', 'description': 'New Mexico - NM'},
{'lookupCode':'NY', 'description': 'New York - NY'},
{'lookupCode':'NC', 'description': 'North Carolina - NC'},
{'lookupCode':'ND', 'description': 'North Dakota - ND'},
{'lookupCode':'OH', 'description': 'Ohio - OH'},
{'lookupCode':'OK', 'description': 'Oklahoma - OK'},
{'lookupCode':'OR', 'description': 'Oregon - OR'},
{'lookupCode':'PA', 'description': 'Pennsylvania - PA'},
{'lookupCode':'RI', 'description': 'Rhode Island - RI'},
{'lookupCode':'SC', 'description': 'South Carolina - SC'},
{'lookupCode':'SD', 'description': 'South Dakota - SD'},
{'lookupCode':'TN', 'description': 'Tennessee - TN'},
{'lookupCode':'TX', 'description': 'Texas - TX'},
{'lookupCode':'UT', 'description': 'Utah - UT'},
{'lookupCode':'VT', 'description': 'Vermont - VT'},
{'lookupCode':'VA', 'description': 'Virginia - VA'},
{'lookupCode':'WA', 'description': 'Washington - WA'},
{'lookupCode':'WV', 'description': 'West Virginia - WV'},
{'lookupCode':'WI', 'description': 'Wisconsin - WI'},
{'lookupCode':'WY', 'description': 'Wyoming - WY'}
];
/**multi select code start*/
$scope.OptionsList = [ {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.Sellcustomers = [ {
name : '<NAME>'
}, {
name : 'Dsouza Alex'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.selectdestinations = [ {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.supplierSiteCheckbox = {};
$scope.materialCheckbox = {};
$scope.setDatapopup.supplierSiteSelected = [];
$scope.setDatapopup.materialSelected = [];
$scope.supplierSiteCheckbox.siteName = "Select Supplier Site Name";
$scope.materialCheckbox.description = "Select Material Profile";
$scope.showSingleSelect1 = function() {
$scope.ss3 = false;
$scope.ss2 = false;
$scope.ss1 = !$scope.ss1;
}
$scope.singleChange = function(singleSelect1) {
$scope.singleSelect1Value = singleSelect1;
}
$scope.updateSupplierSite = function(singleSelect1) {
if (singleSelect1.checked == true) {
$scope.setDatapopup.supplierSiteSelected
.push(singleSelect1);
}
if (singleSelect1.checked == false) {
$scope.setDatapopup.supplierSiteSelected.splice(
singleSelect1, 1);
}
}
$scope.updateMaterial = function(singleSelect1) {
if (singleSelect1.checked == true) {
$scope.setDatapopup.materialSelected
.push(singleSelect1);
}
if (singleSelect1.checked == false) {
angular
.forEach(
$scope.setDatapopup.materialSelected,
function(value, key) {
if (value.materialId == singleSelect1.materialId) {
$scope.setDatapopup.materialSelected
.splice(key, 1);
}
})
}
console
.log(JSON
.stringify($scope.setDatapopup.materialSelected));
}
$scope.singlecustomerValue = "Select commodity Type";
$scope.showSinglecustomer = function() {
$scope.ss1 = false;
$scope.ss3 = false;
$scope.ss2 = !$scope.ss2;
}
$scope.singleChangeoncustomer = function(customerlist) {
$scope.singlecustomerValue = customerlist;
}
/**multi select code end**/
/**Assign popup Start**/
$scope.OptionsList = [ {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.Sellcustomers = [ {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.selectdestinations = [ {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : '<NAME> '
}, {
name : '<NAME>'
}, {
name : '<NAME>'
}, {
name : 'Option6'
}, {
name : 'Option7'
} ];
$scope.singleSelect1Value = "Select Driver Name";
$scope.showSingleSelect1 = function() {
$scope.ss3 = false;
$scope.ss2 = false;
$scope.ss1 = !$scope.ss1;
}
$scope.singleChange = function(singleSelect1) {
$scope.singleSelect1Value = singleSelect1;
}
$scope.singlecustomerValue = "Select Sell Customer";
$scope.showSinglecustomer = function() {
$scope.ss1 = false;
$scope.ss3 = false;
$scope.ss2 = !$scope.ss2;
}
$scope.singleChangeoncustomer = function(customerlist) {
$scope.singlecustomerValue = customerlist;
}
$scope.singledestinationValue = "Select Destination";
$scope.selectdestination = function() {
$scope.ss1 = false;
$scope.ss2 = false;
$scope.ss3 = !$scope.ss3;
}
$scope.selectdestinationpart = function(destination) {
$scope.singledestinationValue = destination;
}
$scope.assignactivity = function() {
$scope.popParams = {};
$scope.ss1 = false;
$scope.ss2 = false;
$scope.ss3 = false;
$scope.AssignActivityPopup = true;
}
$scope.assignactivityclose = function() {
$scope.AssignActivityPopup = false;
}
$scope.showDeleteNewDriverPopup = function(assignment) {
$scope.newDriverAssignment = assignment;
$scope.newDriverDeletePopup = true;
}
$scope.closeAssignNewDriverDeletePopup = function() {
$scope.newDriverDeletePopup = false;
}
$scope.removeDivertedUserToAssignment = function() {
balepickupService.removeNewDriver(
$scope.newDriverAssignment).then(function() {
$scope.newDriverDeletePopup = false;
$scope.getAllAssignmentsWithFilters();
});
}
});
<file_sep>/src/main/webapp/resources/js/angular/main.js
var brtaApp = angular.module('brtaApp',['ngRoute','xeditable','changeStatus','showDay','convertToString',
'ui.bootstrap','angularUtils.directives.dirPagination','angular-js-xlsx'
,'bootstrapLightbox','naif.base64','base64']).constant('applicationContextURL','/brta/app');
brtaApp.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keypress", function(e) {
if (this.value.length == limit) e.preventDefault();
});
}
}
}]);
brtaApp.directive('onlyNumeric', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
var transformedInput = text.replace(/[^0-9]/g, '');
console.log(transformedInput);
if(transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
brtaApp.service('userDetails', function($http,applicationContextURL){
return {
getLoggedInUserDetails: function(){
return $http.get(applicationContextURL+"/common/getdetails/user").
then(function(response){
console.log(JSON.stringify(response));
return response.data;
},function(errResponse){
console.error('Error while retrieving user details');
});
}
}
});
angular.module('changeStatus', []).filter('filterStatus', function() {
return function(status){
if(status==true){
return 'Active';
}
else{
return 'Inactive';
}
}
})
angular.module('showDay', []).filter('filterShowDay', function() {
return function(frequency,weekNumber,dayNumber){
console.log(dayNumber);
var str = "" ;
if(frequency==1){
str= str+'Weekly ';
str = str + 'Week '+weekNumber
}
if(frequency==2){
str = str+'Monthly ';
str = str + 'Week '+weekNumber
}
if(dayNumber==1){
return str+'Monday';
}
else if(dayNumber==2){
return str+'Tuesday';
}
else if(dayNumber==3){
return str+'Wednesday';
}
else if(dayNumber==4){
return str+'Thursday';
}
else if(dayNumber==5){
return str+'Friday';
}
else if(dayNumber==6){
return str+'Saturday';
}
else if(dayNumber==7){
return str+'Sunday';
}
}
})
angular.module('convertToString', []).filter('convertArrayToString', function() {
return function(array){
if(array!=null && array.length!=0){
return array.join(",");
}
}
})
brtaApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/users', {
templateUrl : 'views/usermanagement.html',
controller : 'userManagementController',
resolve: {
message: function(){
return 'Driver';
}
}
})
.when('/driver', {
templateUrl : 'views/usermanagement.html',
controller : 'userManagementController',
resolve: {
message: function(){
return 'Driver';
}
}
})
.when('/suppliers', {
templateUrl : 'views/usermanagement.html',
controller : 'userManagementController',
resolve: {
message: function(){
return 'Supplier';
}
}
})
.when('/incidentmanagement', {
templateUrl : 'views/incidenttypemanagement.html',
controller : 'incidentTypeManagementController'
})
.when('/storemanagement', {
templateUrl : 'views/storemanagement.html',
controller : 'storeManagementController'
})
.when('/balepickup', {
templateUrl : 'views/balepickup.html',
controller : 'balepickupController'
})
.when('/reports', {
templateUrl : 'views/reports.html',
controller : 'reportController'
})
}).run(function(userService,$location){
console.log(JSON.stringify(userService.getLoggedInUserDetails()));
userService.getLoggedInUserDetails().then(function(response){
var user = response;
console.log('UserDetails->'+JSON.stringify(user));
if(user.role=='ROBRCSR'){
$location.path('/storemanagement');
}
if(user.role=='ROBRMANAGER'){
$location.path('/incidentmanagement');
}
});
})
<file_sep>/src/main/java/com/wm/brta/service/ConfigurationService.java
package com.wm.brta.service;
import java.util.List;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.BalePickupSupplierSiteConfiguration;
import com.wm.brta.domain.User;
import com.wm.brta.dto.UserDTO;
public interface ConfigurationService
{
public String addSupplierMaterialConfigData(List<BalePickupSupplierSiteConfiguration> list,
List<BalePickupMaterialConfiguration> list2, boolean editAction, UserDTO user);
}
<file_sep>/src/main/java/com/wm/brta/dao/BalePickupMaterialConfigurationDAO.java
package com.wm.brta.dao;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.Material;
@Repository
public class BalePickupMaterialConfigurationDAO {
@Autowired
protected SessionFactory sessionFactory;
private static final Logger LOGGER = LoggerFactory.getLogger(BalePickupMaterialConfigurationDAO.class);
public Set<Material> getAllMaterial(Integer customerSiteId) {
Set<Material> materialSet = new HashSet<Material>();
Session session = sessionFactory.getCurrentSession();
String stringQuery = "from BalePickupMaterialConfiguration where customerSite.customerSiteId = :customerSiteId";
Query query = session.createQuery(stringQuery);
query.setParameter("customerSiteId", customerSiteId);
List<BalePickupMaterialConfiguration> balePickupMaterialConfigurationList = query.list();
if (balePickupMaterialConfigurationList != null) {
for(BalePickupMaterialConfiguration balePickupMaterialConfiguration: balePickupMaterialConfigurationList){
materialSet.add(balePickupMaterialConfiguration.getMaterial());
}
}
return materialSet;
}
}
<file_sep>/src/main/java/com/wm/brta/dao/BalePickupTripDAO.java
package com.wm.brta.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wm.brta.domain.BalePickupAssignment;
import com.wm.brta.domain.BalePickupTrip;
import com.wm.brta.domain.Image;
import com.wm.brta.dto.Commodity;
import com.wm.brta.dto.CompleteTripInputPayLoad;
import com.wm.brta.dto.PickupDetails;
@Repository
public class BalePickupTripDAO {
@Autowired
protected SessionFactory sessionFactory;
@Autowired
BalePickUpAssignmentDAO assignmentDAO;
private static final Logger LOGGER = LoggerFactory.getLogger(BalePickupTripDAO.class);
public Integer saveTripDetails(BalePickupTrip persistentObject){
Session session = sessionFactory.getCurrentSession();
return (Integer)session.save(persistentObject);
}
public Integer saveImageDetails(Image persistentObject){
Session session = sessionFactory.getCurrentSession();
return (Integer)session.save(persistentObject);
}
public List<BalePickupTrip> getAllTripsForAssignment(
CompleteTripInputPayLoad completeTripPayLoad) {
Session session = sessionFactory.getCurrentSession();
List<BalePickupTrip> trips = null;
List<BalePickupAssignment> assignments = new ArrayList<BalePickupAssignment>();
List<Date> dates = new ArrayList<Date>();
for(PickupDetails pickUpDetails: completeTripPayLoad.getCompletePickups()){
assignments.add(assignmentDAO.getAssignmentById(pickUpDetails.getAssignmentId()));
dates.add(new Date(pickUpDetails.getPickupDate()));
}
Query query = session.createQuery("from BalePickupTrip where"
+ " balePickupAssignment in :assignments and pickupDate in :dates");
query.setParameterList("assignments", assignments);
query.setParameterList("dates", dates);
//query.setParameter("userId", Long.parseLong(completeTripPayLoad.getUserId().toString()));
trips = query.list();
return trips;
}
public void completeTrip(BalePickupTrip trip) {
Session session = sessionFactory.getCurrentSession();
session.merge(trip);
}
public List<BalePickupTrip> getAllTripsWithMaterial(
HashSet<Commodity> commodities, int weekNumber, int day, Integer storeId, String date
) {
List<BalePickupTrip> trips = null;
Date pickupDate = new Date(date);
try{
Session session = sessionFactory.getCurrentSession();
trips = new ArrayList<BalePickupTrip>();
List<Integer> materialIds = new ArrayList<Integer>();
for(Commodity commodity : commodities){
materialIds.add(commodity.getCommodityId());
}
Query query = session.createQuery("from BalePickupTrip where material.materialId in :materialids and weekNumber = :weekNumber and day= :day"
+ " and buyCustomerSite.customerSiteId = :storeId and pickupDate = :pickupDate");
query.setParameterList("materialids", materialIds);
query.setParameter("weekNumber",weekNumber);
query.setParameter("day", day);
query.setParameter("storeId",storeId);
query.setParameter("pickupDate", pickupDate);
trips = query.list();
}
catch(Exception e){
LOGGER.error("Error:BalePickupTripDAO:getAllTripsWithMaterial=====>" +e);
}
return trips;
}
public void deleteTrip(Integer assignmentId, int weekNumber, int day, Integer storeId, String date,Integer userId) {
Session session = sessionFactory.getCurrentSession();
List<Integer>ids = new ArrayList<Integer>();
Date pickupDate = new Date(date);
java.sql.Date sqlDate = new java.sql.Date(pickupDate.getTime());
/*for(Commodity trip:assignmentId){
ids.add(trip.getCommodityId());
}*/
try{
Query query = session.createQuery("delete BalePickupTrip where balePickupAssignment.balePickupAssignmentId = :assignmentId and weekNumber = :weekNumber and day= :day"
+ " and buyCustomerSite.customerSiteId = :storeId and pickupDate = :pickupDate and user.userId = :userId");
query.setParameter("assignmentId", assignmentId);
query.setParameter("weekNumber",weekNumber);
query.setParameter("day", day);
query.setParameter("storeId",storeId);
query.setParameter("pickupDate", sqlDate);
query.setParameter("userId", Long.valueOf(userId));
query.executeUpdate();
}
catch(Exception e){
LOGGER.error("Error:BalePickupTripDAO:deleteTrip=====>" +e);
}
}
public List<BalePickupTrip> getTripsForAssignments(
List<BalePickupAssignment> assignments,List<String>dates) {
Session session = sessionFactory.getCurrentSession();
List<BalePickupTrip>trips = null;
List<Date> javaDates = new ArrayList<Date>();
List<Integer>ids = new ArrayList<Integer>();
for(BalePickupAssignment assignment:assignments){
ids.add(assignment.getBalePickupAssignmentId());
}
for(String date:dates){
javaDates.add(new Date(date));
}
try{
Query query = session.createQuery("from BalePickupTrip where balePickupAssignment.balePickupAssignmentId in :ids "
+ " and pickupDate in :dates");
query.setParameterList("ids", ids);
query.setParameterList("dates", javaDates);
trips = query.list();
}
catch(Exception e){
LOGGER.error("Error:BalePickupTripDAO:getTripsForAssignments=====>" +e);
}
return trips;
}
public List<BalePickupTrip> getTripsForAssignment(
Integer assignmentId) {
Session session = sessionFactory.getCurrentSession();
List<BalePickupTrip>trips = null;
List<Integer>ids = new ArrayList<Integer>();
try{
Query query = session.createQuery("from BalePickupTrip where balePickupAssignment.balePickupAssignmentId = :id");
query.setParameter("id", assignmentId);
trips = query.list();
}
catch(Exception e){
LOGGER.error("Error:BalePickupTripDAO:getTripsForAssignment=====>" +e);
}
return trips;
}
public List<BalePickupTrip> getAllSavedOnlyTrips(Integer userId,
List<String> pickupDates,List<BalePickupAssignment>assignments) {
List<BalePickupTrip> trips = null;
List<java.sql.Date> dates = new ArrayList<java.sql.Date>();
for(String date:pickupDates){
java.util.Date utilDate = new java.util.Date(date);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
dates.add(sqlDate);
}
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from BalePickupTrip where user.userId= :userId and pickupDate in "
+ ":pickupDates and loadTripId is null and childLoadTripId is null and balePickupAssignment in :assignments");
query.setParameter("userId", Long.parseLong(userId.toString()));
query.setParameterList("pickupDates", dates);
query.setParameterList("assignments", assignments);
trips = query.list();
return trips;
}
public void deleteImagesForTrip(Integer assignmentId, int weekNumber,
int day, Integer storeId, String date, Integer userId) {
Session session = sessionFactory.getCurrentSession();
List<Integer>ids = new ArrayList<Integer>();
Date pickupDate = new Date(date);
java.sql.Date sqlDate = new java.sql.Date(pickupDate.getTime());
List<BalePickupTrip> trips = new ArrayList<BalePickupTrip>();
List<Integer> tripIds = new ArrayList<Integer>();
try{
BalePickupAssignment assignment = assignmentDAO.getAssignmentById(assignmentId);
Query query = session.createQuery("from BalePickupTrip where balePickupAssignment = :assignment and weekNumber = :weekNumber and day= :day"
+ " and buyCustomerSite.customerSiteId = :storeId and pickupDate = :pickupDate and user.userId = :userId");
query.setParameter("assignment", assignment);
query.setParameter("weekNumber",weekNumber);
query.setParameter("day", day);
query.setParameter("storeId",storeId);
query.setParameter("pickupDate", sqlDate);
query.setParameter("userId", Long.valueOf(userId));
trips = query.list();
for(BalePickupTrip trip :trips){
tripIds.add(trip.getTripId());
}
Query queryForImages = session.createQuery("delete Image i where i.tripId in :tripids" );
queryForImages.setParameterList("tripids", tripIds);
queryForImages.executeUpdate();
}
catch(Exception e){
LOGGER.error("Error:BalePickupTripDAO:deleteImagesForTrip=====>" +e);
}
}
}
<file_sep>/src/main/java/com/wm/brta/dao/BalePickUpAssignmentDAO.java
package com.wm.brta.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wm.brta.domain.BalePickupAssignment;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.BalePickupTrip;
import com.wm.brta.domain.CustomerSite;
import com.wm.brta.domain.DriverPickups;
import com.wm.brta.domain.Image;
import com.wm.brta.domain.IncidentType;
import com.wm.brta.domain.MaterialInfo;
import com.wm.brta.domain.PendingReport;
import com.wm.brta.domain.Pickupsview;
import com.wm.brta.domain.SavedPickups;
import com.wm.brta.domain.Supplier;
import com.wm.brta.domain.User;
import com.wm.brta.dto.BalePickupFilterDTO;
import com.wm.brta.dto.Destination;
@Repository
public class BalePickUpAssignmentDAO {
@Autowired
protected SessionFactory sessionFactory;
private static final Logger LOGGER = LoggerFactory
.getLogger(BalePickUpAssignmentDAO.class);
public List<BalePickupAssignment> getAllAssignments(int userId) {
List<BalePickupAssignment> assignments = null;
Session session = sessionFactory.getCurrentSession();
try {
Query query = session
.createQuery("from BalePickupAssignment where (userId= :userId or divertedUserId= :divertedUserId "
+ ") and " + "disabled= :disabledFlag");
query.setParameter("userId", userId);
query.setParameter("divertedUserId", userId);
query.setParameter("disabledFlag", false);
assignments = query.list();
}
catch (RuntimeException e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getAllAssignments=====>"
+ e);
}
return assignments;
}
public BalePickupAssignment getAssignmentById(int id) {
List<BalePickupAssignment> assignments = null;
Session session = sessionFactory.getCurrentSession();
System.out.println("====getAssignmentById===" + id);
try {
Query query = session
.createQuery("from BalePickupAssignment where id = :id and disabled = false");
query.setParameter("id", id);
assignments = query.list();
}
catch (RuntimeException e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getAssignmentById=====>"
+ e);
}
return assignments.get(0);
}
public List<BalePickupTrip> getTripDetails(Integer assignmentId,
int userId, String pickupDate) {
List<BalePickupTrip> trips = new ArrayList<BalePickupTrip>();
try {
Session session = sessionFactory.getCurrentSession();
BalePickupAssignment assignment = getAssignmentById(assignmentId);
Date formatDate = new Date(pickupDate);
Query query = session
.createQuery("from BalePickupTrip"
+ " where balePickupAssignment = :assignment and userId = :userId and pickupDate = :formatDate");
query.setParameter("userId", userId);
query.setParameter("formatDate", formatDate);
query.setParameter("assignment", assignment);
trips = query.list();
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getTripDetails=====>"
+ e);
}
if (trips.size() != 0)
return trips;
else
return null;
}
public BalePickupAssignment getAssignmentDetails(int assignmentId,
int weekNumber, int day) {
Session session = sessionFactory.getCurrentSession();
Query query = session
.createQuery("from BalePickupAssignment"
+ " where balePickupAssignmentId = :assignmentId and weekNumber = :weekNumber and day= :day and disabled = false ");
query.setParameter("weekNumber", weekNumber);
query.setParameter("day", day);
query.setParameter("assignmentId", assignmentId);
List<BalePickupAssignment> assignments = query.list();
if (assignments != null && assignments.size() != 0)
return assignments.get(0);
else
return null;
}
public List<BalePickupMaterialConfiguration> getAllMaterialConfiguationMappingsByCustomerSite(
CustomerSite customerSite) {
Session session = sessionFactory.getCurrentSession();
List<BalePickupMaterialConfiguration> materialMappings = null;
Query query = session
.createQuery("from BalePickupMaterialConfiguration where buyCustomerSiteId= :customerId");
query.setParameter("customerId", customerSite.getCustomerSiteId());
try {
materialMappings = query.list();
} catch (RuntimeException e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getAllMaterialConfiguationMappingsByCustomerSite=====>"
+ e);
}
return materialMappings;
}
public void persist(BalePickupAssignment assignment) {
Session session = sessionFactory.getCurrentSession();
try {
CustomerSite customerSite = (CustomerSite) session.get(
"com.wm.brta.domain.CustomerSite", assignment
.getBuyCustomerSite().getCustomerSiteId());
customerSite.setHasFrequency(true);
session.merge(customerSite);
session.persist(assignment);
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:persist=====>" + e);
}
}
public Set<BalePickupAssignment> getAllAssignmentForActivity(
List<CustomerSite> buyCustomerSites, List<User> users,
List<CustomerSite> sellCustomerSites, Supplier supplier,
Integer frequency, HashSet<Integer> dayList,
HashSet<Integer> monthWeekList) {
Session session = sessionFactory.getCurrentSession();
String queryStr = "from BalePickupAssignment where buyCustomerSite in :buyCustomerSites "
+ "and supplier = :supplier and (user = :user or user is null) and disabled = false";
if ((frequency != null) && (!dayList.isEmpty())) {
queryStr = "from BalePickupAssignment where buyCustomerSite in :buyCustomerSites "
+ "and supplier = :supplier and (user = :user or user is null) and "
+ "frequency = :frequency and day in :dayList and disabled = false";
} else if ((frequency != null) && (!monthWeekList.isEmpty())) {
queryStr = "from BalePickupAssignment where buyCustomerSite in :buyCustomerSites "
+ "and supplier = :supplier and (user = :user or user is null) and "
+ "frequency = :frequency and weekNumber in :monthWeekList and disabled = false";
} else if (frequency != null) {
queryStr = "from BalePickupAssignment where buyCustomerSite in :buyCustomerSites "
+ "and supplier = :supplier and (user = :user or user is null) and frequency = :frequency"
+ " and disabled = false";
}
Set<BalePickupAssignment> resultAssignments = new HashSet<BalePickupAssignment>();
try {
Query query = session.createQuery(queryStr);
query.setParameterList("buyCustomerSites", buyCustomerSites);
query.setParameter("user", users.get(0));
query.setParameter("supplier", supplier);
if (frequency != null) {
query.setParameter("frequency", frequency);
}
if (!dayList.isEmpty()) {
query.setParameterList("dayList", dayList);
}
if (!monthWeekList.isEmpty()) {
query.setParameterList("monthWeekList", monthWeekList);
}
List<BalePickupAssignment> assignments = query.list();
resultAssignments = new HashSet<BalePickupAssignment>(assignments);
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getAllAssignmentForActivity=====>"
+ e);
}
return resultAssignments;
}
public void merge(BalePickupAssignment assignment) {
Session session = sessionFactory.getCurrentSession();
try {
session.merge(assignment);
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:merge=====>" + e);
}
}
public List<BalePickupAssignment> getAllOnCallAssignments() {
List<BalePickupAssignment> assignments = null;
Session session = sessionFactory.getCurrentSession();
try {
Query query = session
.createQuery("from BalePickupAssignment where weekNumber = :weekNumber and day = :day"
+ " and disabled= :disabledFlag");
query.setParameter("weekNumber", -1);
query.setParameter("day", -1);
query.setParameter("disabledFlag", false);
assignments = query.list();
}
catch (RuntimeException e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getAllOnCallAssignments=====>"
+ e);
}
return assignments;
}
public HashSet<BalePickupAssignment> getPickupAssignmentsForCustomerSite(
CustomerSite customerSite) {
List<BalePickupAssignment> assignments = null;
HashSet<BalePickupAssignment> hashedResults = null;
Session session = sessionFactory.getCurrentSession();
try {
Query query = session
.createQuery("from BalePickupAssignment where buyCustomerSite.customerSiteId= :customerSiteId and"
+ " disabled = false");
query.setParameter("customerSiteId",
customerSite.getCustomerSiteId());
assignments = query.list();
hashedResults = new HashSet<BalePickupAssignment>(assignments);
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getPickupAssignmentsForCustomerSite=====>"
+ e);
}
return hashedResults;
}
public void delete(List<BalePickupAssignment> assignments) {
System.out.println("======delete dao==================");
Session session = sessionFactory.getCurrentSession();
List<Integer> ids = new ArrayList<Integer>();
for (BalePickupAssignment balePickupAssignment : assignments) {
ids.add(balePickupAssignment.getBalePickupAssignmentId());
}
System.out.println("--ids----" + ids);
if (ids.size() <= 0) {
return;
}
try {
Query query = session
.createQuery("update BalePickupAssignment balePickupAss set balePickupAss.disabled = true where"
+ " balePickupAss.balePickupAssignmentId in :ids");
query.setParameterList("ids", ids);
query.executeUpdate();
} catch (RuntimeException e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:delete=====>" + e);
} finally {
}
}
public void disableBalePickupAssignments(List<Integer> customerSiteIds) {
System.out.println("======delete dao=11================="
+ customerSiteIds);
Session session = sessionFactory.getCurrentSession();
try {
Query query = session
.createQuery("update BalePickupAssignment balePickupAss set balePickupAss.disabled = true where"
+ " balePickupAss.buyCustomerSite.customerSiteId in :ids");
query.setParameterList("ids", customerSiteIds);
query.executeUpdate();
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:disableBalePickupAssignments=====>"
+ e);
} finally {
}
}
public Set<PendingReport> getPendingPickups(Integer buyCustomerId,
Integer supplierId, Integer day, Integer weekNumber,
String pickupDate) {
List<PendingReport> assignments = null;
Set<PendingReport> resultBalePickups = null;
Session session = sessionFactory.getCurrentSession();
try {
Query query = session
.createSQLQuery(
"{CALL GetPendingPickups"
+ "(:buyCustomerId,:supplierId,:pickupDate,:weekNumber,:day)}")
.addEntity(PendingReport.class);
query.setParameter("buyCustomerId", buyCustomerId);
query.setParameter("supplierId", supplierId);
query.setParameter("pickupDate", pickupDate);
query.setParameter("weekNumber", weekNumber);
query.setParameter("day", day);
List<PendingReport> result = query.list();
resultBalePickups = new HashSet<PendingReport>(result);
LOGGER.info(" resultBalePickups " + resultBalePickups.size());
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getPendingPickups=====>"
+ e);
}
return resultBalePickups;
}
public List<DriverPickups> getDriverPickupsByDate(Integer driverId,
String pickupDate, Integer day, Integer weekNumber) {
Session session = sessionFactory.getCurrentSession();
List<DriverPickups> driverPickups = new ArrayList<DriverPickups>();
try {
Query query = session.createSQLQuery(
"{CALL GetDriverPickupsByDate"
+ "(:driverId,:pickupDate,:weekNumber,:day)}")
.addEntity(DriverPickups.class);
query.setParameter("driverId", driverId);
query.setParameter("pickupDate", pickupDate);
query.setParameter("weekNumber", weekNumber);
query.setParameter("day", day);
driverPickups = query.list();
LOGGER.info(" driverPickups " + driverPickups.size());
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getDriverPickupsByDate=====>"
+ e);
}
return driverPickups;
}
public List<SavedPickups> getSavedOnlyTrip(Integer driverId,
String pickupDate) {
Session session = sessionFactory.getCurrentSession();
List<SavedPickups> savedPickups = new ArrayList<SavedPickups>();
try {
Query query = session.createSQLQuery(
"{CALL GetSavedPickups" + "(:driverId,:pickupDate)}")
.addEntity(SavedPickups.class);
query.setParameter("driverId", driverId);
query.setParameter("pickupDate", pickupDate);
savedPickups = query.list();
LOGGER.info(" driverPickups " + savedPickups.size());
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getSavedOnlyTrip=====>"
+ e);
}
return savedPickups;
}
public List<MaterialInfo> getMaterialByAssignmentId(Integer assignmehtaId,
String pickupDate) {
Session session = sessionFactory.getCurrentSession();
List<MaterialInfo> savedPickups = new ArrayList<MaterialInfo>();
try {
Query query = session.createSQLQuery(
"{CALL GetMaterialsByAssignment"
+ "(:assignmehtaId,:pickupDate)}").addEntity(
MaterialInfo.class);
query.setParameter("assignmehtaId", assignmehtaId);
query.setParameter("pickupDate", pickupDate);
savedPickups = query.list();
LOGGER.info(" driverPickups " + savedPickups.size());
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:getMaterialByAssignmentId=====>"
+ e);
}
return savedPickups;
}
public List<Pickupsview> getAllPickups(BalePickupFilterDTO balePickupFilter) {
Session session = sessionFactory.getCurrentSession();
Integer buycustomerId =null;
if(balePickupFilter.getBuyCustomer()!=null){
buycustomerId = balePickupFilter.getBuyCustomer()
.getCustomerId();
}
Integer supplierId =null;
if(balePickupFilter.getSupplier()!=null){
supplierId = balePickupFilter.getSupplier()
.getSupplierId();
}
Date startDate = balePickupFilter.getStartDate();
Date endDate = balePickupFilter.getEndDate();
IncidentType incidentType = balePickupFilter.getIncidentType();
String buyCustomerAddress4 = null;
String description = null;
String stringQuery = null;
stringQuery = "from Pickupsview where pickupDate between :startDate and :endDate ";
if(buycustomerId !=null){
stringQuery=stringQuery+ " and buyCustomerId = :buycustomerid ";
}
if(supplierId !=null){
stringQuery=stringQuery+ " and supplierId = :supplierid ";
}
if (incidentType != null) {
description = incidentType.getIncidentDescription();
if ((description != null) && (description.equals("All Incidents")))
stringQuery=stringQuery+ " and incidentType is not null ";
else
stringQuery=stringQuery+ " and incidentType = :incidentType ";
}
if (balePickupFilter.getState() != null) {
buyCustomerAddress4 = balePickupFilter.getState();
stringQuery=stringQuery +" and buyCustomerAddress4= :buyCustomerAddress4 ";
}
Query query = session.createQuery(stringQuery);
query.setParameter("startDate", startDate);
query.setParameter("endDate", endDate);
if(buycustomerId!=null){
query.setParameter("buycustomerid", buycustomerId);
}
if(supplierId!=null){
query.setParameter("supplierid", supplierId);
}
if ((incidentType != null)
&& ((description != null) && (!description
.equals("All Incidents")))) {
query.setParameter("incidentType", incidentType.getIncidentTypeId());
}
if(buyCustomerAddress4!=null){
query.setParameter("buyCustomerAddress4", buyCustomerAddress4);
}
List<Pickupsview> pickupList = query.list();
return pickupList;
}
public Set<Image> getBalePickupImages(Integer balePickupId) {
Session session = sessionFactory.getCurrentSession();
String stringQuery = "from Image where tripId = :balePickupId ";
Query query = session.createQuery(stringQuery);
query.setParameter("balePickupId", balePickupId);
List<Image> imageList = query.list();
Set<Image> resultBalePickupImages = new HashSet<Image>(imageList);
return resultBalePickupImages;
}
public void mergeAssignment(BalePickupAssignment assignment) {
Session session = sessionFactory.getCurrentSession();
try {
session.merge(assignment);
} catch (Exception e) {
LOGGER.error("Error:BalePickUpAssignmentDAO:mergeAssignment=====>"
+ e);
}
}
public HashSet<Destination> getDestination(String storeName) {
Session session = sessionFactory.getCurrentSession();
String stringQuery = "from Pickupsview where buyCustomerSiteName = :storeName ";
Query query = session.createQuery(stringQuery);
query.setParameter("storeName", storeName);
List<Pickupsview> destinationList = query.list();
HashSet<Destination> destinations = new HashSet<Destination>();
for (Pickupsview pickupsview : destinationList) {
Destination destination = new Destination();
destination.setName(pickupsview.getSellCustomerSiteName());
destination.setDestinationId(pickupsview.getSellCustomerSiteId());
destinations.add(destination);
}
return destinations;
}
public BalePickupAssignment getAssignment(Integer customerSiteId,
Integer day, Integer weekNumber) {
BalePickupAssignment balePickupAssignment = null;
Session session = sessionFactory.getCurrentSession();
String stringQuery = "from BalePickupAssignment where buyCustomerSite.customerSiteId = :customerSiteId and"
+ " day = :day and weekNumber = :weekNumber and disabled = false";
Query query = session.createQuery(stringQuery);
query.setParameter("customerSiteId", customerSiteId);
query.setParameter("day", day);
query.setParameter("weekNumber", weekNumber);
List<BalePickupAssignment> balePickupAssignmentList = query.list();
if (!balePickupAssignmentList.isEmpty()) {
balePickupAssignment = balePickupAssignmentList.get(0);
}
return balePickupAssignment;
}
}<file_sep>/src/main/java/com/wm/brta/service/BalePickupService.java
package com.wm.brta.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*import com.wm.brta.data.domain.Pickupsview;*/
/*import com.wm.brta.data.dto.BalePickupFilterDTO;
import com.wm.brta.data.dto.BalePickupUpdateDTO;*/
import com.wm.brta.domain.BalePickupAssignment;
import com.wm.brta.domain.BalePickupTrip;
import com.wm.brta.domain.CustomerSite;
import com.wm.brta.domain.DriverPickups;
import com.wm.brta.domain.Image;
import com.wm.brta.domain.PendingReport;
import com.wm.brta.domain.Pickupsview;
import com.wm.brta.domain.User;
import com.wm.brta.dto.ActivityListInputPayload;
import com.wm.brta.dto.AssignmentFilterDTO;
import com.wm.brta.dto.BalePickupAssignmentDTO;
import com.wm.brta.dto.BalePickupFilterDTO;
import com.wm.brta.dto.BalePickupUpdateDTO;
import com.wm.brta.dto.Destination;
import com.wm.brta.dto.OnCallInputPayload;
import com.wm.brta.dto.PendingStoreReportDTO;
import com.wm.brta.dto.PickupDetails;
import com.wm.brta.dto.PickupDetailsFromExcel;
import com.wm.brta.dto.PickupDetailsWithMasterSets;
import com.wm.brta.dto.UserDTO;
public interface BalePickupService {
public HashSet<Destination>getAllDestinations(ActivityListInputPayload activityListPayload);
public List<PickupDetails> getAllDestinationsNew(ActivityListInputPayload activityListPayload);
public PickupDetailsWithMasterSets getPickupDetails(PickupDetails pickup);
public void addBalePickupAssignments(BalePickupAssignmentDTO assignmentDTO, UserDTO user);
public Set<BalePickupAssignment> getPickupAssignments(AssignmentFilterDTO assignmentFilter);
public List<Pickupsview> getPickUps(BalePickupFilterDTO balePickupFilter);
public Set<PendingReport> getAllPendingPickups(PendingStoreReportDTO pendingStoreReportDTO);
public List<String> getBalePickupImages(Integer balePickupId);
public void updateBalePickupAssignmentstoAssignActivity(
List<BalePickupAssignment> assignments, UserDTO user);
public HashSet<Destination> getAllPickupsForOnCall(OnCallInputPayload inputPayLoad);
public List<PickupDetails> getAllPickupsForOnCallNew(OnCallInputPayload inputPayLoad);
public Set<BalePickupAssignment> getPickupAssignmentsForCustomerSite(
CustomerSite customerSite);
public String assignNewDriver(BalePickupAssignment assignment) throws Exception;
public PickupDetails createPickupDetailsObject(PickupDetailsFromExcel pickupDetailsFromExcel);
public String removeNewDriver(BalePickupAssignment assignment);
public String getBalePickupImagesFromName(String imageName);
}
<file_sep>/src/main/webapp/resources/js/angular/service/storeservice.js
brtaApp.service('storeConfigService', function($http,applicationContextURL){
return {
addConfigurationData: function(configData){
return $http.post(applicationContextURL+"/add/suppliermaterialconfiguration",configData)
then(function(response){
console.log(JSON.stringify(response));
return response.data;
},function(errResponse){
console.error('Error while adding onfiguration data');
});
}
}
});
brtaApp.service('pickupAssignmentService', function($http,applicationContextURL){
return {
get: function(configData){
return $http.post(applicationContextURL+"/add/suppliermaterialconfiguration",configData)
then(function(response){
console.log(JSON.stringify(response));
return response.data;
},function(errResponse){
console.error('Error while adding configuration data');
});
},
getAssignmentsByCustomerSite: function(customerSite){
return $http.post(applicationContextURL+"/assignMgmt/get/assignments/bycustomerSite",customerSite)
then(function(response){
console.log(JSON.stringify(response));
return response.data;
},function(errResponse){
console.error('Error while getting assignments by customerSite');
});
},
addAssignmentList: function(listOfAssignments){
return $http.post(applicationContextURL+"/assignMgmt/add/pickupassignments",listOfAssignments)
then(function(response){
console.log(JSON.stringify(response));
return response.data;
},function(errResponse){
return response.data;
console.error('Error while adding assignments');
});
},
getAllAssignments:function(assignmentFilterDTO){
return $http.post(applicationContextURL+"/assignMgmt/getAll/pickupassignments",assignmentFilterDTO)
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while getting assignments');
});
},
assignActivityToUser:function(assigmnentActivityList){
return $http.post(applicationContextURL+"/assignMgmt/update/pickupassignments",assigmnentActivityList)
then(function(response){
console.log(response.data);
return response.data;
},function(errResponse){
return response.data;
console.error('Error while adding assignments');
});
}
}
});<file_sep>/src/main/webapp/resources/js/angular/service/masterservice.js
brtaApp.service('supplierService', function($http,applicationContextURL){
return {
getAllSuppliers: function(){
return $http.get(applicationContextURL+"/get/supplier/all").
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving suppliers');
});
},
getAllSupplierSites: function(supplier){
return $http.post(applicationContextURL+"/get/suppliersite/bysupplier",supplier).
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving supplier sites');
});
}
}
});
brtaApp.service('customerService', function($http,$rootScope,$q,applicationContextURL){
return {
getAllBuyCustomers: function(){
if($rootScope.buyCustomers != undefined){
return this.populateData($rootScope.buyCustomers);;
}
return $http.get(applicationContextURL+"/common/get/buycustomers/all").
then(function(response){
$rootScope.buyCustomers=response.data
return response.data;
},function(errResponse){
console.error('Error while retrieving buy customers');
});
},
getCustomerSitesForBuyCustomer: function(storeDto){
return $http.post(applicationContextURL+"/get/customersites/bybuycustomer",storeDto).
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving buy customers');
});
},
getSuppliersForBuyCustomer: function(buyCustomer){
return $http.post(applicationContextURL+"/common/get/supplier/bybuycustomer",buyCustomer).
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving buy customers');
});
},
getAllSuppliersWithBuyCustomer: function(){
console.log("==$rootScope.suppliersWithCustomer==="+JSON.stringify($rootScope.suppliersWithCustomer));
if($rootScope.suppliersWithCustomer != undefined){
return this.populateDataForMap($rootScope.suppliersWithCustomer);
}
return $http.get(applicationContextURL+"/common/get/allSupplierWithBuyCustomer").
then(function(response){
$rootScope.suppliersWithCustomer= response.data;
return response.data;
},function(errResponse){
console.error('Error while retrieving buy customers');
});
},
getMatrialsForBuyCustomer: function(buyCustomer){
return $http.post(applicationContextURL+"/common/get/material/bycustomer",buyCustomer).
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving materials for customers');
});
},
getAllSellCustomersForBuyCustomer: function(buyCustomer){
return $http.post(applicationContextURL+"/get/sellcustomer/bybuycustomer",buyCustomer).
then(function(response){
return response.data;
},function(errResponse){
console.error('Error while retrieving sellcustomers for customers');
});
},
populateData: function(data) {
var deferred = $q.defer();
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
deferred.resolve(items);
return deferred.promise;
},
populateDataForMap: function(data) {
var deferred = $q.defer();
var items = {};
angular.forEach( data, function(value,key){
items[key]=value;
});
deferred.resolve(items);
return deferred.promise;
}
}
});<file_sep>/src/main/java/com/wm/brta/dto/Destination.java
package com.wm.brta.dto;
import java.util.HashSet;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class Destination {
private Integer destinationId;
private String name;
private HashSet<PickupDetails> pickupDetails;
public Integer getDestinationId() {
return destinationId;
}
public void setDestinationId(Integer destinationId) {
this.destinationId = destinationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public HashSet<PickupDetails> getPickupDetails() {
return pickupDetails;
}
public void setPickupDetails(HashSet<PickupDetails> pickupDetails) {
this.pickupDetails = pickupDetails;
}
@Override
public String toString() {
return "Destination [destinationId=" + destinationId + ", name=" + name
+ ", pickupDetails=" + pickupDetails + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((destinationId == null) ? 0 : destinationId.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((pickupDetails == null) ? 0 : pickupDetails.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Destination other = (Destination) obj;
if (destinationId == null) {
if (other.destinationId != null)
return false;
} else if (!destinationId.equals(other.destinationId))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (pickupDetails == null) {
if (other.pickupDetails != null)
return false;
} else if (!pickupDetails.equals(other.pickupDetails))
return false;
return true;
}
}
<file_sep>/src/main/java/com/wm/brta/service/impl/IncidentTypeServiceImpl.java
package com.wm.brta.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.wm.brta.dao.IncidentTypeDao;
import com.wm.brta.dao.UserDao;
import com.wm.brta.domain.IncidentType;
import com.wm.brta.domain.Supplier;
import com.wm.brta.domain.User;
import com.wm.brta.dto.UserDTO;
import com.wm.brta.service.ApplicationService;
import com.wm.brta.service.IncidentTypeService;
import com.wm.brta.utility.MailServiceUtility;
@Component("incidentService")
@Transactional
public class IncidentTypeServiceImpl implements ApplicationService<IncidentType>, IncidentTypeService {
@Autowired
IncidentTypeDao incidentTypeDao;
@Override
public List<IncidentType> add(IncidentType persistenceObject,UserDTO userDTO) throws Exception {
persistenceObject.setCreatedDate(new Date());
persistenceObject.setUpdatedAt(new Date());
persistenceObject.setUpdatedBy(userDTO.getFirstName());
List<IncidentType>incidents = new ArrayList<IncidentType>();
long id = 0;
id = incidentTypeDao.save(persistenceObject);
if(id !=0){
incidents = getAll();
}
return incidents;
}
@Override
public LinkedList delete(IncidentType object) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public List<IncidentType> getAll() {
List<IncidentType>incidents = incidentTypeDao.getAllIncidents();
return incidents;
}
@Override
public List edit(IncidentType incident) throws Exception {
incident.setUpdatedAt(new Date());
List<IncidentType>incidents = new ArrayList<IncidentType>();
long id = 0;
incidentTypeDao.merge(incident);
incidents= getAll();
return incidents;
}
@Override
public Boolean checkIncidenttypeUniqueOrNot(String incidentType) {
Boolean status=false;
status= incidentTypeDao.checkIncidenttypeUnique(incidentType);
return status;
}
@Override
public List<IncidentType> getAll(Supplier supplierSelected)
throws Exception {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/src/main/java/com/wm/brta/service/IncidentTypeService.java
package com.wm.brta.service;
public interface IncidentTypeService {
public Boolean checkIncidenttypeUniqueOrNot(String incidentType);
}
<file_sep>/src/main/webapp/resources/js/angular/service/balepickupservice.js
brtaApp.service('balepickupService', function($http, applicationContextURL) {
return {
getAllPickups : function(configData) {
return $http.post(applicationContextURL + "/common/getAll/pickUps",
configData)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
addNewDriver : function(assignment) {
return $http.post(applicationContextURL + "/assignMgmt/add/newdriver",
assignment)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding new driver');
});
},
removeNewDriver : function(assignment) {
return $http.post(applicationContextURL + "/assignMgmt/remove/newdriver",
assignment)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while removing new driver');
});
},
editBalePickup : function(balePickup) {
return $http.post(applicationContextURL
+ "/tripMgmt/add/tripdetails", balePickup)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
addNewBalePickup : function(balePickup) {
return $http.post(applicationContextURL
+ "/tripMgmt/add/tripdetails", balePickup)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
getAllDestination : function(storeName) {
return $http.post(applicationContextURL + "/assignMgmt/get/destination",
storeName)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
getDestinationForUserAndDate : function(setDto) {
return $http.post(applicationContextURL + "/assignMgmt/pickups",
setDto)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
getBalePickUpImages : function(tripId) {
return $http.post(applicationContextURL + "/tripMgmt/pickUp/images", tripId)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding configuration data');
});
},
pickupUploadFromExcel : function(pickUpList) {
console.log("---pickUpList-" + JSON.stringify(pickUpList));
return $http.post(applicationContextURL
+ "/tripMgmt/upload/pickUpsFromExcel", pickUpList)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding new driver');
});
},
completeBalePickup : function(pickUp) {
return $http.post(applicationContextURL
+ "/tripMgmt/update/completetrip", pickUp)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding new driver');
});
},
}
});<file_sep>/src/main/java/com/wm/brta/constants/ApplicationCommonConstants.java
package com.wm.brta.constants;
public class ApplicationCommonConstants
{
public static final String INSERTION_SUCCESSFULL_MESSAGE = "Records inserted successfully";
public static final String INSERTION_FAILURE_MESSAGE = "Records failed to insert";
public static final String AUTHENTICATION_SUCCESSFULL_MESSAGE = "Driver Authenticated Succssfully";
public static final String AUTHENTICATION_UNSUCCESSFULL_MESSAGE = "Driver Not Registered";
}
<file_sep>/src/main/java/com/wm/brta/dto/StoreInputDTO.java
package com.wm.brta.dto;
import com.wm.brta.domain.Customer;
public class StoreInputDTO {
private Customer buyCustomer;
private String state;
public Customer getBuyCustomer() {
return buyCustomer;
}
public void setBuyCustomer(Customer buyCustomer) {
this.buyCustomer = buyCustomer;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "StoreInputDTO [buyCustomer=" + buyCustomer + ", state=" + state
+ "]";
}
}
<file_sep>/src/main/java/com/wm/brta/controller/web/LoginController.java
/**
*
*/
package com.wm.brta.controller.web;
import java.io.IOException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wm.brta.dto.UserDTO;
import com.wm.brta.service.LoginService;
import com.wm.brta.utility.UserDetailsUtility;
/**
* @fileName BaleRouteLoginController.java
* @author rthoma24
* @Project BaleRoute
* @Date Nov 29, 2016
* @Sprint
* @UserStory
* @Theme BaleRouteLoginController
*
*/
@Controller
public class LoginController {
@Autowired
private UserDetailsUtility userDetails;
@Autowired
private LoginService loginService;
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getIndexPage(HttpServletRequest request) {
UserDTO user;
try {
try {
user = userDetails.getUserDetails(request);
String sm_groups = request.getHeader("sm_groups")
.replace('\n', ' ').trim();
} catch (Exception e) {
user = new UserDTO();
user.setFirstName("nmehta");
user.setRole("ROBRCSR");
user.setRoles("ROBRCSR");
/*user.setRole("ROBRMANAGER");
user.setRoles("ROBRMANAGER");*/
LOGGER.info("Error:Login Controller:getUserDetails=====>" + e);
}
HttpSession session = request.getSession();
Double versionNo=1.04;
session.setAttribute("versionNo", versionNo);
session.setAttribute("user", user);
session.setAttribute("sm_groups", user.getRole());
LOGGER.debug("Logged in user name:" + user.getFirstName());
LOGGER.debug("Logged in user role:" + user.getRole());
} catch (Exception e) {
LOGGER.error("Error:Login Controller:getRole,getFirstName=====>"+ e);
}
return "landing";
}
@RequestMapping(value = "/logout")
public void logout(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession session = request.getSession();
Cookie[] cookies = request.getCookies();
if (cookies != null)
for (int i = 0; i < cookies.length; i++) {
if ("SMSESSION".equals(cookies[i].getName())) {
cookies[i].setValue("null");
cookies[i].setPath("/");
cookies[i].setMaxAge(0);
cookies[i].setDomain(".wm.com");
// cookies[i].setComment(MESSAGE +
// System.currentTimeMillis());
response.addCookie(cookies[i]);
} else if ("JSESSIONID".equals(cookies[i].getName())) {
cookies[i].setValue("null");
// cookies[i].setPath(cookiePath);
cookies[i].setMaxAge(0);
// cookies[i].setDomain(cookieDomain);
// cookies[i].setComment(MESSAGE +
// System.currentTimeMillis());
response.addCookie(cookies[i]);
} else {
cookies[i].setValue("");
cookies[i].setPath("/");
cookies[i].setMaxAge(0);
// cookies[i].setComment(MESSAGE +
// System.currentTimeMillis());
response.addCookie(cookies[i]);
}
}
session.invalidate();
String siteuri = "/";
response.sendRedirect(siteuri);
}
@RequestMapping(value = "/common/getdetails/user", method = RequestMethod.GET)
@ResponseBody
public UserDTO getLoggedInUserDetails(HttpServletRequest request) {
HttpSession session = request.getSession();
UserDTO user = (UserDTO) session.getAttribute("user");
return user;
}
}
<file_sep>/README.md
# Bale-Back
<file_sep>/src/main/java/com/wm/brta/dto/PickupDetailsFromExcel.java
package com.wm.brta.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(Include.NON_NULL)
public class PickupDetailsFromExcel {
private String storeName;
private String pickupDate;
private Integer balesPicked;
private Integer balesRemaining;
private String commodity;
private Integer bol;
@JsonProperty("STORE_NAME")
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
@JsonProperty("PICKUP_DATE")
public String getPickupDate() {
return pickupDate;
}
public void setPickupDate(String pickupDate) {
this.pickupDate = pickupDate;
}
@JsonProperty("BALES_PICKED")
public Integer getBalesPicked() {
return balesPicked;
}
public void setBalesPicked(Integer balesPicked) {
this.balesPicked = balesPicked;
}
@JsonProperty("BALES_REMAINING")
public Integer getBalesRemaining() {
return balesRemaining;
}
public void setBalesRemaining(Integer balesRemaining) {
this.balesRemaining = balesRemaining;
}
@JsonProperty("COMMODITY")
public String getCommodity() {
return commodity;
}
public void setCommodity(String commodity) {
this.commodity = commodity;
}
@JsonProperty("BOL")
public Integer getBol() {
return bol;
}
public void setBol(Integer bol) {
this.bol = bol;
}
@Override
public String toString() {
return "PickupDetailsFromExcel [storeName=" + storeName
+ ", pickupDate=" + pickupDate + ", balesPicked=" + balesPicked
+ ", balesRemaining=" + balesRemaining + ", commodity="
+ commodity + ", bol=" + bol + "]";
}
}<file_sep>/src/main/java/com/wm/brta/domain/CustomerSite.java
package com.wm.brta.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="[customersite]")
public class CustomerSite {
private Integer customerSiteId;
private Customer customer;
private Location location;
private String siteName;
private SalesTerritory salesTerritory;
private Integer customerServiceRepId;
private Integer salesRepId;
private String sysUserName;
private Date createdDate;
private Date updatedAt;
private String updatedBy;
private boolean hasFrequency;
private float avgBaleWeight;
private Date balePickupStartDate;
private List<BalePickupMaterialConfiguration> balePickupMaterialConfiguration;
private List<BalePickupSupplierSiteConfiguration> BalePickupSupplierSiteConfiguration;
private List<String>configuredMaterials;
private List<String>configuredSupplierSites;
private String alternativeSearchReference;
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL,mappedBy="customerSite")
@JsonBackReference(value="materialConfigurations")
@JsonIgnore
public List<BalePickupMaterialConfiguration> getBalePickupMaterialConfiguration() {
return balePickupMaterialConfiguration;
}
public void setBalePickupMaterialConfiguration(
List<BalePickupMaterialConfiguration> balePickupMaterialConfiguration) {
this.balePickupMaterialConfiguration = balePickupMaterialConfiguration;
}
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL,mappedBy="customerSite")
@JsonBackReference(value="supplierSiteConfigurations")
@JsonIgnore
public List<BalePickupSupplierSiteConfiguration> getBalePickupSupplierSiteConfiguration() {
return BalePickupSupplierSiteConfiguration;
}
public void setBalePickupSupplierSiteConfiguration(
List<BalePickupSupplierSiteConfiguration> balePickupSupplierSiteConfiguration) {
BalePickupSupplierSiteConfiguration = balePickupSupplierSiteConfiguration;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "customersiteid", unique = true, nullable = false)
public Integer getCustomerSiteId() {
return customerSiteId;
}
public void setCustomerSiteId(Integer customerSiteId) {
this.customerSiteId = customerSiteId;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="customerid",nullable=false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="locationid",nullable=false)
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
@Column(name="sitename",nullable=false)
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="salesterritoryid",nullable=false)
public SalesTerritory getSalesTerritory() {
return salesTerritory;
}
public void setSalesTerritory(SalesTerritory salesTerritory) {
this.salesTerritory = salesTerritory;
}
@Column(name="customerservicerepid",nullable=false)
public Integer getCustomerServiceRepId() {
return customerServiceRepId;
}
public void setCustomerServiceRepId(Integer customerServiceRepId) {
this.customerServiceRepId = customerServiceRepId;
}
@Column(name="salesrepid",nullable=false)
public Integer getSalesRepId() {
return salesRepId;
}
public void setSalesRepId(Integer salesRepId) {
this.salesRepId = salesRepId;
}
@Column(name="sysusername")
public String getSysUserName() {
return sysUserName;
}
public void setSysUserName(String sysUserName) {
this.sysUserName = sysUserName;
}
@Column(name="createdate",nullable=false)
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Column(name="updatedat",nullable=false)
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Column(name="updatedby",nullable=false)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
@Column(name="hasfrequency")
public boolean isHasFrequency() {
return hasFrequency;
}
public void setHasFrequency(boolean hasFrequency) {
this.hasFrequency = hasFrequency;
}
@Column(name="balepickupstartdate")
public Date getBalePickupStartDate() {
return balePickupStartDate;
}
public void setBalePickupStartDate(Date balePickupStartDate) {
this.balePickupStartDate = balePickupStartDate;
}
@Column(name="avgbaleweight")
public float getAvgBaleWeight() {
return avgBaleWeight;
}
public void setAvgBaleWeight(float avgBaleWeight) {
this.avgBaleWeight = avgBaleWeight;
}
@Transient
public List<String> getConfiguredSupplierSites() {
return configuredSupplierSites;
}
public void setConfiguredSupplierSites(List<String> configuredSupplierSites) {
this.configuredSupplierSites = configuredSupplierSites;
}
@Transient
public List<String> getConfiguredMaterials() {
return configuredMaterials;
}
public void setConfiguredMaterials(List<String> configuredMaterials) {
this.configuredMaterials = configuredMaterials;
}
@Column(name="alternativesearchreference")
public String getAlternativeSearchReference() {
return alternativeSearchReference;
}
public void setAlternativeSearchReference(String alternativeSearchReference) {
this.alternativeSearchReference = alternativeSearchReference;
}
}
<file_sep>/src/main/webapp/resources/js/angular/app/reportmanagement.js
brtaApp.controller("reportController",function(applicationContextURL,$scope,$http,reportService,customerService,incidentTypeService)
{
$scope.selectAllIncidentTypeObj={
"incidentTypeId":"1234",
"incidentDescription":"All Incidents"
}
$scope.editingData = [];
//$scope.boundary-links=false;
$scope.detailedActivityReportTab = true;
$scope.currentPage=1;
$scope.pageSize =10;
$scope.pageChangeHandler = function(num) {
$scope.currentPage= num;
};
$scope.currentPageRMT=1;
$scope.pageSizeRMT=10;
$scope.pageChangeHandlerRMT = function(numrmt) {
$scope.currentPageRMT= numrmt;
};
$scope.currentPagePending=1;
$scope.pageSizePending=10;
$scope.pageChangeHandlerPending = function(numpending) {
$scope.currentPagePending= numpending;
};
$scope.disableSubmitBtn=true;
$scope.disableSubmitBtnRMT=true;
$scope.disableSubmitBtnPR=true;
$scope.disableAddPickupBtn=true;
$scope.checkSubmitBtn=function(){
if(($scope.buyCustomerSelected !=undefined )&& ($scope.supplierSelected !=undefined )&& ($scope.startDate !=undefined ) && ($scope.endDate !=undefined )){
$scope.disableSubmitBtn=false;
}
if(($scope.buyCustomerSelectedRMT !=undefined )&& ($scope.supplierSelectedRMT !=undefined )&& ($scope.startDateRMT !=undefined ) && ($scope.endDateRMT !=undefined )){
$scope.disableSubmitBtnRMT=false;
}
if(($scope.buyCustomerSelectedPR !=undefined )&& ($scope.supplierSelectedPR !=undefined )){
$scope.disableSubmitBtnPR=false;
}
}
customerService.getAllBuyCustomers().then(function(response){
$scope.buyCustomers = response;
});
incidentTypeService.getAllIncidentTypes().then(function(response){
$scope.incidentTypes = response;
var c=$scope.incidentTypes.length+1;
var incident= new String('All Incidents' + c)
var incident = {};
incident.incidentDescription = "All Incidents";
$scope.incidentTypes.splice(0,0,incident);
});
$scope.getBuyCustomerDetails = function(buyCustomer)
{
$scope.loaderDetailedReport=true;
$scope.loaderRmtReport = true;
$scope.loaderPendingReport=true;
customerService.getSuppliersForBuyCustomer(buyCustomer).then(function(response){
$scope.suppliersForCustomerSelected = response;
$scope.loaderDetailedReport= false;
$scope.loaderRmtReport = false;
$scope.loaderPendingReport= false;
});
};
$scope.getBalePickups = function(buyCustomer ,supplier ,incidentType ,startDate, endDate){
$scope.loaderDetailedReport=true;
if($scope.selectAllIncident == true){
incidentType=$scope.selectAllIncidentTypeObj
}
var balePickupFilterDTO = {};
balePickupFilterDTO.buyCustomer = buyCustomer;
balePickupFilterDTO.supplier = supplier;
balePickupFilterDTO.incidentType = incidentType;
balePickupFilterDTO.startDate = startDate;
balePickupFilterDTO.endDate = endDate;
reportService.getAllPickups(balePickupFilterDTO).then(function(response){
$scope.balePickupList = response.data;
$scope.loaderDetailedReport=false;
});
};
$scope.getBalePickupsRMT = function(buyCustomer ,supplier ,startDate, endDate){
$scope.loaderRmtReport=true;
var balePickupFilterDTO = {};
balePickupFilterDTO.buyCustomer = buyCustomer;
balePickupFilterDTO.supplier = supplier;
balePickupFilterDTO.startDate = startDate;
balePickupFilterDTO.endDate = endDate;
reportService.getAllPickups(balePickupFilterDTO).then(function(response){
$scope.balePickupListRMT = response.data;
$scope.loaderRmtReport= false;
});
};
$scope.getPendingBalePickups = function(buyCustomerId,supplierId){
console.log("------buyCustomerId---"+JSON.stringify(buyCustomerId))
console.log("------supplierId---"+JSON.stringify(supplierId))
$scope.loaderPendingReport = true;
var PendingStoreReportDTO = {};
PendingStoreReportDTO.buyCustomerId = buyCustomerId.customerId;
PendingStoreReportDTO.supplierId = supplierId.supplierId;
reportService.getPendingPickups(PendingStoreReportDTO).then(function(response){
$scope.balePickupLists = response.data;
$scope.loaderPendingReport = false;
});
};
$scope.EndDateFun = function() {
$scope.EndDate.opened = true;
$scope.dateOptionsss = {
datepickerMode:'day',
minMode:'day',
startingDay: 1,
showWeeks:false,
formatMonth:'MMM',
formatYear: 'yyyy',
monthColumns:4,
}
};
$scope.EndDate = {
opened: false
};
$scope.StartDateFun = function() {
$scope.StartDate.opened = true;
$scope.dateOptionsStart = {
datepickerMode:'day',
minMode:'day',
startingDay: 1,
showWeeks:false,
formatMonth:'MMM',
formatYear: 'yyyy',
monthColumns:4,
}
};
$scope.StartDate = {
opened: false
};
$scope.EndDateFunRMT = function(){
$scope.EndDateRMT.opened = true;
$scope.dateOptionsEnd = {
datepickerMode:'day',
minMode:'day',
startingDay: 1,
showWeeks:false,
formatMonth:'MMM',
formatYear: 'yyyy',
monthColumns:4,
}
};
$scope.EndDateRMT = {
opened: false
};
$scope.StartDateFunRMT = function() {
$scope.StartDateRMT.opened = true;
$scope.dateOptionsStart = {
datepickerMode:'day',
minMode:'day',
startingDay: 1,
showWeeks:false,
formatMonth:'MMM',
formatYear: 'yyyy',
monthColumns:4,
}
};
$scope.StartDateRMT = {
opened: false
};
$scope.downloadExcel = function(){
var blob = new Blob([document.getElementById('rmtReportDiv').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
}
$scope.downloadPdf = function(){
console.log("---download Pdf---");
var marginTop;
var doc = new jsPDF('l', 'pt');
var table = document.getElementById('rmtReportTable');
console.log("---table ---"+table);
var rows = tableToJson(table);
doc.autoTable(columns, rows, {
styles : {
overflow : 'linebreak'
},
theme : 'grid',
headerStyles : {
fillColor : [ 160, 160, 160 ]
},
});
doc.save('report.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
columns = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
columns.push(table.rows[0].cells[i].innerHTML);
}
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(
/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = [];
for (var j = 0; j < tableRow.cells.length; j++) {
if (headers[j] == 'time') {
if (!tableRow.cells[j].childNodes[0].text) {
rowData.push(tableRow.cells[j].childNodes[0].data);
} else {
rowData.push(tableRow.cells[j].childNodes[0].innerHTML);
}
} else {
rowData.push(tableRow.cells[j].innerHTML);
}
}
data.push(rowData);
}
return data;
}
$scope.reportExcel = function(){
var blob = new Blob([document.getElementById('detailedReportDiv').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
}
$scope.reportPdf = function(){
console.log("---download Pdf---");
var marginTop;
var doc = new jsPDF('l', 'pt');
var table = document.getElementById('detailedReportTable');
console.log("---table ---"+table);
var rows = tableToJson(table);
doc.autoTable(columns, rows, {
styles : {
overflow : 'linebreak'
},
theme : 'grid',
headerStyles : {
fillColor : [ 160, 160, 160 ]
},
});
doc.save('report.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
columns = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
columns.push(table.rows[0].cells[i].innerHTML);
}
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(
/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = [];
for (var j = 0; j < tableRow.cells.length; j++) {
if (headers[j] == 'time') {
if (!tableRow.cells[j].childNodes[0].text) {
rowData.push(tableRow.cells[j].childNodes[0].data);
} else {
rowData.push(tableRow.cells[j].childNodes[0].innerHTML);
}
} else {
rowData.push(tableRow.cells[j].innerHTML);
}
}
data.push(rowData);
}
return data;
}
$scope.pendingreportExcel = function(){
var blob = new Blob([document.getElementById('pendingReportDiv').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
}
$scope.pendingreportPdf = function(){
console.log("---download Pdf---");
var marginTop;
var doc = new jsPDF('l', 'pt');
var table = document.getElementById('pendingReportTable');
console.log("---table ---"+table);
var rows = tableToJson(table);
doc.autoTable(columns, rows, {
styles : {
overflow : 'linebreak'
},
theme : 'grid',
headerStyles : {
fillColor : [ 160, 160, 160 ]
},
});
doc.save('report.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
columns = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
columns.push(table.rows[0].cells[i].innerHTML);
}
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(
/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = [];
for (var j = 0; j < tableRow.cells.length; j++) {
if (headers[j] == 'time') {
if (!tableRow.cells[j].childNodes[0].text) {
rowData.push(tableRow.cells[j].childNodes[0].data);
} else {
rowData.push(tableRow.cells[j].childNodes[0].innerHTML);
}
} else {
rowData.push(tableRow.cells[j].innerHTML);
}
}
data.push(rowData);
}
return data;
}
$scope.changeLongToStringDate = function(balePickup){
var divertDate=balePickup.divertDate;
var pickupDate=balePickup.pickupDate;
if(divertDate != null ){
var date = new Date(divertDate);
var month=date.getMonth() + 1;
var day=date.getDate();
var year=date.getFullYear();
if(month <10){
month='0' + month;
}
if(day <10){
day='0' + day;
}
var strDate = month + '/' + day+ '/' + year;
console.log("================divertedDate=="+strDate);
console.log("+++++++++++++++++++++++++pickupDate++"+pickupDate);
if(strDate == pickupDate){
return balePickup.divertTripDriverFirstName + ' '+ balePickup.divertTripDriverLastName;
}
}
return balePickup.tripDriverFirstName + ' ' +balePickup.tripDriverLastName;
}
$scope.getBuyCustomerCode= function(balePickup){
var returnValue= balePickup.buyCustomerSiteAlternativeSearchReference != '' ? balePickup.buyCustomerSiteAlternativeSearchReference : balePickup.buyCustomerAlternativeSearchReference
return returnValue;
}
$scope.getSellCustomerSiteCode= function(balePickup){
var returnValue=balePickup.sellCustomerSiteAlternativeSearchReference != '' ? balePickup.sellCustomerSiteAlternativeSearchReference : balePickup.sellCustomerAlternativeSearchReference;
return returnValue;
}
});
<file_sep>/src/main/webapp/resources/js/angular/app/incidenttypemanagement.js
brtaApp.controller("incidentTypeManagementController",function(applicationContextURL,$scope,$http,incidentTypeService){
$scope.showaddincidenttype = function(){
$scope.addIncidentType = true;
$scope.incidentType = {};
}
$scope.editingData = [];
incidentTypeService.getAllIncidentTypes().then(function(response){
$scope.incidentTypes = response;
for (var i = 0, length = $scope.incidentTypes.length; i < length; i++) {
$scope.editingData[$scope.incidentTypes[i].incidentTypeId] = false;
}
console.log(JSON.stringify($scope.incidentTypes));
})
$scope.checkIncidentUnique = function(incidentType){
if(incidentType != undefined){
incidentTypeService.checkIncidentUnique(incidentType).then(function(response){
$scope.incidentTypeUnique= response.status
if( response.status == true){
$scope.incident_unique_error= true
} });
}
}
$scope.addIncidentTypeDetails = function(incidentType){
$scope.error = false;
if($scope.incidentType.incidentDescription == "" || $scope.incidentType.incidentDescription== null )
{
$scope.incident_des_error = true;
$scope.error = true;
}
if( $scope.incidentTypeUnique == true){
$scope.incident_unique_error= true;
$scope.error = true;
}
if(!$scope.error){
if(incidentType.enabled=='Active'){
incidentType.enabled = true;
}
else{
incidentType.enabled = false;
}
incidentTypeService.addIncidentType(incidentType).then(function(response){
$scope.incidentTypes = response;
console.log(JSON.stringify($scope.incidentTypes));
if($scope.incidentTypes != null && $scope.incidentTypes != ""){
$scope.addIncidentType = false;
incidentType = {};
}
});
}
}
$scope.checkIncidentUniqueForEdit = function(incidentType, incidentId){
if((incidentType != $scope.selectedIncidentDescription) && (incidentType != undefined)){
incidentTypeService.checkIncidentUnique(incidentType).then(function(response){
if( response.status == true){
var errorMsgName= "incident_unique_error_" + incidentId;
console.log("===errorMsgName==="+errorMsgName);
$scope[errorMsgName] = true;
}
});
}
}
var originalIncidentTypeWithoutEdit = {};
$scope.modify = function(tableData){
$scope.incidentType = tableData;
originalIncidentTypeWithoutEdit = angular.copy(tableData);
if(tableData.enabled == true){
$scope.incidentType.enabled = 'Active';
}
else{
$scope.incidentType.enabled = 'Inactive';
}
$scope.selectedIncidentDescription =tableData.incidentDescription;
$scope.editingData[tableData.incidentTypeId] = true;
var errorMsgName= "incident_unique_error_" + tableData.incidentTypeId;
console.log("===errorMsgName==="+errorMsgName);
$scope[errorMsgName] = false;
};
$scope.cancel = function(tableData){
for(var i=0;i< $scope.incidentTypes.length;i++){
if($scope.incidentTypes[i].incidentTypeId == tableData.incidentTypeId){
$scope.incidentTypes[i] =originalIncidentTypeWithoutEdit
break;
}
}
$scope.editingData[tableData.incidentTypeId] = false;
};
$scope.editIncentiveTypeDetails = function(incidentType){
$scope.error = false;
var incidentId= "incident_unique_error_" + incidentType.incidentTypeId;
if($scope.incidentType.incidentDescription == "" || $scope.incidentType.incidentDescription== null )
{
var incidentId= "incident_des_error_" + incidentType.incidentTypeId;
$scope[incidentId] = true;
$scope.error = true;
}
if( $scope[incidentId] == true){
$scope[incidentId] = true;
$scope.error = true;
}
if(!$scope.error){
if(incidentType.enabled =='Active'){
incidentType.enabled = true;
}
else{
incidentType.enabled = false;
}
incidentTypeService.editIncidentType(incidentType).then(function(response){
$scope.incidentTypes = response;
$scope.editingData[incidentType.incidentTypeId] = false;
})
}
}
});<file_sep>/src/main/webapp/resources/js/angular/app/landing.js
brtaApp.controller("sideMenuController",function(applicationContextURL,$rootScope,$scope,$http,userService){
userService.getLoggedInUserDetails().then(function(response){
$scope.user = response;
console.log(JSON.stringify(response));
if($scope.user.role=='ROBRCSR')
{
$scope.showstoreManagement = true;
$scope.userManagement = true;
$scope.storeAssignment = true;
$scope.balePickup = true;
$scope.reports = true;
$scope.supplierManagement =true;
}
if($scope.user.role=='ROBRMANAGER'){
$scope.showincidentManagement = true;
$scope.incidentManagement = true;
$scope.reports = true;
$scope.userManagement = true;
$scope.storeAssignment = true;
$scope.balePickup = true;
}
})
$scope.backClickFun=function(){
$rootScope.backClick=!$rootScope.backClick;
}
});
brtaApp.controller("welcomeUserController",function(applicationContextURL,$scope,$http,userService){
$scope.greetingMessage = "";
var currDate = new Date();
if(currDate.getHours()>=0 && currDate.getHours()<12){
$scope.greetingMessage = "Good Morning";
}
if(currDate.getHours()>=12 && currDate.getHours()<16){
$scope.greetingMessage = "Good Afternoon";
}
if(currDate.getHours()>=16 && currDate.getHours()<24){
$scope.greetingMessage = "Good Evening";
}
console.log($scope.greetingMessage);
});
<file_sep>/src/main/java/com/wm/brta/service/impl/BalePickupConfigurationServiceImpl.java
package com.wm.brta.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wm.brta.constants.ApplicationCommonConstants;
import com.wm.brta.dao.BalePickUpAssignmentDAO;
import com.wm.brta.dao.ConfigurationDao;
import com.wm.brta.dao.MasterDataDao;
import com.wm.brta.domain.BalePickupAssignment;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.BalePickupSupplierSiteConfiguration;
import com.wm.brta.domain.CustomerSite;
import com.wm.brta.domain.User;
import com.wm.brta.dto.UserDTO;
import com.wm.brta.service.ConfigurationService;
@Component("configurationService")
@Transactional
public class BalePickupConfigurationServiceImpl implements ConfigurationService {
@Autowired
ConfigurationDao configDao;
@Autowired
MasterDataDao masterDataDao;
@Autowired
BalePickUpAssignmentDAO balePickupassignmentDAO;
//@Autowired BalePickupServiceImpl balePickupServiceImpl;
@Override
public String addSupplierMaterialConfigData(
List<BalePickupSupplierSiteConfiguration> supplierSiteConfigList,List<BalePickupMaterialConfiguration> materialConfigList,
boolean editAction,UserDTO user) {
boolean errorFlag = false;
CustomerSite customerSite = supplierSiteConfigList.get(0).getCustomerSite();
masterDataDao.mergeCustomerSite(customerSite);
if(editAction){
configDao.deleteSupplierConfigurationRecordsForCustomerSite(customerSite);
configDao.deleteMaterialConfigurationRecordsForCustomerSite(customerSite);
}
for(BalePickupSupplierSiteConfiguration supplierSiteConfig:supplierSiteConfigList){
supplierSiteConfig.setUpdatedBy(user.getFirstName());
supplierSiteConfig.setCreateDate(new Date());
supplierSiteConfig.setUpdatedAt(new Date());
supplierSiteConfig.setEnabled(true);
int supplierSiteConfigId = configDao.addSupplierSiteConfigData(supplierSiteConfig);
if(supplierSiteConfigId==0){
errorFlag = true;
}
}
// TODO Update the BalePickupAssignment table to disable all the records by customerSite
List<BalePickupAssignment> _assignments = new ArrayList<BalePickupAssignment>(balePickupassignmentDAO.getPickupAssignmentsForCustomerSite(customerSite));
balePickupassignmentDAO.delete(_assignments);
for(BalePickupMaterialConfiguration materialConfig:materialConfigList){
materialConfig.setUpdatedBy(user.getFirstName());
materialConfig.setUpdatedAt(new Date());
materialConfig.setCreateDate(new Date());
int materialConfigId = configDao.addMaterialConfigData(materialConfig);
if(materialConfigId==0){
errorFlag = true;
}
}
if(!errorFlag){
return ApplicationCommonConstants.INSERTION_SUCCESSFULL_MESSAGE;
}
else{
return ApplicationCommonConstants.INSERTION_FAILURE_MESSAGE;
}
}
}
<file_sep>/src/main/java/com/wm/brta/util/BaleUtils.java
package com.wm.brta.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.mockito.Mockito;
import net.iharder.Base64;
public class BaleUtils {
private static SessionFactory mockedSessionFactory;
private static Session mockedSession;
private static Transaction mockedTransaction;
public static Integer getWeekNumber(String date) throws ParseException {
String format = "MM/dd/yyyy";
SimpleDateFormat df = new SimpleDateFormat(format);
Date dateFormat = df.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat);
int weeknumber = cal.get(Calendar.WEEK_OF_MONTH);
if (cal.get(Calendar.DAY_OF_WEEK) == 1)
weeknumber = weeknumber - 1;
return weeknumber;
}
public static Integer getDay(String date) throws ParseException {
String format = "MM/dd/yyyy";
SimpleDateFormat df = new SimpleDateFormat(format);
Date dateFormat = df.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat);
int day = cal.get(Calendar.DAY_OF_WEEK);
day = day - 1;
if (day == 0)
day = 7;
return day;
}
public static List<String> getLastOneWeekDates() {
List<String> dateList=new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -8);
// loop adding one day in each iteration
for(int i = 0; i< 7; i++){
cal.add(Calendar.DAY_OF_YEAR, 1);
dateList.add(sdf.format(cal.getTime()));
}
return dateList;
}
public static void setUpMokito() {
mockedSessionFactory = Mockito.mock(SessionFactory.class);
mockedSession = Mockito.mock(Session.class);
mockedTransaction = Mockito.mock(Transaction.class);
}
public static String convertWeekNumberAndDayToDate1(int weekNumber, int day,
Date startDate) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
if (day == 7) {
day = 0;
weekNumber = weekNumber + 1;
}
cal.set(Calendar.WEEK_OF_MONTH, weekNumber);
boolean entryFlag = false;
cal.set(Calendar.MONTH, cal.getTime().getMonth());
cal.set(Calendar.DAY_OF_WEEK, day + 1);
String dateToreturn = sdf.format(cal.getTime());
Calendar startDateCalendar = Calendar.getInstance();
Calendar todaysDatecalendar = Calendar.getInstance();
Calendar dateToReturnCalendar = Calendar.getInstance();
if (startDate.after(new Date())) {
if (startDate.after(new Date(dateToreturn))) {
cal.set(Calendar.WEEK_OF_MONTH, weekNumber);
startDateCalendar.setTime(startDate);
cal.set(Calendar.MONTH,
startDateCalendar.getTime().getMonth() + 1);
cal.set(Calendar.DAY_OF_WEEK, day + 1);
dateToreturn = sdf.format(cal.getTime());
}
}
if ( (startDate.before(new Date()) || startDate.equals(new Date()))) {
if (new Date().getMonth() == (new Date(dateToreturn)).getMonth()
&& new Date().getYear() == (new Date(dateToreturn))
.getYear()
&& new Date().getDate() == (new Date(dateToreturn)).getDate()) {
cal.set(Calendar.WEEK_OF_MONTH, weekNumber);
todaysDatecalendar.setTime(new Date());
cal.set(Calendar.MONTH, todaysDatecalendar.getTime().getMonth());
cal.set(Calendar.DAY_OF_WEEK, day + 1);
dateToreturn = sdf.format(cal.getTime());
}
else if (new Date().after(new Date(dateToreturn))) {
cal.set(Calendar.WEEK_OF_MONTH, weekNumber);
todaysDatecalendar.setTime(new Date());
cal.set(Calendar.MONTH,
todaysDatecalendar.getTime().getMonth() + 1);
cal.set(Calendar.DAY_OF_WEEK, day + 1);
dateToreturn = sdf.format(cal.getTime());
}
}
return dateToreturn;
}
public static String convertWeekNumberAndDayToDate(int weekNumber,int day){
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
if(day == 7){
day = 0;
weekNumber = weekNumber + 1;
}
cal1.set(Calendar.WEEK_OF_MONTH, weekNumber);
cal1.set(Calendar.MONTH, cal.getTime().getMonth());
cal1.set(Calendar.DAY_OF_WEEK, day+1);
String dateToreturn = sdf.format(cal1.getTime());
return dateToreturn;
}
public static byte[] loadFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
is.close();
return bytes;
}
public static String encodedBase64String(String filePath){
String encodedString="";
try {
File file = new File(filePath.toString());
if (file.length() > 0) {
byte[] bytes = BaleUtils.loadFile(file);
byte[] encoded = org.apache.tomcat.util.codec.binary.Base64.encodeBase64(bytes);
encodedString = new String(encoded);
}
} catch (Exception e) {
System.out.println("======exception while reading file ====" + e);
}
return encodedString;
}
public static String convertWeekNumberAndDayToDate(int weekNumber, int dayNumber, Date startDate) {
//System.out.println("===weekNo="+weekNumber +" =====dayNumber="+dayNumber+ "======startDate="+startDate);
int _dayOfTheWeek = getDayOfTheWeek(dayNumber);
Date _baseDate = new Date();
if ((startDate != null) && startDate.after(_baseDate)) {
_baseDate = startDate;
}
Calendar _cal = Calendar.getInstance();
_cal.setFirstDayOfWeek(Calendar.MONDAY);
_cal.setTime(_baseDate);
Calendar _nextDateCal = Calendar.getInstance();
_nextDateCal.setFirstDayOfWeek(Calendar.MONDAY);
Calendar _calcDateCal = Calendar.getInstance();
_calcDateCal.setFirstDayOfWeek(Calendar.MONDAY);
int _monthNumber = _cal.get(Calendar.MONTH);
boolean _checkMonth = true;
do {
_nextDateCal.set(Calendar.MONTH, _monthNumber);
_nextDateCal.set(Calendar.WEEK_OF_MONTH, weekNumber);
_nextDateCal.set(Calendar.DAY_OF_WEEK, _dayOfTheWeek);
_monthNumber++;
if (_monthNumber > 12) {
_monthNumber = 1;
_checkMonth = false;
}
// Following code is to ensure even if it is today's date, it is greater than _baseDate
_calcDateCal.setTime(_nextDateCal.getTime());
_calcDateCal.set(Calendar.HOUR_OF_DAY, 23);
_calcDateCal.set(Calendar.MINUTE, 59);
_calcDateCal.set(Calendar.SECOND, 59);
_calcDateCal.set(Calendar.MILLISECOND, 59);
} while (!((_calcDateCal.getTime().after(_baseDate))
&& ((_calcDateCal.get(Calendar.MONTH) >= _cal.get(Calendar.MONTH)) || !_checkMonth)
&& (_calcDateCal.get(Calendar.WEEK_OF_MONTH) == weekNumber)
&& (_calcDateCal.get(Calendar.DAY_OF_WEEK) == _dayOfTheWeek)));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String dateString= sdf.format(_calcDateCal.getTime());
return dateString;
}
/**
* Returns Java day of the week
*
* @param dayNumberStartingMonday
* @return
*/
private static int getDayOfTheWeek(int dayNumberStartingMonday) {
int _dayOfTheWeek = Calendar.SUNDAY;
switch (dayNumberStartingMonday) {
case 1:
_dayOfTheWeek = Calendar.MONDAY;
break;
case 2:
_dayOfTheWeek = Calendar.TUESDAY;
break;
case 3:
_dayOfTheWeek = Calendar.WEDNESDAY;
break;
case 4:
_dayOfTheWeek = Calendar.THURSDAY;
break;
case 5:
_dayOfTheWeek = Calendar.FRIDAY;
break;
case 6:
_dayOfTheWeek = Calendar.SATURDAY;
break;
case 7:
_dayOfTheWeek = Calendar.SUNDAY;
break;
default:
break;
}
return _dayOfTheWeek;
}
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
}
<file_sep>/src/main/java/com/wm/brta/domain/UserAccount.java
package com.wm.brta.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Table(name="[useraccount]")
@Entity
public class UserAccount {
private long accountId;
private User user;
private Role role;
//private AccessLevel access;
private Date createdDate;
private Date updatedAt;
private String updatedBy;
private boolean isEnabled;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "acctid", unique = true, nullable = false)
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userid", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "roleid", nullable = false)
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
// @OneToOne(fetch = FetchType.EAGER)
// @JoinColumn(name = "accessid", nullable = false)
// public AccessLevel getAccess() {
// return access;
// }
// public void setAccess(AccessLevel access) {
// this.access = access;
// }
@Column(name = "createdate")
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Column(name = "updatedat")
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Column(name = "updatedby", nullable = false)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
@Column(name = "enabled", nullable = false)
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
<file_sep>/src/main/java/com/wm/brta/dto/ConfigurationDataDTO.java
package com.wm.brta.dto;
import java.util.List;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.BalePickupSupplierSiteConfiguration;
public class ConfigurationDataDTO {
List<BalePickupSupplierSiteConfiguration> supplierSiteConfig;
List<BalePickupMaterialConfiguration> materialConfig;
boolean editAction;
@Override
public String toString() {
return "ConfigurationDataDTO [supplierSiteConfig=" + supplierSiteConfig
+ ", materialConfig=" + materialConfig + "]";
}
public List<BalePickupSupplierSiteConfiguration> getSupplierSiteConfig() {
return supplierSiteConfig;
}
public void setSupplierSiteConfig(
List<BalePickupSupplierSiteConfiguration> supplierSiteConfig) {
this.supplierSiteConfig = supplierSiteConfig;
}
public List<BalePickupMaterialConfiguration> getMaterialConfig() {
return materialConfig;
}
public void setMaterialConfig(
List<BalePickupMaterialConfiguration> materialConfig) {
this.materialConfig = materialConfig;
}
public boolean isEditAction() {
return editAction;
}
public void setEditAction(boolean editAction) {
this.editAction = editAction;
}
}
<file_sep>/src/main/java/com/wm/brta/security/AuthorizationFilter.java
package com.wm.brta.security;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import com.wm.brta.domain.User;
import com.wm.brta.dto.UserDTO;
import com.wm.brta.service.LoginService;
@Component
public class AuthorizationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(
(HttpServletResponse) res);
MyRequestWrapper multiReadRequest = new MyRequestWrapper(
(HttpServletRequest) req);
String url = ((HttpServletRequest) multiReadRequest).getRequestURL()
.toString();
String queryString = ((HttpServletRequest) multiReadRequest)
.getQueryString();
if (url.contains("/app/service") || url.contains("/landing.jsp") || url.contains("/app/resources")
|| url.contains("/logout")|| url.contains("/app/views") ||url.contains("/common") || url.endsWith("/app/")
|| url.endsWith("/app")|| url.contains("/get/")|| url.contains("/app/")){
chain.doFilter(multiReadRequest, res);
}else{
HttpSession session = session();
String role = (String) session.getAttribute("sm_groups");
if(role!=null){
if (url.contains("/app/incidentMgmt")) {
if(role.equals("ROBRMANAGER")){
chain.doFilter(multiReadRequest, res);
}else{
responseWrapper.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized");
}
} else if(url.contains("/app/reportMgmt")){
chain.doFilter(multiReadRequest, res);
}else{
if(role.equals("ROBRCSR")){
chain.doFilter(multiReadRequest, res);
}else{
responseWrapper.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized");
}
}
}else{
//chain.doFilter(multiReadRequest, res);
responseWrapper.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized");
}
}
}
@Override
public void destroy() {
}
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
}<file_sep>/src/main/java/com/wm/brta/dto/PickupDetailsWithMasterSets.java
package com.wm.brta.dto;
import java.util.HashSet;
import com.wm.brta.domain.IncidentType;
import com.wm.brta.domain.Material;
public class PickupDetailsWithMasterSets {
PickupDetails pickupDetails;
HashSet<Material> materials;
HashSet<IncidentType>incidentTypes;
public PickupDetails getPickupDetails() {
return pickupDetails;
}
public void setPickupDetails(PickupDetails pickupDetails) {
this.pickupDetails = pickupDetails;
}
public HashSet<Material> getMaterials() {
return materials;
}
public void setMaterials(HashSet<Material> materials) {
this.materials = materials;
}
public HashSet<IncidentType> getIncidentTypes() {
return incidentTypes;
}
public void setIncidentTypes(HashSet<IncidentType> incidentTypes) {
this.incidentTypes = incidentTypes;
}
}
<file_sep>/src/main/java/com/wm/brta/controller/web/BalePickUpAssignmentController.java
package com.wm.brta.controller.web;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wm.brta.domain.BalePickupAssignment;
import com.wm.brta.domain.CustomerSite;
import com.wm.brta.dto.ActivityListInputPayload;
import com.wm.brta.dto.AssignmentFilterDTO;
import com.wm.brta.dto.BalePickupAssignmentDTO;
import com.wm.brta.dto.Destination;
import com.wm.brta.dto.OutputResponse;
import com.wm.brta.dto.UserDTO;
import com.wm.brta.service.BalePickupService;
@Controller
public class BalePickUpAssignmentController
{
@Autowired
BalePickupService balePickupService;
private static final Logger LOGGER = LoggerFactory.getLogger(BalePickUpAssignmentController.class);
@RequestMapping(value="/assignMgmt/pickups",method = RequestMethod.POST)
@ResponseBody
public HashSet<Destination> getAllDestinationsForWeb(@RequestBody ActivityListInputPayload activitylistPayLoad){
HashSet<Destination>destinationsToReturn = null;
try{
destinationsToReturn= balePickupService.getAllDestinations(activitylistPayLoad);
}catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:getAllDestinations=====>"+ e);
}
return destinationsToReturn;
}
@RequestMapping(value="/assignMgmt/add/pickupassignments",method = RequestMethod.POST)
@ResponseBody
public OutputResponse addPickuoAssignments(@RequestBody BalePickupAssignmentDTO assignmentDTO,HttpServletRequest request){
OutputResponse response = new OutputResponse();
HttpSession session = request.getSession();
UserDTO user = (UserDTO)session.getAttribute("user");
try{
balePickupService.addBalePickupAssignments(assignmentDTO,user);
}catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:addBalePickupAssignments=====>"+ e);
}
return response;
}
@RequestMapping(value="/assignMgmt/getAll/pickupassignments",method = RequestMethod.POST)
@ResponseBody
public Set<BalePickupAssignment> getAllPickupAssignments(@RequestBody AssignmentFilterDTO assignmentFilter){
Set<BalePickupAssignment> assignments=null;
try{
assignments = balePickupService.getPickupAssignments(assignmentFilter);
}catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:getPickupAssignments=====>" +e);
}
return assignments;
}
///get/assignments/bycustomerSite
@RequestMapping(value="/assignMgmt/get/assignments/bycustomerSite",method = RequestMethod.POST)
@ResponseBody
public Set<BalePickupAssignment> getAllPickupAssignmentsByCustomerSite(@RequestBody CustomerSite customerSite){
Set<BalePickupAssignment> assignments=null;
try{
assignments = balePickupService.getPickupAssignmentsForCustomerSite(customerSite);
}catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:getPickupAssignmentsForCustomerSite=====>" +e);
}
return assignments;
}
///update/pickupassignments
@RequestMapping(value="/assignMgmt/update/pickupassignments",method = RequestMethod.POST)
@ResponseBody
public OutputResponse updatePickupAssignmentstoAssignActivity(@RequestBody List<BalePickupAssignment> assignments,HttpServletRequest request){
OutputResponse response = new OutputResponse();
HttpSession session = request.getSession();
UserDTO user = (UserDTO)session.getAttribute("user");
balePickupService.updateBalePickupAssignmentstoAssignActivity(assignments,user);
return response;
}
@RequestMapping(value="/assignMgmt/add/newdriver",method = RequestMethod.POST)
@ResponseBody
public OutputResponse assignNewDriver(@RequestBody BalePickupAssignment assignment){
OutputResponse response = new OutputResponse();
try{
String status = balePickupService.assignNewDriver(assignment);
response.setMessage(status);
}
catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:assignNewDriver=====>" +e);
}
return response;
}
@RequestMapping(value="/assignMgmt/remove/newdriver",method = RequestMethod.POST)
@ResponseBody
public OutputResponse removeNewDriver(@RequestBody BalePickupAssignment assignment){
OutputResponse response = new OutputResponse();
try{
String status = balePickupService.removeNewDriver(assignment);
response.setMessage(status);
}
catch(Exception e){
LOGGER.error("Error:BalePickUpAssignmentController:removeNewDriver=====>" +e);
}
return response;
}
}<file_sep>/src/main/java/com/wm/brta/domain/PendingReport.java
package com.wm.brta.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name ="Pendingreport")
public class PendingReport {
@Id
@Column(name = "balepickupassignmentid")
private Integer balePickupAssignmentId;
@Column(name = "driver")
private Integer driver;
@Column(name = "supplierid")
private Integer supplierId;
@Column(name = "weeknumber")
private Integer weekNumber;
@Column(name = "day")
private Integer day;
@Column(name = "divertdate")
private Date divertDate;
@Column(name = "diverteduserid")
private Integer divertedUserId;
@Column(name = "buycustomersiteid")
private Integer buyCustomerSiteId;
@Column(name = "sellcustomersiteid")
private Integer sellCustomerSiteId;
@Column(name = "buycustomersitename")
private String buyCustomerSiteName;
@Column(name = "buycustomerlocationid")
private Integer buyCustomerLocationId;
@Column(name = "buycustomerhousenumber")
private String buyCustomerHouseNumber;
@Column(name = "buycustomeraddress1")
private String buyCustomerAddress1;
@Column(name = "buycustomeraddress2")
private String buyCustomerAddress2;
@Column(name = "buycustomeraddress3")
private String buyCustomerAddress3;
@Column(name = "buycustomeraddress4")
private String buyCustomerAddress4;
@Column(name = "buycustomeraddress5")
private String buyCustomerAddress5;
@Column(name = "buycustomerpostcode")
private String buyCustomerPostCode;
@Column(name = "buycustomertelno")
private String buyCustomerTelNo;
@Column(name = "buycustomerid")
private Integer buyCustomerId;
@Column(name = "buycustomername")
private String buyCustomerName;
@Column(name = "buycustomeralternativesearchreference")
private String buyCustomerAlternativeSearchReference;
@Column(name = "tripdriverfirstname")
private String tripDriverFirstName;
@Column(name = "tripdriverlastname")
private String tripDriverLastName;
@Column(name = "tripdriveremail")
private String tripDriverEmail;
@Column(name = "tripdrivermobile")
private String tripDriverMobile;
@Column(name = "diverttripdriverfirstname")
private String divertTripDriverFirstName;
@Column(name = "diverttripdriverlastname")
private String divertTripDriverLastName;
@Column(name = "diverttripdriveremail")
private String divertTripDriverEmail;
@Column(name = "diverttripdrivermobile")
private String divertTripDriverMobile;
public String getDivertTripDriverEmail() {
return divertTripDriverEmail;
}
public void setDivertTripDriverEmail(String divertTripDriverEmail) {
this.divertTripDriverEmail = divertTripDriverEmail;
}
public String getDivertTripDriverMobile() {
return divertTripDriverMobile;
}
public void setDivertTripDriverMobile(String divertTripDriverMobile) {
this.divertTripDriverMobile = divertTripDriverMobile;
}
public String getDivertTripDriverFirstName() {
return divertTripDriverFirstName;
}
public void setDivertTripDriverFirstName(String divertTripDriverFirstName) {
this.divertTripDriverFirstName = divertTripDriverFirstName;
}
public String getDivertTripDriverLastName() {
return divertTripDriverLastName;
}
public void setDivertTripDriverLastName(String divertTripDriverLastName) {
this.divertTripDriverLastName = divertTripDriverLastName;
}
@Transient
private String pickupDate;
public String getPickupDate() {
return pickupDate;
}
public void setPickupDate(String pickupDate) {
this.pickupDate = pickupDate;
}
public Integer getBalePickupAssignmentId() {
return balePickupAssignmentId;
}
public void setBalePickupAssignmentId(Integer balePickupAssignmentId) {
this.balePickupAssignmentId = balePickupAssignmentId;
}
public Integer getDriver() {
return driver;
}
public void setDriver(Integer driver) {
this.driver = driver;
}
public Integer getSupplierId() {
return supplierId;
}
public void setSupplierId(Integer supplierId) {
this.supplierId = supplierId;
}
public Integer getWeekNumber() {
return weekNumber;
}
public void setWeekNumber(Integer weekNumber) {
this.weekNumber = weekNumber;
}
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
public Date getDivertDate() {
return divertDate;
}
public void setDivertDate(Date divertDate) {
this.divertDate = divertDate;
}
public Integer getDivertedUserId() {
return divertedUserId;
}
public void setDivertedUserId(Integer divertedUserId) {
this.divertedUserId = divertedUserId;
}
public Integer getBuyCustomerSiteId() {
return buyCustomerSiteId;
}
public void setBuyCustomerSiteId(Integer buyCustomerSiteId) {
this.buyCustomerSiteId = buyCustomerSiteId;
}
public Integer getSellCustomerSiteId() {
return sellCustomerSiteId;
}
public void setSellCustomerSiteId(Integer sellCustomerSiteId) {
this.sellCustomerSiteId = sellCustomerSiteId;
}
public String getBuyCustomerSiteName() {
return buyCustomerSiteName;
}
public void setBuyCustomerSiteName(String buyCustomerSiteName) {
this.buyCustomerSiteName = buyCustomerSiteName;
}
public Integer getBuyCustomerLocationId() {
return buyCustomerLocationId;
}
public void setBuyCustomerLocationId(Integer buyCustomerLocationId) {
this.buyCustomerLocationId = buyCustomerLocationId;
}
public String getBuyCustomerHouseNumber() {
return buyCustomerHouseNumber;
}
public void setBuyCustomerHouseNumber(String buyCustomerHouseNumber) {
this.buyCustomerHouseNumber = buyCustomerHouseNumber;
}
public String getBuyCustomerAddress1() {
return buyCustomerAddress1;
}
public void setBuyCustomerAddress1(String buyCustomerAddress1) {
this.buyCustomerAddress1 = buyCustomerAddress1;
}
public String getBuyCustomerAddress2() {
return buyCustomerAddress2;
}
public void setBuyCustomerAddress2(String buyCustomerAddress2) {
this.buyCustomerAddress2 = buyCustomerAddress2;
}
public String getBuyCustomerAddress3() {
return buyCustomerAddress3;
}
public void setBuyCustomerAddress3(String buyCustomerAddress3) {
this.buyCustomerAddress3 = buyCustomerAddress3;
}
public String getBuyCustomerAddress4() {
return buyCustomerAddress4;
}
public void setBuyCustomerAddress4(String buyCustomerAddress4) {
this.buyCustomerAddress4 = buyCustomerAddress4;
}
public String getBuyCustomerAddress5() {
return buyCustomerAddress5;
}
public void setBuyCustomerAddress5(String buyCustomerAddress5) {
this.buyCustomerAddress5 = buyCustomerAddress5;
}
public String getBuyCustomerPostCode() {
return buyCustomerPostCode;
}
public void setBuyCustomerPostCode(String buyCustomerPostCode) {
this.buyCustomerPostCode = buyCustomerPostCode;
}
public String getBuyCustomerTelNo() {
return buyCustomerTelNo;
}
public void setBuyCustomerTelNo(String buyCustomerTelNo) {
this.buyCustomerTelNo = buyCustomerTelNo;
}
public Integer getBuyCustomerId() {
return buyCustomerId;
}
public void setBuyCustomerId(Integer buyCustomerId) {
this.buyCustomerId = buyCustomerId;
}
public String getBuyCustomerName() {
return buyCustomerName;
}
public void setBuyCustomerName(String buyCustomerName) {
this.buyCustomerName = buyCustomerName;
}
public String getBuyCustomerAlternativeSearchReference() {
return buyCustomerAlternativeSearchReference;
}
public void setBuyCustomerAlternativeSearchReference(
String buyCustomerAlternativeSearchReference) {
this.buyCustomerAlternativeSearchReference = buyCustomerAlternativeSearchReference;
}
public String getTripDriverFirstName() {
return tripDriverFirstName;
}
public void setTripDriverFirstName(String tripDriverFirstName) {
this.tripDriverFirstName = tripDriverFirstName;
}
public String getTripDriverLastName() {
return tripDriverLastName;
}
public void setTripDriverLastName(String tripDriverLastName) {
this.tripDriverLastName = tripDriverLastName;
}
public String getTripDriverEmail() {
return tripDriverEmail;
}
public void setTripDriverEmail(String tripDriverEmail) {
this.tripDriverEmail = tripDriverEmail;
}
public String getTripDriverMobile() {
return tripDriverMobile;
}
public void setTripDriverMobile(String tripDriverMobile) {
this.tripDriverMobile = tripDriverMobile;
}
@Override
public String toString() {
return "PendingReport [balePickupAssignmentId="
+ balePickupAssignmentId + ", driver=" + driver
+ ", supplierId=" + supplierId + ", weekNumber=" + weekNumber
+ ", day=" + day + ", divertDate=" + divertDate
+ ", divertedUserId=" + divertedUserId + ", buyCustomerSiteId="
+ buyCustomerSiteId + ", sellCustomerSiteId="
+ sellCustomerSiteId + ", buyCustomerSiteName="
+ buyCustomerSiteName + ", buyCustomerLocationId="
+ buyCustomerLocationId + ", buyCustomerHouseNumber="
+ buyCustomerHouseNumber + ", buyCustomerAddress1="
+ buyCustomerAddress1 + ", buyCustomerAddress2="
+ buyCustomerAddress2 + ", buyCustomerAddress3="
+ buyCustomerAddress3 + ", buyCustomerAddress4="
+ buyCustomerAddress4 + ", buyCustomerAddress5="
+ buyCustomerAddress5 + ", buyCustomerPostCode="
+ buyCustomerPostCode + ", buyCustomerTelNo="
+ buyCustomerTelNo + ", buyCustomerId=" + buyCustomerId
+ ", buyCustomerName=" + buyCustomerName
+ ", buyCustomerAlternativeSearchReference="
+ buyCustomerAlternativeSearchReference
+ ", tripDriverFirstName=" + tripDriverFirstName
+ ", tripDriverLastName=" + tripDriverLastName
+ ", tripDriverEmail=" + tripDriverEmail
+",diverTripDriverFirstName=" + divertTripDriverFirstName
+",divertTripDriverLastName=" + divertTripDriverLastName
+",divertTripDriverEmail=" + divertTripDriverEmail
+",divertTripDriverMobile=" + divertTripDriverMobile
+ ", tripDriverMobile=" + tripDriverMobile + ", pickupDate="
+ pickupDate + "]";
}
}
<file_sep>/src/main/webapp/resources/js/angular/service/userservice.js
brtaApp.service('userService', function($http, applicationContextURL) {
return {
getLoggedInUserDetails : function() {
return $http.get(applicationContextURL + "/common/getdetails/user")
.then(function(response) {
console.log(JSON.stringify(response));
return response.data;
}, function(errResponse) {
console.error('Error while retrieving user details');
});
},
addUser : function(driverSupplierDTO) {
return $http.post(applicationContextURL + '/userMgmt/add/user',
driverSupplierDTO).then(function(response) {
// console.log('TRF Created successfully'+response);
// console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while adding user");
return $q.reject(errResponse);
});
},
editUser : function(user) {
return $http.post(applicationContextURL + '/userMgmt/edit/user',
user).then(function(response) {
// console.log('TRF Created successfully'+response);
// console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while adding user");
return $q.reject(errResponse);
});
},
getAllUsers : function() {
return $http.get(applicationContextURL + '/userMgmt/get/user/all')
.then(function(response) {
// console.log('TRF Created successfully'+response);
// console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while getting all users");
return $q.reject(errResponse);
});
},
getFilteredUsers : function(user) {
return $http.post(
applicationContextURL + '/userMgmt/get/user/byfilters',
user).then(function(response) {
// console.log('TRF Created successfully'+response);
// console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while getting all users");
return $q.reject(errResponse);
});
},
editUser : function(user) {
return $http.post(applicationContextURL + '/userMgmt/edit/user',
user).then(function(response) {
// console.log('TRF Created successfully'+response);
// console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while adding user");
return $q.reject(errResponse);
});
},
checkUniqueMobileNo : function(mobileNo) {
return $http.post(
applicationContextURL + '/userMgmt/check/mobileNumber',
mobileNo).then(function(response) {
console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while check mobole number");
return $q.reject(errResponse);
});
},
checkUniqueEmail : function(emailId) {
return $http.post(
applicationContextURL + '/userMgmt/check/emailIdUnique',
emailId).then(function(response) {
console.log(response.data);
return response.data;
}, function(errResponse) {
console.error("Error while check emailId unique");
return $q.reject(errResponse);
});
},
getAllUsersForSupplierSite : function(supplierSite) {
return $http.post(applicationContextURL + "/userMgmt/get/user/all",
supplierSite).then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while retrieving users');
});
},
getAllActiveUsersForSupplierSite : function(supplierSite) {
return $http.post(applicationContextURL + "/userMgmt/get/user/active",
supplierSite).then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while retrieving users');
});
},
userUploadFromExcel : function(userList){
console.log("---userList-" + JSON.stringify(userList));
return $http.post(applicationContextURL
+ "/userMgmt/upload/usersFromExcel", userList)
then(function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while adding new driver');
});
}
}
});<file_sep>/src/main/java/com/wm/brta/utility/MailServiceUtility.java
package com.wm.brta.utility;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.wm.brta.domain.User;
public class MailServiceUtility {
static String host = "mail.wm.com";
static String port = "25";
static String to = "<EMAIL>";
static String from = "<EMAIL>";
public static void sendMail(User persistenceObject) {
Properties _properties = new Properties();
_properties.setProperty("mail.smtp.host", host);
_properties.setProperty("mail.smtp.port", port);
Session session = Session.getDefaultInstance(_properties);
try {
MimeMessage _message = new MimeMessage(session);
_message.setFrom(new InternetAddress(from));
_message.addRecipient(Message.RecipientType.TO, new InternetAddress(
persistenceObject.getEmailId().trim()));
_message.addRecipient(Message.RecipientType.CC, new InternetAddress(
"<EMAIL>"));
_message.setSubject("Welcome to Bale Route tracking Application");
_message.setText("Hello,You can download your app by clicking the below link. Your registered phone number is:"+persistenceObject.getMobilePhone());
// Send message
Transport.send(_message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/wm/brta/dao/CustomerSiteDAO.java
package com.wm.brta.dao;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.CustomerSite;
@Repository
public class CustomerSiteDAO {
@Autowired
protected SessionFactory sessionFactory;
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerSiteDAO.class);
public CustomerSite getBuyCustomerSite(String storeName) {
CustomerSite customerSite=null;
Session session = sessionFactory.getCurrentSession();
List<BalePickupMaterialConfiguration> materialMappings = null;
Query query = session
.createQuery("from CustomerSite where alternativeSearchReference = :storeName");
query.setParameter("storeName", storeName);
List<CustomerSite> customerSiteList = query.list();
if(customerSiteList !=null){
customerSite=customerSiteList.get(0);
}
return customerSite;
}
}
<file_sep>/src/main/java/com/wm/brta/dao/ConfigurationDao.java
package com.wm.brta.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wm.brta.domain.BalePickupMaterialConfiguration;
import com.wm.brta.domain.BalePickupSupplierSiteConfiguration;
import com.wm.brta.domain.CustomerSite;
import com.wm.brta.domain.Material;
@Repository
public class ConfigurationDao
{
@Autowired
protected SessionFactory sessionFactory;
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationDao.class);
public int addSupplierSiteConfigData(
BalePickupSupplierSiteConfiguration supplierSiteConfig
) {
Session session = sessionFactory.getCurrentSession();
int id=0;
CustomerSite customerSite = supplierSiteConfig.getCustomerSite();
session.merge(customerSite);
try {
id = (int)session.save(supplierSiteConfig);
} catch (RuntimeException e) {
LOGGER.error("Error:ConfigurationDao:addSupplierSiteConfigData=====>" +e);
} finally {
}
return id;
}
public int addMaterialConfigData(
BalePickupMaterialConfiguration materialConfig
) {
Session session = sessionFactory.getCurrentSession();
int id=0;
try {
id = (int)session.save(materialConfig);
} catch (RuntimeException e) {
LOGGER.error("Error:ConfigurationDao:addMaterialConfigData=====>" +e);
} finally {
}
return id;
}
public void deleteSupplierConfigurationRecordsForCustomerSite(
CustomerSite customerSite) {
Session session = sessionFactory.getCurrentSession();
try{
Query query = session.createQuery("delete from BalePickupSupplierSiteConfiguration where customerSite.customerSiteId"
+ " = :customerSiteId");
query.setParameter("customerSiteId", customerSite.getCustomerSiteId());
query.executeUpdate();
}
catch(Exception e){
LOGGER.error("Error:ConfigurationDao:deleteSupplierConfigurationRecordsForCustomerSite=====>" +e);
}
}
public void deleteMaterialConfigurationRecordsForCustomerSite(
CustomerSite customerSite) {
Session session = sessionFactory.getCurrentSession();
try{
Query query = session.createQuery("delete from BalePickupMaterialConfiguration where customerSite.customerSiteId"
+ " = :customerSiteId");
query.setParameter("customerSiteId", customerSite.getCustomerSiteId());
query.executeUpdate();
}
catch(Exception e){
LOGGER.error("Error:ConfigurationDao:deleteMaterialConfigurationRecordsForCustomerSite=====>" +e);
}
}
public BalePickupMaterialConfiguration getMaterialConfigByCustomerSiteAndMaterial
(CustomerSite buyCustomerSite,Material material){
List<BalePickupMaterialConfiguration> balePickupMaterialConfig = null;
Session session = sessionFactory.getCurrentSession();
try{
Query query = session.createQuery(" from BalePickupMaterialConfiguration where customerSite"
+ " = :customerSite and material = :material");
query.setParameter("customerSite", buyCustomerSite);
query.setParameter("material",material);
balePickupMaterialConfig = query.list();
}
catch(Exception e){
LOGGER.error("Error:ConfigurationDao:getMaterialConfigByCustomerSiteAndMaterial=====>" +e);
}
return balePickupMaterialConfig.get(0);
}
}
|
17d6061451d5ebe74c0b61b605e6db4d97a1343b
|
[
"JavaScript",
"Java",
"Markdown"
] | 35
|
Java
|
rinuthomaz/Bale-Back
|
2ca47385e300a3972b6a73effa7bd6a120fda81a
|
27b30af7bf27bb19b6082239c3256b9f705808d8
|
refs/heads/master
|
<repo_name>o84118317/18_Complete-intro-to-react<file_sep>/js/ClientApp.js
let ce = React.createElement;
let MyTitle = function(props) {
return (
ce('div', null,
ce('h1', {style: {color:props.color}}, props.title)
)
);
};
let MyFirstComponent = function () {
return (
ce('div', null,
ce(MyTitle, {color:'rebeccapurple', title: 'House of Cards'}),
ce(MyTitle, {color:'peru', title: 'Orange od the New Black'}),
ce(MyTitle, {color:'burlywood', title: 'Stranger Things'})
)
);
};
ReactDOM.render(
ce(MyFirstComponent),
document.getElementById('app')
);
|
2a4c3a32d0107c112b7a612df7bca4b157661a17
|
[
"JavaScript"
] | 1
|
JavaScript
|
o84118317/18_Complete-intro-to-react
|
f5ea8e6c61a2bf85a25dea0335dd4a92f1209a7d
|
db484c3b84c3ce788fc3b42f901830dbd26d7764
|
refs/heads/master
|
<repo_name>sameerLinked/react-app<file_sep>/src/pages/Contact.jsx
import React, { Component } from 'react';
import axios from 'axios';
import Footer from '../components/Footer.jsx';
import Navbar from '../components/Navbar.jsx';
import { Link } from 'react-router-dom';
class Contact extends Component {
constructor(props) {
super(props);
this.onChangePersonName = this.onChangePersonName.bind(this);
this.onChangeBusinessName = this.onChangeBusinessName.bind(this);
this.onChangeGstNumber = this.onChangeGstNumber.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.deleteEmployee = this.deleteEmployee.bind(this);
this.state = {
person_name: '',
business_name: '',
business_gst_number:'',
business: [],
isLoaded: false
}
}
componentDidMount(){
fetch('http://localhost:8080/projects/api/select.php')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
business: json
})
})
}
deleteEmployee(e) {
axios.get('http://localhost:8080/projects/api/delete.php?id='+e)
.then(res => console.log(res.data));
//this.props.history.push('/contact');
}
onChangePersonName(e) {
this.setState({
person_name: e.target.value
});
}
onChangeBusinessName(e) {
this.setState({
business_name: e.target.value
})
}
onChangeGstNumber(e) {
this.setState({
business_gst_number: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
const obj = {
person_name: this.state.person_name,
business_name: this.state.business_name,
business_gst_number: this.state.business_gst_number
};
axios.post('http://localhost:8080/projects/api/business_create.php', obj)
.then(res => console.log(res.data));
this.setState({
person_name: '',
business_name: '',
business_gst_number: ''
})
this.props.history.push('/about');
}
render() {
var { isLoaded, business } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
}
return (
<div>
<Navbar />
<h3 align="center">Business List</h3>
<table className="table table-striped" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>Person</th>
<th >Action</th>
</tr>
</thead>
<tbody>
{business.map(item => (
<tr key="{item.id}">
<td>
{item.name}</td>
<td>
<Link to={"/edit/"+item.id} className="btn btn-primary">Edit</Link>
<button onClick={this.deleteEmployee.bind(this,item.id)} className="btn btn-danger">Delete</button>
</td>
</tr>
))}
<tr>
</tr>
</tbody>
</table>
<div className="container">
<h2>Send Message</h2>
<div style={{ marginTop: 10 }}>
<h3>Add New Business</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Person Name: </label>
<input
type="text"
className="form-control"
value={this.state.person_name}
onChange={this.onChangePersonName}
/>
</div>
<div className="form-group">
<label>Business Name: </label>
<input type="text"
className="form-control"
value={this.state.business_name}
onChange={this.onChangeBusinessName}
/>
</div>
<div className="form-group">
<label>GST Number: </label>
<input type="text"
className="form-control"
value={this.state.business_gst_number}
onChange={this.onChangeGstNumber}
/>
</div>
<div className="form-group">
<input type="submit" value="Register Business" className="btn btn-primary"/>
</div>
</form>
</div>
</div>
<Footer />
</div>
);
}
}
export default Contact;
<file_sep>/build/precache-manifest.171f072df1c84831d881be1bd6e7ad19.js
self.__precacheManifest = [
{
"revision": "229c360febb4351a89df",
"url": "/static/js/runtime~main.229c360f.js"
},
{
"revision": "df4972d3d35373bad361",
"url": "/static/js/main.df4972d3.chunk.js"
},
{
"revision": "b14bb2c29034c522e5a5",
"url": "/static/js/1.b14bb2c2.chunk.js"
},
{
"revision": "df4972d3d35373bad361",
"url": "/static/css/main.df151876.chunk.css"
},
{
"revision": "468f31994e9e7a3<PASSWORD>",
"url": "/index.html"
}
];
|
c5f73021bb2a911e40ec36404d0c2a899388314a
|
[
"JavaScript"
] | 2
|
JavaScript
|
sameerLinked/react-app
|
ffbd553612896f0f32acfa3f17fba8cbfb41a14d
|
a65a545c97326bbf2b8892946f0a8f7ae2750cde
|
refs/heads/master
|
<repo_name>benbolzman/Chess<file_sep>/King.js
function King (color, location) {
//A constructor for kings
var self = this;
this.moveCount = 0;
this.type = "King";
this.color = color;
this.location = location;
var blackpieces = [blackpawns[0], blackpawns[1], blackpawns[2], blackpawns[3], blackpawns[4], blackpawns[5], blackpawns[6], blackpawns[7], blackrookL, blackrookR, blackknightL, blackknightR, blackbishopL, blackbishopR, blackqueen];
var whitepieces = [whitepawns[0], whitepawns[1], whitepawns[2], whitepawns[3], whitepawns[4], whitepawns[5], whitepawns[6], whitepawns[7], whiterookL, whiterookR, whiteknightL, whiteknightR, whitebishopL, whitebishopR, whitequeen];
if (color == "black") {
this.otherteam = whitepieces;
} else if (color == "white") {
this.otherteam = blackpieces;
}
this.image = "images/" + color + "King.png";
this.checkMove = (function (desiredlocation) {
var target = isOccupied(desiredlocation);
var opposite = null;
if (target === "empty") {
opposite = false;
} else {
opposite = isOpposing(self, target);
}
var validMove = null;
var currentletteridx = translateLocation(self.location);
var desiredletteridx = translateLocation(desiredlocation);
var currentdigit = self.location[1];
var desireddigit = desiredlocation[1];
var letterdist = desiredletteridx - currentletteridx;
var digitdist = desireddigit - currentdigit;
if (Math.abs(letterdist) <= 1 && Math.abs(digitdist) <= 1) {
if (target == "empty"){
validMove = true;
for (piece of self.otherteam) {
if(piece.checkKing(desiredlocation)) {
validMove = false;
break;
}
}
} else if (target != "empty" && opposite) {
validMove = true;
for (piece of self.otherteam) {
if(piece.checkKing(desiredlocation)) {
validMove = false;
break;
}
}
} else {
validMove = false;
}
} else if (target.type == 'Rook' && target.color == self.color) { //this is for castling.
var distance = desiredletteridx - currentletteridx;
var counter = null;
if (distance > 0) {
counter = 1;
var endLetteridx = 8;
}
if (distance < 0) {
counter = -1;
var endLetteridx = 2;
}
validMove = true;
for (var i = currentletteridx; i != endLetteridx; i += counter) {
if (i == currentletteridx) continue;
var obstacle = isOccupied([letters[i], currentdigit]);
if (obstacle != "empty") {
validMove = false;
break;
}
for (piece of self.otherteam) {
if(piece.checkKing([letters[i], 1])) {
validMove = false;
break;
}
}
}
} else {
validMove = false;
}
return validMove
});
this.checkKing = (function (kingdest) {
return self.checkMove(kingdest);
});
this.isCheckmate = (function () {
var currentletteridx = translateLocation(self.location);
var currentdigit = self.location[1];
var checkmate = true;
if (self.checkMove([currentletteridx, (currentdigit + 1)])
|| self.checkMove([currentletteridx, (currentdigit - 1)])
|| self.checkMove([(currentletteridx + 1), currentdigit])
|| self.checkMove([(currentletteridx - 1), currentdigit])
|| self.checkMove([(currentletteridx + 1), (currentdigit + 1)])
|| self.checkMove([(currentletteridx - 1), (currentdigit - 1)])
|| self.checkMove([(currentletteridx + 1), (currentdigit - 1)])
|| self.checkMove([(currentletteridx - 1), (currentdigit + 1)])) {
checkmate = false;
}
return checkmate;
});
}
<file_sep>/Rook.js
function Rook (color, location) {
//A constructor for the Rook object
var self = this;
this.moveCount = 0;
this.type = "Rook";
this.color = color;
this.location = location;
this.image = "images/" + color + "rook.png";
this.checkMove = (function (desiredlocation) {
var target = isOccupied(desiredlocation);
var opposite = null;
if (target === "empty") {
opposite = false;
} else {
opposite = isOpposing(self, target);
}
var validMove = null;
var currentletteridx = translateLocation(self.location);
var desiredletteridx = translateLocation(desiredlocation);
var currentdigit = self.location[1];
var desireddigit = desiredlocation[1];
//movmetn loop if moving vertically
if (currentletteridx === desiredletteridx) {
var distance = desireddigit - currentdigit;
var counter = null;
if (distance > 0) counter = 1;
if (distance < 0) counter = -1;
for (var i = currentdigit; i != desireddigit; i += counter) {
validMove = true;
if (i == currentdigit) continue;
var obstacle = isOccupied([letters[currentletteridx], i]);
if (obstacle != "empty") {
validMove = false;
break;
}
}
if (validMove && target != "empty" && !opposite) {
validMove = false;
}
//movment loop if moving horizontally
} else if (currentdigit === desireddigit) {
var distance = desiredletteridx - currentletteridx;
var counter = null;
if (distance > 0) counter = 1;
if (distance < 0) counter = -1;
for (var i = currentletteridx; i != desiredletteridx; i += counter) {
validMove = true;
if (i == currentletteridx) continue;
var obstacle = isOccupied([letters[i], currentdigit]);
if (obstacle != "empty") {
validMove = false;
break;
}
}
if (validMove && target != "empty" && !opposite) {
validMove = false;
}
} else {
validMove = false;
}
return validMove;
});
this.checkKing = (function (kingdest) {
return self.checkMove(kingdest);
});
}
|
5fe47c3d333130cbc3826d48497216bb0ba2d9f3
|
[
"JavaScript"
] | 2
|
JavaScript
|
benbolzman/Chess
|
54019f624c040022a443e7b4f82548ac42001229
|
775b7c388c4cae14c84ad9d6346b01dff0e0f90f
|
refs/heads/master
|
<file_sep>from parsers import PMAG_PLUS_handler, Handler, GASTS_handler, GapAdj_handler, MGRA_handler, Procars_handler, infercarspro_handler, Rococo_handler, Anges_handler
ancestor = GASTS_handler.GASTS_handler().parse('/media/hamster/UUI/RealData/fungal_genomes/Fungi')['3']
ancestor2 = Procars_handler.Procars_handler().parse('/media/hamster/UUI/RealData/fungal_genomes/Fungi')
ancestor3 = MGRA_handler.MGRA_handler().parse('/media/hamster/UUI/RealData/fungal_genomes/Fungi')['3']
ancestor4 = Anges_handler.Anges_handler().parse_cars('/media/hamster/UUI/RealData/fungal_genomes/Fungi')
simul = set()
simul2 = set()
simul3 = set()
simul4 = set()
def create_adjacency_set(input_set, genome):
get_left = lambda gene: gene
get_right = lambda gene: -gene
for chromosome in genome:
chr = list(chromosome)
if chromosome.is_circular():
input_set.add((min(get_right(chr[-1]), get_left(chr[0])), max(get_right(chr[-1]), get_left(chr[0]))))
elif not chromosome.is_circular():
input_set.add((min(0, get_left(chr[0])), max(0, get_left(chr[0]))))
input_set.add((min(get_right(chr[-1]), 0), max(get_right(chr[-1]), 0)))
for prev, next in zip(chr, chr[1:]):
input_set.add((min(get_right(prev), get_left(next)), max(get_right(prev), get_left(next))))
create_adjacency_set(simul, ancestor)
create_adjacency_set(simul2, ancestor2)
create_adjacency_set(simul3, ancestor3)
create_adjacency_set(simul4, ancestor4)
only_gasts = 0
only_pro = 0
only_mgra = 0
gasts_mgra = 0
gasts_pro = 0
mgra_pro = 0
common = 0
for i in simul:
if i in simul2:
if i in simul3:
common += 1
else:
gasts_pro += 1
elif i in simul3:
gasts_mgra += 1
else:
only_gasts += 1
for i in simul2:
if i not in simul:
if i in simul3:
mgra_pro += 1
else:
only_pro += 1
for i in simul3:
if i not in simul and i not in simul2:
only_mgra += 1
print(only_gasts, only_pro, only_mgra, gasts_pro, gasts_mgra, mgra_pro, common)<file_sep>#!/usr/bin/python3.4
import os
import os.path
import sys
import logging
import utils.utils as utils
from parsers import Handler, Anges_handler, PMAG_PLUS_handler, GapAdj_handler, MGRA_handler, Procars_handler, infercarspro_handler, Rococo_handler
from parsers.GASTS_handler import GASTS_handler
def prepare_input_files(dir_path, tools):
ancestors_file = os.path.join(dir_path, "ancestral.txt")
genomes_file = os.path.join(dir_path, "blocks.txt")
tree_file = os.path.join(dir_path, "tree.txt")
bad_tree_file = os.path.join(dir_path, "bad_tree.txt")
if not os.path.isfile(genomes_file):
sys.stderr.write("Directory need contain blocks.txt\n")
sys.exit(1)
genomes = Handler.parse_genomes_in_grimm_file(genomes_file)
ancestors = Handler.parse_genomes_in_grimm_file(ancestors_file)
def dojob(name_directory, tools):
for tool in tools:
print('Preparing input files for %s' % tool)
for path, name in utils.get_immediate_subdirectories(name_directory):
for subpath, subname in utils.get_immediate_subdirectories(path):
if tool == 'GASTS':
GASTS_handler().save(subpath)
elif tool == 'MGRA':
MGRA_handler.MGRA_handler().save(subpath)
elif tool == 'GapAdj':
GapAdj_handler.GapAdj_handler().save(subpath)
elif tool == 'PMAG+':
PMAG_PLUS_handler.PMAG_PLUS_handler().save(subpath)
elif tool == 'Procars':
print(subpath)
Procars_handler.Procars_handler().save(subpath)
elif tool == 'InferCarsPro':
infercarspro_handler.Infercarspro_handler().save(subpath)
elif tool == 'Anges':
Anges_handler.Anges_handler().save(subpath)
elif tool == 'Rococo':
Rococo_handler.Rococo_handler().save(subpath)
#prepare_input_files(subpath, tools)
#prepare_ancestor(subpath)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
if (len(sys.argv) < 2):
sys.stderr.write("USAGE: walker.py <destination>\n")
sys.exit(1)
if os.path.isfile(sys.argv[1]):
sys.stderr.write("<destination> - is directory with strong hierarchy\n")
sys.exit(1)
dir_path = os.path.abspath(sys.argv[1])
tools = ['GASTS', 'PMAG+', 'MGRA', 'GapAdj', 'Procars', 'InferCarsPro', 'Anges', 'Rococo']
dojob(dir_path, tools)
<file_sep>import os
import utils.utils as utils
from utils.Genome import Genome, Chromosome
from parsers import Handler
import shutil
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class Infercarspro_handler(Handler.Handler):
def __init__(self):
super(Infercarspro_handler, self).__init__("InferCarsPro")
'''
Blocks file in GRIMM format with given number of chromosomes
in genomes, trees without labels and save tree with labels
for future parsing.
'''
def save(self, dir_path):
infercarspro_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(infercarspro_dir):
os.makedirs(infercarspro_dir)
blocks_txt = os.path.join(infercarspro_dir, self.input_blocks_file)
infer_tree_with_tag = os.path.join(infercarspro_dir, "tree_tag.txt")
infer_tree_txt = os.path.join(infercarspro_dir, "tree.txt")
tree_file_with_tag = os.path.join(dir_path, "tree.txt")
tree_file_without_tag = os.path.join(dir_path, "bad_tree.txt")
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
with open(blocks_txt, 'w') as f:
for genome in genomes:
f.write(">%s %d\n" % (genome.get_name(), genome.get_length()))
for chromosome in genome:
for gene in chromosome:
f.write(str(gene) + " ")
if chromosome.is_circular():
f.write(" @\n")
else:
f.write(" $\n")
shutil.copyfile(tree_file_with_tag, infer_tree_with_tag)
def parse(self, path):
current_path = os.path.join(path, 'InferCarsPro')
files = os.listdir(current_path)
ancestors = filter(lambda x: x.startswith('Ancestor'), files)
genomes = {}
for ancestor in ancestors:
full_path = os.path.join(current_path, ancestor)
genome = Handler.parse_genome_in_infercarspro_file(full_path)
genomes[genome] = genome.get_name()
return genomes
def compare_dist_Infercarspro(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j.get_name():
genomes_list = [genomes[i], j]
distances[i] = BPGscript.BreakpointGraph(). \
DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return distances[max(distances)]
def compare_acc_Infercarspro(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
print(j.get_name())
if i == j.get_name():
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], j)
return accuracies[min(accuracies)]<file_sep>import os
from parsers import Handler
import utils.Genome as Genome
import utils.utils as utils
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class GapAdj_handler(Handler.Handler):
def __init__(self):
super(GapAdj_handler, self).__init__("GapAdj")
def parse(self, path):
genomes = {}
dir_path = os.path.join(path, self.name_tool)
for genome_file, name_file in utils.get_immediate_files(dir_path):
if name_file.find("gap_gen") != -1:
names = os.path.splitext(os.path.splitext(os.path.basename(genome_file))[0])
genome = self._parse_genome(genome_file)
genome.set_name(names[0])
genomes[genome.get_name()] = genome
return genomes
'''
Blocks file in GapAdj format, n - 2 trees, where each internal node labeled by [T] and
save tree with labels for future parsing.
'''
def save(self, dir_path):
gapadj_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(gapadj_dir):
os.makedirs(gapadj_dir)
gapadj_blocks_txt = os.path.join(gapadj_dir, self.input_blocks_file)
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
self._write_genomes(gapadj_blocks_txt, genomes)
with open(os.path.join(dir_path, self.tree_file), 'r') as inp:
tree_str = inp.readline().strip(" \t\n")
with open(os.path.join(dir_path, self.tree_file_with_tag), 'r') as inp:
tree_str_with_tag = inp.readline().strip(" \t\n")
ancestors = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.ancestor_file))
for ancestor in ancestors:
target_name = ancestor.get_name()
ind = tree_str_with_tag.find(target_name)
count = 0
for i in range(ind, 0, -1):
if tree_str_with_tag[i] == ')':
count += 1
target_ind = 0
for i in range(0, len(tree_str)):
if tree_str[i] == ')':
count -= 1
if count == 0:
target_ind = i
break
finally_str = tree_str[0:(target_ind + 1)] + "[T]" + tree_str[(target_ind + 1):]
result_file = os.path.join(gapadj_dir, target_name + '.tree')
with open(result_file, 'w') as out:
out.write("%s\n" % finally_str)
'''
This function parse genomes files in gapadj format.
# - comments
> [number] - name on genome
return genome with Genome type (see Genome class)
'''
def _parse_genome(self, full_name):
genome = Genome.Genome()
with open(full_name, 'r') as f:
chromosome = Genome.Chromosome()
for line in f:
line = line.strip(' \n\t')
if line.find("{") != -1 or len(line) == 0 or line.find("[") != -1 or line.find("]") != -1\
or line.find("}") != -1:
continue
if line.find("name") != -1:
continue
for gene in line.split(' '):
if len(gene) == 0 or gene == "(":
continue
elif gene == ")":
genome.append(chromosome)
chromosome = Genome.Chromosome()
else:
chromosome.append(int(gene))
return genome
def _write_genomes(self, path_to_file, genomes):
with open(path_to_file, 'w') as out:
out.write("{\n")
for genome in genomes:
out.write("name:%s\n[\n" % genome.get_name())
for chromosome in genome:
out.write("( ")
for gene in chromosome:
out.write(str(gene) + " ")
out.write(")\n")
out.write("]\n\n")
out.write("}\n")
def compare_dist_GapAdj(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
genomes_list = [genomes[i], anc_genomes[j]]
distances[i] = BPGscript.BreakpointGraph().DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return min(distances)
def compare_acc_GapAdj(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], anc_genomes[j])
return accuracies
<file_sep>class Chromosome(object):
def __init__(self):
self.is_circ = False
self.blocks = []
self.position = -1
def size(self):
return len(self.blocks)
def set_circular(self, is_circular):
self.is_circ = is_circular
def append(self, block):
self.blocks.append(block)
def is_circular(self):
return self.is_circ
def __iter__(self):
return iter(self.blocks)
class Genome(object):
def __init__(self, name=""):
self.name = name
self.chromosomes = []
self.position = -1
def set_name(self, name):
self.name = name
def append(self, chromosome):
self.chromosomes.append(chromosome)
def add_chromosome(self, is_circular, chromosome):
self.chromosomes.append(Chromosome(is_circular, chromosome))
def get_length(self):
return len(self.chromosomes)
def get_chromosome(self, ind):
return self.chromosomes[ind]
def get_name(self):
return self.name
def __iter__(self):
return iter(self.chromosomes)
<file_sep>/*
* File: adjacency.h
* Author: shine
*
* Created on September 26, 2013, 11:41 AM
*/
#ifndef ADJACENCY_H
#define ADJACENCY_H
#include <utility>
#include <string>
#include <sstream>
#include <fstream>
#include <set>
#include <vector>
#include "genome.h"
using namespace std;
class Adjacency:public pair<string,string> {
public:
vector<int> labels; // "","id" can be negative, representing the strand
string side; // "", "A", "B"
// once created should not be modified
Adjacency(){};
Adjacency(string a, string b){
this->first = a;
this->second = b;
};
Adjacency(string a, string b, string s){
this->first = a;
this->second = b;
this->side=s;
};
bool NotTelomere(){
return this->first!="oo"&&this->second!="oo";
};
bool Contain(string s){
return this->first==s||this->second==s;
};
void Print(ofstream &out) const{
out << this->side << ":(" << this->first << ", ";
for(vector<int>::const_iterator it=this->labels.begin();it!=this->labels.end();it++){
out << *it << ", ";
}
out << this->second << ")";
};
void PrintOnScreen() const{
cerr << this->side << ":(" << this->first << ", ";
for(vector<int>::const_iterator it=this->labels.begin();it!=this->labels.end();it++){
cerr << *it << ", ";
}
cerr << this->second << ")";
};
};
bool operator== (const Adjacency& lhs, const Adjacency& rhs){ // not consider the labels
if (lhs.side !=rhs.side )
return false;
return ( lhs.first==rhs.first && lhs.second==rhs.second )
|| ( lhs.first==rhs.second && lhs.second==rhs.first );
};
bool operator!=(const Adjacency& lhs, const Adjacency& rhs){
return !(lhs==rhs);
}
bool operator < (const Adjacency& lhs, const Adjacency& rhs){
if(lhs.side!=rhs.side)
return lhs.side < rhs.side;
string lS = lhs.first>lhs.second?lhs.second:lhs.first;
string lG = lhs.first>lhs.second?lhs.first:lhs.second;
string rS = rhs.first>rhs.second?rhs.second:rhs.first;
string rG = rhs.first>rhs.second?rhs.first:rhs.second;
if(lS==rS)
return lG < rG;
else
return lS < rS;
};
bool IsSame(Adjacency lhs, Adjacency rhs) {
// Direction of the labels between the extremities should be considered.
if ( lhs.first==rhs.first && lhs.second==rhs.second ) {
return lhs.labels == rhs.labels;
}
else if ( lhs.first==rhs.second && lhs.second==rhs.first ) {
vector <int> rhs_labels_reverse = rhs.labels;
reverse(rhs_labels_reverse.begin(), rhs_labels_reverse.end());
return lhs.labels == rhs_labels_reverse;
}
else
return false;
}
struct AdjComp {
bool operator() (Adjacency lhs, Adjacency rhs) {
if(lhs.side!=rhs.side)
return lhs.side < rhs.side;
string lS = lhs.first>lhs.second?lhs.second:lhs.first;
string lG = lhs.first>lhs.second?lhs.first:lhs.second;
string rS = rhs.first>rhs.second?rhs.second:rhs.first;
string rG = rhs.first>rhs.second?rhs.first:rhs.second;
if(lS==rS)
return lG < rG;
else
return lS < rS;
}
};
//bool Connected(Adjacency a, Adjacency b){
// return
//};
class GenomeAG:public set<Adjacency, AdjComp>{
public:
string side; // Genome "A", "B"
GenomeAG(){};
GenomeAG(Genome g, set<int> marks, string s){
this->side=s;
stringstream convert;
for(Genome::iterator it1=g.begin();it1!=g.end();it1++){ // gene (end_right,end_left).
string end_left="oo", end_right, suffix_left, suffix_right;
Adjacency adj;
vector<int> labels;
for(Chromosome::iterator it2=it1->begin(); it2!=it1->end(); it2++ ){ // start with right end
int gene = *it2, gene_id=abs(gene);
if(gene>=0){ // (right, left) --- (right, left)
suffix_left="H";
suffix_right="T";
}
else{
suffix_left="T";
suffix_right="H";
}
if(marks.count(gene_id)){
labels.push_back(gene);
}
else{
convert << gene_id << suffix_right;
end_right = convert.str();
convert.str(std::string());
adj=Adjacency(end_left,end_right,s);
adj.labels=labels;
this->insert(adj);
labels.clear();
convert << gene_id << suffix_left;
end_left = convert.str();
convert.str(std::string());
}
// cerr << "(" << adj.first << ", ";
// for(vector<int>::iterator it=adj.labels.begin();it!=adj.labels.end();it++){
// cerr << *it << ", ";
// }
// cerr << adj.second << ")\t";
}
end_right="oo";
adj=Adjacency(end_left,end_right,s);
adj.labels=labels;
this->insert(adj);
labels.clear();
}
};
};
#endif /* ADJACENCY_H */
<file_sep>from parsers import PMAG_PLUS_handler, GASTS_handler, GapAdj_handler, MGRA_handler, Procars_handler, infercarspro_handler, Rococo_handler
import csv
import os
def single_tool_data(tool, path):
dist = []
accuracy = []
test = []
for test_dir in os.listdir(path):
if tool == 'PMAG':
dist.append(PMAG_PLUS_handler.PMAG_PLUS_handler().compare_dist_PMAG(path + '/' + test_dir))
accuracy.append(PMAG_PLUS_handler.PMAG_PLUS_handler().compare_acc_PMAG(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'GASTS':
dist.append(GASTS_handler.GASTS_handler().compare_dist_GASTS(path + '/' + test_dir))
accuracy.append(GASTS_handler.GASTS_handler().compare_acc_GASTS(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'GapAdj':
dist.append(GapAdj_handler.GapAdj_handler().compare_dist_GapAdj(path + '/' + test_dir))
accuracy.append(GapAdj_handler.GapAdj_handler().compare_acc_GapAdj(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'MGRA':
dist.append(MGRA_handler.MGRA_handler().compare_dist_MGRA(path + '/' + test_dir))
accuracy.append(MGRA_handler.MGRA_handler().compare_acc_MGRA(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'Procars':
dist.append(Procars_handler.Procars_handler().compare_dist_procars(path + '/' + test_dir))
accuracy.append(Procars_handler.Procars_handler().compare_acc_procars(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'InferCarsPro':
dist.append(infercarspro_handler.Infercarspro_handler().compare_dist_Infercarspro(path + '/' + test_dir))
accuracy.append(infercarspro_handler.Infercarspro_handler().compare_acc_Infercarspro(path + '/' + test_dir))
test.append(test_dir)
elif tool == 'Rococo':
dist.append(Rococo_handler.Rococo_handler().compare_dist_rococo(path + '/' + test_dir))
accuracy.append(Rococo_handler.Rococo_handler().compare_acc_rococo(path + '/' + test_dir))
test.append(test_dir)
mean_dist = sum(dist)/10
TP, FN, FP = [], [], []
print(accuracy)
for i in accuracy:
TP.append(i[0])
FN.append(i[1])
FP.append(i[2])
mean_TP = sum(TP)/10
mean_FN = sum(FN) / 10
mean_FP = sum(FP) / 10
mean_acc = [mean_TP, mean_FN, mean_FP]
return mean_dist, mean_acc
def tool_compare_dist(tool, path):
param_dirs = []
dist = []
for param_dir in os.listdir(path):
try:
dist.append(single_tool_data(tool, path + '/' + param_dir)[0])
param_dirs.append(param_dir)
except:
dist.append('not done')
param_dirs.append(param_dir)
return dist, param_dirs
def tool_compare_acc(tool, path):
param_dirs = []
acc = {}
acc['TP'] = []
acc['FN'] = []
acc['FP'] = []
for param_dir in os.listdir(path):
try:
acc['TP'].append(single_tool_data(tool, path + '/' + param_dir)[1][0])
acc['FN'].append(single_tool_data(tool, path + '/' + param_dir)[1][1])
acc['FP'].append(single_tool_data(tool, path + '/' + param_dir)[1][2])
param_dirs.append(param_dir)
except:
acc['TP'].append('not done')
acc['FN'].append('not done')
acc['FP'].append('not done')
param_dirs.append(param_dir)
return acc, param_dirs
def tools_compare_acc(tools, path):
param_dirs = []
tool_acc = {}
tool_acc['TP'] = {}
tool_acc['FN'] = {}
tool_acc['FP'] = {}
for tool in tools:
tool_acc['TP'][tool] = tool_compare_acc(tool, path)[0]['TP']
tool_acc['FN'][tool] = tool_compare_acc(tool, path)[0]['FN']
tool_acc['FP'][tool] = tool_compare_acc(tool, path)[0]['FP']
param_dirs = tool_compare_dist(tool, path)[1]
return param_dirs, tool_acc
def tools_compare_dist(tools, path):
tool_dist = {}
for tool in tools:
tool_dist[tool] = tool_compare_dist(tool, path)
return tool_dist
def create_acc_table(tools, path, result_path):
accuracies = tools_compare_acc(tools, path)
with open(result_path, 'w') as out:
csv_out = csv.writer(out)
header = [' ']
for i in accuracies[0]:
header.append(i)
csv_out.writerow(header)
for tool in accuracies[1]['TP']:
csv_out.writerow(tool)
row = ['TP']
for i in accuracies[1]['TP'][tool]:
row.append(i)
csv_out.writerow(row)
row = ['FN']
for i in accuracies[1]['FN'][tool]:
row.append(i)
csv_out.writerow(row)
row = ['FP']
for i in accuracies[1]['FP'][tool]:
row.append(i)
csv_out.writerow(row)
def create_dist_table(tools, path, result_path):
distances = tools_compare_dist(tools, path)
with open(result_path, 'w') as out:
csv_out = csv.writer(out)
header = [' ']
for i in distances:
for j in distances[i][1]:
header.append(j)
csv_out.writerow(header)
for tool in distances:
row = [tool]
for i in distances[tool][0]:
row.append(i)
csv_out.writerow(row)
<file_sep>import os
from parsers import Handler
import shutil
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class PMAG_PLUS_handler(Handler.Handler):
def __init__(self):
super(PMAG_PLUS_handler, self).__init__("PMAG")
#self.name_tool = "PMAG"
def parse(self, path):
genomes = {}
path_dir = os.path.join(path, self.name_tool, "result.txt")
temp_genomes = Handler.parse_genomes_in_grimm_file(path_dir)
for genome in temp_genomes:
genomes[genome.get_name()] = genome
return genomes
'''
Blocks file in grimm format, tree with labeled ancestors
'''
def save(self, dir_path):
pmag_plus_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(pmag_plus_dir):
os.makedirs(pmag_plus_dir)
pmag_plus_blocks_txt = os.path.join(pmag_plus_dir, self.input_blocks_file)
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
Handler.write_genomes_with_grimm_in_file(pmag_plus_blocks_txt, genomes)
tree_txt = os.path.join(pmag_plus_dir, "tree.txt")
tree_file_with_tags = os.path.join(dir_path, "tree.txt")
shutil.copyfile(tree_file_with_tags, tree_txt)
#shutil.copyfile(self.tree_file_with_tag, tree_txt)
def compare_dist_PMAG(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
genomes_list = [genomes[i], anc_genomes[j]]
distances[i] = BPGscript.BreakpointGraph().DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return min(distances)
def compare_acc_PMAG(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], anc_genomes[j])
return accuracies
<file_sep>dist <- read.csv('results_project.csv', dec = ',', sep = ';' )
View(dist)
library(ggplot2)
ggplot(dist, aes(x= name, y = time),
las = 2) + geom_bar(stat = 'identity',
fill = 'slateblue') + ylim(0,400) + ggtitle('GASTS') +
xlab('') + ylab('') +
theme(axis.text.x = element_text(angle = 60,
hjust = 1, colour = 'black', face = 'bold'),
plot.title =
element_text(size = 16, face = 'bold'))
<file_sep>import os
from parsers import Handler
import shutil
from ete3 import Tree
import utils.Genome as Genome
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class GASTS_handler(Handler.Handler):
def __init__(self):
Handler.Handler.__init__(self, "GASTS")
#self.name_tool = "GASTS"
self.total_score = 0
self.tree = None
self.all_species = set()
self.true_ancestor_names = {}
self.branch_to_info = {}
def parse(self, dir_path):
self._parse_tree_tag(dir_path)
path = os.path.join(dir_path, self.name_tool)
with open(os.path.join(path, "summary_tree.txt")) as f:
f.readline()
f.readline()
order_branch = list(self._parse_gasts_tree(list(f.readline().split(" "))))
f.readline()
f.readline()
genomes = []
genome = None
chromosome = Genome.Chromosome()
for line in f:
line = line.strip(' \n\t')
if line.find("#") != -1 or len(line) == 0:
continue
if line.find('>') != -1:
if chromosome.size() != 0:
genome.append(chromosome)
if genome is not None:
genomes.append(genome)
chromosome = Genome.Chromosome()
genome = Genome.Genome()
genome.set_name(line[1:])
continue
for gene in line.split(' '):
str_gene = gene.strip(' \n\t')
if str_gene == '$':
chromosome.set_circular(False)
genome.append(chromosome)
chromosome = Genome.Chromosome()
elif str_gene == '@':
chromosome.set_circular(True)
genome.append(chromosome)
chromosome = Genome.Chromosome()
elif len(str_gene) != 0:
chromosome.append(int(str_gene))
if chromosome.size() != 0:
genome.append(chromosome)
genomes.append(genome)
result_genomes = {}
for branch, genome in zip(order_branch, genomes):
genome_name = self.true_ancestor_names.get(branch)
if genome_name is not None:
genome.set_name(genome_name)
result_genomes[genome_name] = genome
return result_genomes
'''
Tree without labels, blocks file in grimm format and save tree with labels for future parsing.
'''
def save(self, dir_path):
gasts_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(gasts_dir):
os.makedirs(gasts_dir)
blocks_txt = os.path.join(gasts_dir, self.input_blocks_file)
gasts_tree_with_tag = os.path.join(gasts_dir, "tree_tag.txt")
gasts_tree_txt = os.path.join(gasts_dir, "tree.txt")
tree_file_with_tag = os.path.join(dir_path, "tree.txt")
tree_file_without_tag = os.path.join(dir_path, "bad_tree.txt")
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
Handler.write_genomes_with_grimm_in_file(blocks_txt, genomes)
shutil.copyfile(tree_file_with_tag, gasts_tree_with_tag)
shutil.copyfile(tree_file_without_tag, gasts_tree_txt)
#shutil.copyfile(self.tree_file_with_tag, gasts_tree_with_tag)
#shutil.copyfile(self.tree_file, gasts_tree_txt)
def _parse_tree_tag(self, dir_path):
self.true_ancestor_names = {}
with open(os.path.join(dir_path, self.name_tool, "tree_tag.txt")) as f:
input_tree = Tree(f.readline().strip("\n\t"), 8)
self.all_species = set(input_tree.get_leaf_names())
for node in list(input_tree.traverse("preorder"))[1:]:
if node.name not in self.all_species:
if not node.is_leaf():
left_split = list(node.children[0].get_leaf_names())
left_split.sort()
right_split = list(node.children[1].get_leaf_names())
right_split.sort()
ancestor_split = list(self.all_species.difference(set(left_split).union(set(right_split))))
ancestor_split.sort()
result = [left_split, right_split, ancestor_split]
result = ["".join(str(result[0])),
"".join(str(result[1])),
"".join(str(result[2]))]
result.sort()
branch = " ".join(result)
self.true_ancestor_names[branch] = node.name
def _parse_gasts_tree(self, dist_tree):
order_branch = []
self.tree, self.total_score = Tree(dist_tree[0], 5), int(dist_tree[1].strip(" \t\n"))
for node in list(self.tree.traverse("preorder"))[1:]:
if not node.is_leaf():
left_split = list(node.children[0].get_leaf_names())
left_split.sort()
right_split = list(node.children[1].get_leaf_names())
right_split.sort()
ancestor_split = list(self.all_species.difference(set(left_split).union(set(right_split))))
ancestor_split.sort()
result = [left_split, right_split, ancestor_split]
result = ["".join(str(result[0])), "".join(str(result[1])), "".join(str(result[2]))]
result.sort()
branch = " ".join(result)
self.branch_to_info[branch] = node.dist
order_branch.append(branch)
else:
order_branch.append(node.name)
return order_branch
def compare_dist_GASTS(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
genomes_list = [genomes[i], anc_genomes[j]]
distances[i] = BPGscript.BreakpointGraph().DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return min(distances)
def compare_acc_GASTS(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], anc_genomes[j])
return accuracies
<file_sep>from boomslang import *
import Configure as conf
def prepare_unique_datasets(tools, results):
name_labels = []
vals = [[[], [], []] for _ in range(len(tools))]
min_y = 101.0
for key, infos in results.items():
_, genes, rear, _ = key
name = "(" + str(5 * genes) + "," + str(rear) + ")"
name_labels.append(name)
for i in range(len(tools)):
TP, FN, FP = infos[i]
vals[i][0].append(TP)
vals[i][1].append(FN)
vals[i][2].append(FP)
if min_y > TP:
min_y = TP
return name_labels, vals, min_y
def draw_clustered_stacked_histigram(filename, name_labels, vals, min_y, name_y, number_tools):
"""
Draw clustered stacked graphic with any tools
"""
hatches = ['/', '-', '\\', '.', ',', '//', '\\\\', '+', 'o']
colors = ['lightgreen', 'steelblue', 'red']
labels = ['True Positive', 'False Negative', 'False Positive']
cluster = ClusteredBars()
for i in range(number_tools):
stack = StackedBars()
for j in range(3):
bar = Bar()
bar.xValues = range(len(vals[i][j]))
bar.yValues = vals[i][j]
bar.hatch = hatches[i]
bar.color = colors[j]
bar.label = labels[j]
stack.add(bar)
cluster.add(stack)
cluster.spacing = 1.5
cluster.xTickLabels = name_labels
cluster.xTickLabelProperties = {
'fontsize': 8,
'horizontalalignment': 'left',
'rotation': 340
}
plot = Plot()
plot.setYFormatter((lambda s, pos: str(int(s)) + "%"))
plot.axesLabelSize = 12
plot.xLabel = "Simulated datasets"
plot.yLabel = name_y
plot.yLimits = (min_y - 3, 100)
plot.add(cluster)
plot.save(filename)
def draw_clustered_histogram(filename, results):
"""
Draw clustered graphic with three tools
"""
labels = ['MGRA2', 'PMAG+', 'GapAdj', 'GASTS']
colors = ['lightgreen', 'steelblue', 'red', 'yellow', 'grey']
my_name_labels = []
for key, _ in results.items():
_, genes, rear, _ = key
name = "(" + str(5 * genes) + "," + str(rear) + ")"
my_name_labels.append(name)
min_y = 10000
max_y = 0
yVals = [[] for _ in range(len(conf.tools))]
for _, infos in results.items():
for i in range(len(conf.tools)):
yVals[i].append(infos[i])
if min_y > min(infos):
min_y = min(infos)
if max_y < max(infos):
max_y = max(infos)
cluster = ClusteredBars()
for i in range(len(conf.tools)):
bar = Bar()
bar.xValues = range(len(yVals[i]))
bar.yValues = yVals[i]
bar.color = colors[i]
bar.label = labels[i]
cluster.add(bar)
cluster.spacing = 1.0
cluster.xTickLabels = my_name_labels
cluster.xTickLabelProperties = {
'fontsize': 8,
'horizontalalignment': 'left',
'rotation': 340
}
plot = Plot()
plot.axesLabelSize = 12
plot.xLabel = "Simulated datasets"
plot.yLabel = "Distance"
plot.yLimits = (min_y - 3, max_y + 3)
plot.add(cluster)
plot.hasLegend()
plot.save(filename)
<file_sep>import os
from parsers import Handler
import shutil
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class Anges_handler(Handler.Handler):
def __init__(self):
super(Anges_handler, self).__init__("Anges")
#self.name_tool = "Anges"
def parse_cars(self, dir_path):
path_dir = os.path.join(dir_path, 'Anges', "TEL_BAB", 'CARS', 'NON_DUP_YEAST_PQRTREE_DOUBLED')
genome = Handler.parse_genome_in_procars_file(path_dir)
return genome
'''
Blocks file in Cars format, needs weightened trees, all combined in PARAMETERS file.
'''
def save(self, dir_path):
anges_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(anges_dir):
os.makedirs(anges_dir)
blocks_txt = os.path.join(anges_dir, self.input_blocks_file)
anges_tree_with_tag = os.path.join(anges_dir, "tree_tag.txt")
anges_tree_txt = os.path.join(anges_dir, "tree.txt")
tree_file_with_tag = os.path.join(dir_path, "tree.txt")
tree_file_without_tag = os.path.join(dir_path, "bad_tree.txt")
shutil.copy(tree_file_without_tag, anges_tree_txt)
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
Handler.write_genomes_with_cars_in_file(blocks_txt, genomes)
param_file = os.path.join(anges_dir, 'PARAMETERS.txt')
with open(param_file, 'w') as f:
n1 = '/n'
lines = ['markers_file ' + blocks_txt + '/n', n1, 'tree_file ' + anges_tree_txt + '/n', n1,
'output_directory ' + anges_dir + '/results/n', n1, 'output_ancestor ANCESTOR/n',
n1, 'markers_doubled 0/n', n1, 'markers_unique 1/n', n1, 'markers_universal 2/n', n1,
'#acs_pairs PAIRS [ACS_SPECIES_PAIRS_FILE_NAME] # name of file containing the species pairs to compare/n',
n1, 'acs_sa 1/n', n1, 'acs_ra 0/n', n1, 'acs_sci 0/n', n1, 'acs_mci 0/n', n1, 'acs_aci 0/n',
n1, '#acs_file ACS [ACS_FILE_NAME] # ACS provided by user/n', n1, 'acs_weight 1/n',
n1, 'c1p_linear 1 # 0 for working with circular chromosomes/n', n1,
'c1p_circular 0 # 1 for working with a unique circular chromosomes/n', n1,
'c1p_telomeres 2 # 0: no telomere, 1: added after optimization (greedy heuristic), '
'2: added after optimization (bab), 3: added during optimization (bab)/n', n1,
'c1p_heuristic 0 # Using a greedy heuristic/n', n1, 'c1p_bab 0 # Using a branch-and-bound/n', n1,
'c1p_spectral 0 # Using spectral seriation/n', n1,
'c1p_spectral_alpha 1.0 # Spectral seriation alpha value']
f.writelines(lines)
# f.write('markers_file ' + blocks_txt + '/n')
# f.write('tree_file ' + anges_tree_txt + '/n')
# f.write('output_directory' + anges_dir + '/results/n')
# f.write('output_ancestor ANCESTOR/n')
# f.write('markers_doubled 0/n')
# f.write('markers_unique 1/n')
# f.write('markers_universal 2/n')
# f.write('#acs_pairs PAIRS [ACS_SPECIES_PAIRS_FILE_NAME] # name of file containing the species pairs to compare/n')
# f.write('acs_sa 1/n')
# f.write('acs_ra 0/n')
# f.write('acs_sci 0/n')
# f.write('acs_mci 0/n')
# f.write('acs_aci 0/n')
# f.write('#acs_file ACS [ACS_FILE_NAME] # ACS provided by user/n')
# f.write('acs_weight 1/n')
# f.write('#acs_correction [0/1/2] # Correcting for missing markers: 0 = none, 1 = adding markers spanned by intervals, 2 = X/n')
# f.write('c1p_linear 1 # 0 for working with circular chromosomes/n')
# f.write('c1p_circular 0 # 1 for working with a unique circular chromosomes/n')
# f.write('c1p_telomeres 2 # 0: no telomere, 1: added after optimization (greedy heuristic), '
# '2: added after optimization (bab), 3: added during optimization (bab)/n')
# f.write('c1p_heuristic 0 # Using a greedy heuristic/n')
# f.write('c1p_bab 0 # Using a branch-and-bound/n')
# f.write('c1p_spectral 0 # Using spectral seriation/n')
# f.write('c1p_spectral_alpha 1.0 # Spectral seriation alpha value')
<file_sep>install.packages('VennDiagram')
require(VennDiagram)
# Adopted from Chen and Boutros, 2011 (DOI: 10.1186/1471-2105-12-35)
# If you want to compare three tools
venn.diagram(
x = list(
GASTS = c(1:9, 10:12, 13:705, 707:719),
Procars = c(720:755, 10:12, 13:705, 756:759),
MGRA = c(760:766, 707:719, 13:705, 756:759)
),
filename = "Common.jpg",
col = "transparent",
fill = c("red", "blue", "green"),
alpha = 0.5,
main = 'Common', main.cex = 4,
label.col = c("darkred", "white", "darkblue", "white", "white", "white", "darkgreen"),
cex = 2.5,
fontfamily = "serif",
fontface = "bold",
cat.default.pos = "text",
cat.col = c("darkred", "darkblue", "darkgreen"),
cat.cex = 2.5,
cat.fontfamily = "serif",
cat.dist = c(0.06, 0.06, 0.03),
cat.pos = 0
);
#If you want to compare 4 tools
venn.diagram(
x = list(
I = c(1:60, 61:105, 106:140, 141:160, 166:175, 176:180, 181:205, 206:220),
IV = c(531:605, 476:530, 336:375, 376:405, 181:205, 206:220, 166:175, 176:180),
II = c(61:105, 106:140, 181:205, 206:220, 221:285, 286:335, 336:375, 376:405),
III = c(406:475, 286:335, 106:140, 141:160, 166:175, 181:205, 336:375, 476:530)
),
filename = "quadruple_Venn.tiff",
col = "black",
lty = "dotted",
lwd = 4,
fill = c("cornflowerblue", "green", "yellow", "darkorchid1"),
alpha = 0.50,
label.col = c("orange", "white", "darkorchid4", "white", "white", "white", "white", "white", "darkblue", "white", "white", "white", "white", "darkgreen", "white"),
cex = 2.5,
fontfamily = "serif",
fontface = "bold",
cat.col = c("darkblue", "darkgreen", "orange", "darkorchid4"),
cat.cex = 2.5,
cat.fontfamily = "serif"
);
<file_sep>import os
from parsers import Handler
import utils.Genome as Genome
import utils.utils as utils
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
import shutil
class Rococo_handler(Handler.Handler):
def __init__(self):
super(Rococo_handler, self).__init__("Rococo")
'''
Blocks file in Rococo format,
tree with labels used.
'''
def save(self, dir_path):
rococo_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(rococo_dir):
os.makedirs(rococo_dir)
rococo_blocks_txt = os.path.join(rococo_dir, self.input_blocks_file)
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
self._write_genomes(rococo_blocks_txt, genomes)
infer_tree_with_tag = os.path.join(rococo_dir, "tree_tag.txt")
tree_file_with_tag = os.path.join(dir_path, "tree.txt")
shutil.copyfile(tree_file_with_tag, infer_tree_with_tag)
def parse(self, path):
path_dir = os.path.join(path, 'Rococo', "result")
genomes = Handler.parse_genomes_in_rococo_file(path_dir)
return genomes
def _write_genomes(self, path_to_file, genomes):
with open(path_to_file, 'w') as out:
for genome in genomes:
out.write("%s\n" % genome.get_name())
for chromosome in genome:
for gene in chromosome:
if gene >= 0:
out.write(str(gene) + "\t" + '+\n')
elif gene < 0:
out.write(str(abs(gene)) + '\t' + '-\n')
if not chromosome.is_circular:
out.write(")\n")
else:
out.write('|\n')
out.write("\n")
def compare_dist_rococo(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j.get_name():
genomes_list = [genomes[i], j]
distances[i] = BPGscript.BreakpointGraph(). \
DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return distances[max(distances)]
def compare_acc_rococo(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
print(j.get_name())
if i == j.get_name():
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], j)
return accuracies[min(accuracies)]
<file_sep>/*
* File: genome.h
* Author: shine
*
* Created on October 14, 2013, 7:34 AM
*/
#ifndef GENOME_H
#define GENOME_H
#include<list>
#include<set>
using namespace std;
class Chromosome:public list<int>{
public:
int chrID; // for compare
bool circular; //linear
set<int> genes; //obtain sets of G A B, cal # of shared genes
//no duplication
};
class Genome:public list<Chromosome>{
public:
// string genomeID;
set<int> genes; //obtain sets of G A B, cal # of shared genes
// for stat: # of shared genes
};
#endif /* GENOME_H */
<file_sep>/*
* File: graph.h
* Author: shine
*
* Created on October 14, 2013, 8:02 AM
*/
#ifndef GRAPH_H
#define GRAPH_H
#include<string>
#include "adjacency.h"
using namespace std;
class Component:public list<Adjacency>{
public:
int id;//?
string type; //"", "cycle", "AA", "AB", "BA", "BB".
};
class Graph:public list<Component>{
public:
int stat();// # cycles + 1/2 # of "AB" path
};
class ReducedComponent:public list<string>{ //must be path, list of types of runs "A" "B" "A"; cycle start with A-run;
public:
string type_path; //"", "cycle", "AA", "AB", "BB".
string type_run; // AA, BB paths: "", "A", "B", "AB"
// AB path: "", "A", "B". "AB", "BA"
// cycle: no type;
};
class ReducedGraph:public list<ReducedComponent>{
public:
int stat();// landa = [(#run + 1 )/2 ]; sum up of weighted pairs of ReducedComponents.
};
#endif /* GRAPH_H */
<file_sep>import networkx as nx
from Handler import parse_genomes_in_grimm_file
import matplotlib.pyplot as plt
class BreakpointGraph:
def __init__(self):
self.BPG = nx.MultiGraph()
def create_BPG(self, genomes):
color = 0
for genome in genomes:
color += 1
count = 0
for i in genomes[genome]:
self.BPG.add_edge(i[0], i[1], color=color, order=count)
count += 1
return self.BPG
def add_edge(self, vertex1, vertex2, color, order):
self.BPG.add_edge(vertex1, vertex2, color=color, order=order)
def delete_edge(self, vertex1, vertex2):
try:
self.BPG.remove_edge(vertex1, vertex2)
except:
raise IndexError('no such edge')
def path_finder(self, i):
# path_finder[0] gives the number of pathes
# path_finder[1] gives the number of cycles
pathes = 0
cycles = 0
flag = True
for j in nx.connected_components(i):
for vertex in j:
if nx.degree(i, vertex) == 1:
flag = False
if flag:
cycles += 1
else:
pathes += 1
flag = True
return pathes, cycles
def DCJ_distance(self, i):
n = len(i.edges())
cycles = self.path_finder(i)[1]
pathes = self.path_finder(i)[0]
return float(n - cycles - pathes/2)
def draw_BPG(self, first_seq, second_seq, save=False):
# option save = True will save our graph as an image
pos = nx.spring_layout(self.BPG)
nx.draw_networkx_nodes(self.BPG, pos, cmap=plt.get_cmap('jet'),
node_color='black', node_size=50, alpha=0.8)
nx.draw_networkx_edges(self.BPG, pos, edgelist=first_seq, width=2,
alpha=0.5, edge_color='r', edge_vmax=100)
nx.draw_networkx_edges(self.BPG, pos, edgelist=second_seq, width=2,
alpha=0.5, edge_color='b', style='dashed')
if save:
plt.savefig("breakpoint_graph.png")
return plt.show()
def BPG_from_genomes(self, grimm_genomes_list):
genomes_dict = {}
genome_number = 0
for genome in grimm_genomes_list:
genome_number += 1
for el in genome:
genomes_dict[genome_number] = []
chromosome = list(el)
for i in range(len(chromosome)-1):
gene = ['h' + str(abs(chromosome[i])),
't' + str(abs(chromosome[i]))]
next_gene = ['h' + str(abs(chromosome[i+1])),
't' + str(abs(chromosome[i+1]))]
if chromosome[i] > 0 and chromosome[i+1] > 0:
genomes_dict[genome_number].append([gene[1],
next_gene[0]])
elif chromosome[i] > 0 and chromosome[i+1] < 0:
genomes_dict[genome_number].append([gene[1],
next_gene[1]])
elif chromosome[i] < 0 and chromosome[i+1] > 0:
genomes_dict[genome_number].append([gene[0],
next_gene[0]])
else:
genomes_dict[genome_number].append([gene[0],
next_gene[1]])
if el.is_circular():
first_gene = ['h' + str(abs(chromosome[0])),
't' + str(abs(chromosome[0]))]
last_gene = ['h' + str(abs(chromosome[-1])),
't' + str(abs(chromosome[-1]))]
if chromosome[0] > 0 and chromosome[-1] > 0:
genomes_dict[genome_number].append([first_gene[0],
last_gene[1]])
elif chromosome[0] > 0 and chromosome[-1] < 0:
genomes_dict[genome_number].append([first_gene[0],
last_gene[0]])
else:
genomes_dict[genome_number].append([first_gene[1],
last_gene[0]])
return self.create_BPG(genomes_dict)
<file_sep>import os
import sys
from parsers import MGRA_handler, GapAdj_handler, GASTS_handler, PMAG_PLUS_handler
LIB_DIR = "lib"
ragout_root = os.path.dirname(os.path.realpath(__file__))
lib_absolute = os.path.join(ragout_root, LIB_DIR)
sys.path.extend([ragout_root, lib_absolute])
os.environ["PATH"] += os.pathsep + lib_absolute
tools = [
MGRA_handler.MGRA_handler(),
PMAG_PLUS_handler.PMAG_PLUS_handler(),
GapAdj_handler.GapAdj_handler(),
GASTS_handler.GASTS_handler()
]
def filter_genomes_by_species(target, params):
species, genome, rear, indel_ratio = params
if species == target:
return True
else:
return False
<file_sep>#!/bin/bash
cd ..
HOME_DIR=$PWD
#SCRIPT_DIR=${HOME_DIR}/script
DATA_DIR=${HOME_DIR}/CLASSIC
MGRA_TOOL=${HOME_DIR}/tools/MGRA/build/mgra
PMAG_DIR=${HOME_DIR}/tools/PMAG/
GapAdj_TOOL=${HOME_DIR}/tools/GapAdj/GapAdj
GASTS_TOOL=${HOME_DIR}/tools/GASTS/gasts.jar
## Run MGRA on each dataset and save results in current directory
function run_MGRA {
echo "START TESTING DATASET"
for param_folder in ${DATA_DIR}/*
do
param_folder_name=${param_folder##*/}
echo MGRA start to work with dataset ${param_folder_name}
for folder in ${param_folder}/*
do
folder_name=${folder##*/}
echo Work with ${folder_name}
${MGRA_TOOL} -c ${folder}/MGRA/sim.cfg -f grimm -g ${folder}/MGRA/blocks.txt -o ${folder}/MGRA/ 2>logerror.txt >/dev/null
done
done
echo "END TESTING DATASET"
}
## Run PMAG+ on each dataset and save results in current directory
function run_PMAG {
echo "START TESTING DATASET"
for param_folder in ${DATA_DIR}/*
do
param_folder_name=${param_folder##*/}
echo PMAG start to work with dataset ${param_folder_name}
for folder in ${param_folder}/*
do
folder_name=${folder##*/}
echo Work with ${folder_name}
cd ${PMAG_DIR}
cp ${folder}/PMAG/blocks.txt ${PMAG_DIR}/blocks.txt
cp ${folder}/PMAG/tree.txt ${PMAG_DIR}/tree.txt
perl RunPMAG+.pl blocks.txt tree.txt result.txt
mv result.txt ${folder}/PMAG/result.txt
rm tree.txt
rm blocks.txt
done
done
echo "END TESTING DATASET"
}
## Run GapAdj on each dataset and save results in current directory
function run_GapAdj {
echo "START TESTING DATASET"
for param_folder in ${DATA_DIR}/*
do
param_folder_name=${param_folder##*/}
echo GapAdj start to work with dataset ${param_folder_name}
for folder in ${param_folder}/*
do
folder_name=${folder##*/}
echo Work with ${folder_name}
for current_tree_file in ${folder}/GapAdj/*.tree
do
current_tree=${current_tree_file##*/}
tree_name=${current_tree%.*}
name_gen=${tree_name}.gap_gen
echo "Work with ${current_tree} and run on ${name_gen}"
${GapAdj_TOOL} ${folder}/GapAdj/${current_tree} ${folder}/GapAdj/blocks.txt ${folder}/GapAdj/${name_gen} 25 0.6 2>logerror.txt >/dev/null
done
done
done
echo "END TESTING DATASET"
}
## Run GASTS on each dataset and save results in current directory
function run_GASTS {
echo "START TESTING DATASET"
for param_folder in ${DATA_DIR}/*
do
param_folder_name=${param_folder##*/}
echo "GASTS start to work with dataset ${param_folder_name}"
for folder in ${param_folder}/*
do
folder_name=${folder##*/}
echo "Work with ${folder_name}"
cp -r ${GASTS_TOOL} ${folder}/GASTS/gasts.jar
java -jar ${folder}/GASTS/gasts.jar ${folder}/GASTS/tree.txt ${folder}/GASTS/blocks.txt 2>logerror.txt
rm ${folder}/GASTS/gasts.jar
done
done
echo "END TESTING DATASET"
}
###################
## MAIN FUNCTION ##
###################
if [ "$#" -ne 1 ]; then
echo "./tester.sh {1,2,3,4} where
1 - run MGRA
2 - run PMAG+
3 - run GapAdj
4 - run GASTS
5 - run InferCarsPro (future)
6 - run DupCars (future)
7 - run SCJ (future)"
exit
fi
if [ ! -d ${DATA_DIR} ]; then
echo "ERROR with ${DATA_DIR}"
exit
fi
if [ $1 -eq 1 ]; then
echo "Run MGRA"
run_MGRA
elif [ $1 -eq 2 ]; then
echo "Run PMAG"
run_PMAG
elif [ $1 -eq 3 ]; then
echo "Run GapAdj"
run_GapAdj
elif [ $1 -eq 4 ]; then
echo "Run GASTS"
run_GASTS
elif [ $1 -eq 5 ]; then
echo "Run InferCarsPro (future)"
elif [ $1 -eq 6 ]; then
echo "Run DupCars (future)"
elif [ $1 -eq 7 ]; then
echo "Run SCJ (future)"
fi
###################
## END ##
###################
<file_sep>__author__ = 'nikita_kartashov'
from Queue import Queue
class UnrootedBinaryTree(object):
def __init__(self, artificial_root_node):
# Vertices are stored as a list of lists, so if node x is connected to y
# y in vertices[x] = x in vertices[y] = True
self.__vertices = []
# ith element is true if ith vertex is a leaf
self.__leaves = {}
self.__process_artificial_root(artificial_root_node)
self.__leaf_distances = self.__calculate_pairwise_leaf_distances()
def __calculate_pairwise_leaf_distances(self):
distances = [[0 for _ in self.__vertices] for _ in self.__vertices]
for start_leaf in self.__leaves.iterkeys():
for end_leaf in self.__leaves.iterkeys():
self.calculate_distance_between_two(distances, start_leaf, end_leaf)
leaf_distances = {}
for left_leaf, left_genome in self.__leaves.iteritems():
leaf_distances[left_genome] = {}
for right_leaf, right_genome in self.__leaves.iteritems():
leaf_distances[left_genome][right_genome] = distances[left_leaf][right_leaf]
return leaf_distances
def pretty_branches(self, branches):
complete_label = set(self.leaf_labels())
return ['{0} + {1}'.format(', '.join(branch),
', '.join(complete_label.difference(branch))) for branch in branches]
def branches_when_rooted_at(self, root_label):
root_node, _ = filter(lambda (node, label): label == root_label, self.__leaves.iteritems())[0]
labels = [None for _ in self.__vertices]
_, tree_labels = self.__label_nodes(root_node, labels)
return {frozenset(element for element in s) for s in tree_labels}
def compare_branches(self, other_tree, rooted_at=None):
if rooted_at is None:
k, v = next(self.__leaves.iteritems())
rooted_at = v
first_branch_set = self.branches_when_rooted_at(rooted_at)
second_branch_set = other_tree.branches_when_rooted_at(rooted_at)
return first_branch_set.symmetric_difference(second_branch_set)
def compare_distances(self, other_tree):
assert (set(self.leaf_labels()) == set(other_tree.leaf_labels()))
distance_difference = 0
for label in self.leaf_labels():
for other_label in self.leaf_labels():
distance_difference += \
abs(self.leaf_distances()[label][other_label] - other_tree.leaf_distances()[label][other_label])
return distance_difference * 1.0 / len(self.leaf_labels())
def __label_nodes(self, current_node, labels, visited=None):
if visited is None:
visited = [False for _ in self.__vertices]
visited[current_node] = True
current_node_labels = set() if len(self.__vertices[current_node]) != 1 else {self.__leaves[current_node]}
current_tree_labels = [current_node_labels]
nodes_to_visit = filter(lambda n: not visited[n], self.__vertices[current_node])
for node in nodes_to_visit:
new_node_labels, new_tree_labels = self.__label_nodes(node, labels, visited)
current_node_labels.update(new_node_labels)
current_tree_labels.extend(new_tree_labels)
labels[current_node] = current_node_labels
return current_node_labels, current_tree_labels
def leaf_distances(self):
return self.__leaf_distances
def leaves(self):
return self.__leaves.keys()
def leaf_labels(self):
return self.__leaves.values()
def calculate_distance_between_two(self, distances, start, end, current=None, distance_so_far=0, visited=None):
if current is None:
current = start
if visited is None:
visited = [False for _ in self.__vertices]
if current == end:
distances[start][end] = distance_so_far
distances[end][start] = distance_so_far
visited[current] = True
for node in filter(lambda n: not visited[n], self.__vertices[current]):
self.calculate_distance_between_two(distances, start, end, node, distance_so_far + 1, visited)
def __process_artificial_root(self, artificial_root_node):
nodes_to_process = Queue()
for node in artificial_root_node.child_nodes():
nodes_to_process.put((node, None))
while not nodes_to_process.empty():
node, parent = nodes_to_process.get()
self.__vertices.append([])
current_node = len(self.__vertices) - 1
for child in node.child_nodes():
nodes_to_process.put((child, current_node))
if not node.child_nodes():
self.__leaves[current_node] = node.taxon.__str__()
if parent is not None:
self.__vertices[parent].append(current_node)
self.__vertices[current_node].append(parent)
self.__vertices[0].append(1)
self.__vertices[1].append(0)<file_sep>import os
from parsers import Handler
import utils.utils as utils
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class MGRA_handler(Handler.Handler):
def __init__(self):
super(MGRA_handler, self).__init__("MGRA")
#self.name_tool = "MGRA"
def parse(self, dir_path):
self.path_to_genomes_dir = os.path.join(dir_path, self.name_tool, "genomes")
genomes = {}
for genome_file, _ in utils.get_immediate_files(self.path_to_genomes_dir):
genome = Handler.parse_genome_in_grimm_file(genome_file)
genome.set_name(os.path.splitext(os.path.basename(genome_file))[0])
genomes[genome.get_name()] = genome
return genomes
'''
Blocks file in grimm format, configure file
'''
def save(self, dir_path):
mgra_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(mgra_dir):
os.makedirs(mgra_dir)
blocks_txt = os.path.join(dir_path, 'blocks.txt')
genomes = Handler.parse_genomes_in_grimm_file(blocks_txt)
#genomes = Handler.parse_genomes_in_grimm_file(self.input_blocks_file)
mgra_blocks_txt = os.path.join(mgra_dir, "blocks.txt")
Handler.write_genomes_with_grimm_in_file(mgra_blocks_txt, genomes)
tree_file_with_tag_cool = os.path.join(dir_path, "tree.txt")
with open(tree_file_with_tag_cool, 'r') as inp:
tree_str = inp.readline().strip(" \t\n")
# with open(self.tree_file_with_tag, 'r') as inp:
# tree_str = inp.readline().strip(" \t\n")
config_txt = os.path.join(mgra_dir, "sim.cfg")
with open(config_txt, 'w') as out:
out.write("[Genomes]\n")
for genome in genomes:
out.write("%s\n" % genome.get_name())
out.write("\n[Trees]\n")
out.write("%s\n\n" % tree_str)
out.write("[Algorithm]\n")
out.write("stages 4\n")
out.write("rounds 3\n")
out.write("bruteforce 12\n\n")
out.write("[Completion]\n")
def parse_history_stats_file(self):
pass
def compare_dist_MGRA(self, dir_path):
distances = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
genomes_list = [genomes[i], anc_genomes[j]]
distances[i] = BPGscript.BreakpointGraph().DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return min(distances)
def compare_acc_MGRA(self, dir_path):
accuracies = {}
genomes = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for i in genomes:
for j in anc_genomes:
if i == j:
accuracies[i] = Measures.calculate_accuracy_measure(genomes[i], anc_genomes[j])
return accuracies
<file_sep>/*
* File: io.h
* Author: shine
*
* Created on September 26, 2013, 1:13 PM
*/
#ifndef IO_H
#define IO_H
#include <stdlib.h>
#include <iostream>
#include <istream>
#include <fstream>
#include <sstream>
#include <set>
#include <list>
#include <string>
#include "genome.h"
using namespace std;
class IO{
public:
// set<Adjacency,AdjComp> ImportAdjacencies(const char * address);
Genome ImportGenome(const char * address);
};
Genome IO::ImportGenome(const char* address){
string word, line;
int id;
ifstream input;
Genome g;
input.open(address);
if(input.is_open()){
// cerr << "Open: " << address << endl;
while (input.good()) {
// abandon non chromosome lines;
if((char)input.peek()=='\n' || (char)input.peek()=='>' || (char)input.peek()=='#' || input.peek()==-1){
line ="";
getline(input,line);
// cerr << "Non chr line: " << line << endl;
continue;
}
// readin the chromosome;
Chromosome chr;
getline(input,line);
// cerr << "Chr: " << endl;
stringstream read(line);
while(read.good()){
read >> word;
if(word == "$" ){
chr.circular=false;
}
else if(word == "@" || word == ";"){
chr.circular=true;
}
else if(word == "#"){ // comments symbol
break;
}
else {
stringstream convert(word);
if (convert >> id) {
chr.push_back(id);
chr.genes.insert(abs(id) );
}
else {
cerr << "Error: ImportGenomes, cannot convert string to int, " << word << endl;
}
}
}
g.push_back(chr);
g.genes.insert(chr.genes.begin(),chr.genes.end());
// print the chromosome;
// if(chr.circular){
// cerr << "Circular chr: ";
// }
// else{
// cerr << "Linear chr: ";
// }
// for(Chromosome::iterator it=chr.begin();it!=chr.end();it++){
// cerr << *it << " \t";
// }
// cerr <<endl;
}
}
else {
cerr << "Fail to open: " << address << endl;
}
return g;
}
//set<Adjacency,AdjComp> IO::ImportAdjacencies(const char * address){
// set<Adjacency,AdjComp> AS;
// ifstream input;
// string word, prev_word, cur_word, next_word;
// int id;
// list<string> gene_list;
// bool flag=false;
//
// input.open(address);
// if(input.is_open()){
// cerr << "open: " << address << endl;
// while (input >> word) {
// if(word == "("){
// gene_list.push_back("oo");
// flag = true;
// }
// else if(word == ")"){
// gene_list.push_back("oo");
// flag = false;
// bool flag_start = false;
// for(list<string>::iterator it=gene_list.begin();it!=gene_list.end();it++){
// string gene = *it;
// if(!flag_start && gene=="oo"){//start:
// prev_word = "oo";
// cur_word = "";
// next_word = "";
// flag_start = true;
// continue;
// }
// else if(flag_start && gene=="oo") {//end:
// cur_word = "oo";
// next_word = "";
// flag_start = false;
// }
// else if(flag_start && gene != "oo"){
// stringstream convert(gene);
// if (convert >> id) {
// if (id >= 0) {
// cur_word = gene;
// cur_word.append("T");
// next_word = gene;
// next_word.append("H");
// } else { // id < 0
// gene.erase(gene.begin());
// cur_word = gene;
// cur_word.append("H");
// next_word = gene;
// next_word.append("T");
// }
// }
// else
// cerr << "Unexpected name that is not gene between delimeter ( ). Location: " << address << ", " << gene << endl;
// }
// else // not within a chr; not infinite point ; should not be a gene id
// continue;
//
// //cout << prev_word << " --- " << cur_word << ";\t";
// AS.insert(Adjacency(prev_word,cur_word));
// prev_word = next_word;
// }
// cout << endl;
// gene_list.clear();
// }
// else{
// if(flag){
// gene_list.push_back(word);
// }
// }
// }
// }
// else{
// cerr << "cannot open file: " << address << endl;
// }
// input.close();
// return AS;
//}
#endif /* IO_H */
<file_sep>/*
* File: stat_branch.cpp
* Author: shine
*
* Created on April 5, 2014, 1:22 PM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <math.h>
#include <map>
#include <stack>
#include "genome.h"
#include "adjacency.h"
#include "io.h"
#include "graph.h"
using namespace std;
std::pair<int, int> Distance(Genome g1, Genome g2) {
ofstream dist_log("/dev/null");
// shared genes and marks, let the simulated genome be genome A and reconstructed genome be genome B
Genome a = g1, b = g2;
set<int> shared_genes, marks_a, marks_b;
set_intersection(g1.genes.begin(), g1.genes.end(), g2.genes.begin(), g2.genes.end(), insert_iterator <set<int> >(shared_genes, shared_genes.begin()));
set_difference(g1.genes.begin(), g1.genes.end(), g2.genes.begin(), g2.genes.end(), insert_iterator <set<int> >(marks_a, marks_a.begin()));
set_difference(g2.genes.begin(), g2.genes.end(), g1.genes.begin(), g1.genes.end(), insert_iterator <set<int> >(marks_b, marks_b.begin()));
int num_shared_genes = shared_genes.size();
// dist_log << "G1 size: " << g1.genes.size() << ", G2 size: " << g2.genes.size() << endl;
// dist_log << marks_a.size() << " marks in G1: " << endl;
// for(set<int>::iterator it=marks_a.begin(); it!=marks_a.end(); it++) {
// dist_log << *it << "\t";
// }
// dist_log << endl << marks_b.size() << " marks in G2: " << endl;
// for(set<int>::iterator it=marks_b.begin(); it!=marks_b.end(); it++) {
// dist_log << *it << "\t";
// }
// dist_log << endl;
// adjacency graph: adjacency -> connected components -> cycle/path -> shrinked cycle/path according to marks -> type
GenomeAG a_ag(a, marks_a, "A");
GenomeAG b_ag(b, marks_b, "B");
// dist_log << "G1 adj graph: " << endl;
// for(GenomeAG::iterator it1=a_ag.begin();it1!=a_ag.end();it1++){
// (*it1).Print(dist_log); dist_log << "\t";
// }
// dist_log << endl << "G2 adj graph: " << endl;
// for(GenomeAG::iterator it1=b_ag.begin();it1!=b_ag.end();it1++){
// (*it1).Print(dist_log); dist_log << "\t";
// }
// dist_log << endl;
//construct partial equivalence relation using multimap
multimap<Adjacency, Adjacency, AdjComp> connections;
for (GenomeAG::iterator itA = a_ag.begin(); itA != a_ag.end(); itA++) {
for (GenomeAG::iterator itB = b_ag.begin(); itB != b_ag.end(); itB++) {
if ((itA->first == itB->first && itA->first != "oo") ||
(itA->first == itB->second && itA->first != "oo") ||
(itA->second == itB->first && itA->second != "oo") ||
(itA->second == itB->second && itA->second != "oo")) {
connections.insert(pair<Adjacency, Adjacency>(*itA, *itB));
connections.insert(pair<Adjacency, Adjacency>(*itB, *itA));
}
}
}
// dist_log << "Adjacency equivalence relation btw G1 and G2 adj graph: " << endl;
// for(multimap<Adjacency,Adjacency,AdjComp>::iterator it=connections.begin();it!=connections.end();it++){
// it->first.Print(dist_log);
// dist_log << "\t -> ";
// it->second.Print(dist_log);
// dist_log << endl;
// }
// Construct the ag graph
// dist_log << "Components: " << endl;
Graph ag_graph;
while (connections.size() > 0) {
Component c; // list of the adjacencies;
set<Adjacency, AdjComp> elements; // set of adjacencies in the component C -> exclude duplicated adjacency and later removal
// 1st adjacency
Adjacency a = (*connections.begin()).first;
c.push_back(a);
elements.insert(a);
pair <multimap<Adjacency, Adjacency, AdjComp>::iterator, multimap<Adjacency, Adjacency, AdjComp>::iterator> ret; // iterator range to all mapped elements
string left, right, new_left, new_right, flag; // record the
// begin the iteration
left = c.front().first;
right = c.back().second;
// iterate on left direction
while (left != "oo" && flag != "cycle") {
ret = connections.equal_range(c.front());
int match_num = 0;
new_left = left;
for (multimap<Adjacency, Adjacency, AdjComp>::iterator it = ret.first; it != ret.second; it++) {
if ((*it).second.Contain(left)) {
match_num++;
if (elements.find((*it).second) != elements.end()) {
flag = "cycle";
} else {
c.push_front((*it).second);
elements.insert((*it).second);
new_left = (*it).second.first == left ? (*it).second.second : (*it).second.first;
}
}
}
left = new_left;
if (match_num != 1) {
dist_log << "Error: non/concurrent matched adj " << endl;
}
}
// iterate on right direction
while (right != "oo" && flag != "cycle") {
ret = connections.equal_range(c.back());
int match_num = 0;
new_right = right;
for (multimap<Adjacency, Adjacency, AdjComp>::iterator it = ret.first; it != ret.second; it++) {
if ((*it).second.Contain(right)) {
match_num++;
if (elements.find((*it).second) != elements.end()) {
flag = "cycle";
} else {
c.push_back((*it).second);
elements.insert((*it).second);
new_right = (*it).second.first == right ? (*it).second.second : (*it).second.first;
}
}
}
right = new_right;
if (match_num != 1) {
dist_log << "Error: non/concurrent matched adj " << endl;
}
}
if (flag == "cycle")
c.type = "cycle";
else
c.type = c.front().side + c.back().side;
// dist_log << c.type << ", ";
// for(Component::iterator it=c.begin();it!=c.end();it++){
// (*it).Print(dist_log);
// dist_log << ",\t";
// }
// dist_log << endl;
ag_graph.push_back(c);
// remove Component elements in the connections.
for (set<Adjacency, AdjComp>::iterator it = elements.begin(); it != elements.end(); it++) {
connections.erase(*it);
}
}
// compress the ag graph and statistic on num of cycles and different paths
int num_cycle = 0, num_AB = 0, num_BA = 0, num_AA = 0, num_BB = 0, num_empty = 0;
ReducedGraph run_graph;
for (Graph::iterator it1 = ag_graph.begin(); it1 != ag_graph.end(); it1++) {
Component c = *it1;
if (c.type == "cycle") { // put adj with mark A on the front of the cycle
num_cycle++;
Adjacency a0 = c.front(), a_split = c.front();
for (Component::iterator it2 = c.begin(); it2 != c.end(); it2++) {
if (it2->labels.size() > 0 && it2->side == "A") {
a_split = *it2;
break;
}
}
while (a0 != a_split) {
c.pop_front();
c.push_back(a0);
a0 = c.front();
}
} else if (c.type == "AB") {
num_AB++;
} else if (c.type == "BA") { // Turn "BA" -> "AB"
num_BA++;
c.reverse();
c.type = "AB";
} else if (c.type == "AA") {
num_AA++;
} else if (c.type == "BB") {
num_BB++;
} else if (c.type == "") {
num_empty++;
} else {
dist_log << "impossible component" << endl;
}
// compress the component
ReducedComponent runs;
runs.type_path = c.type;
string prev_side = "nothing";
for (Component::iterator it2 = c.begin(); it2 != c.end(); it2++) {
if (it2->labels.size() > 0 && it2->side != prev_side) {
runs.push_back(it2->side);
prev_side = it2->side;
}
}
if (runs.size() > 0) {
run_graph.push_back(runs);
}
}
// dist_log << "cycle num: " << num_cycle << "\tAB: " << num_AB << "\tBA: " << num_BA << "\tAA: " << num_AA << "\tBB: " << num_BB << "\tempty: " << num_empty << endl;
// statistic on num_runs, landa = [num_rum+1/2]
int sum_lambda = 0, num_AA_a = 0, num_AA_b = 0, num_AA_ab = 0,
num_AB_a = 0, num_AB_b = 0, num_AB_ab = 0, num_AB_ba = 0,
num_BB_a = 0, num_BB_b = 0, num_BB_ab = 0;
for (ReducedGraph::iterator it = run_graph.begin(); it != run_graph.end(); it++) {
int num_runs = 0, lambda = 0;
num_runs = it->size();
lambda = (int) ceil((num_runs + 1) / 2);
sum_lambda += lambda;
if (num_runs = 0) {
cerr << "impossible 0 number of runs" << endl;
} else if (num_runs % 2 == 1) { // odd runs
it->type_run = (*it).front();
} else if (num_runs % 2 == 0) { // even runs
it->type_run = it->front() + it->back();
} else {
cerr << "impossible negative number of runs" << endl;
}
if (it->type_path == "AA") {
if (it->type_run == "A")
num_AA_a++;
else if (it->type_run == "B")
num_AA_b++;
else if (it->type_run == "AB")
num_AA_ab++;
} else if (it->type_path == "BB") {
if (it->type_run == "A")
num_BB_a++;
else if (it->type_run == "B")
num_BB_b++;
else if (it->type_run == "AB")
num_BB_ab++;
} else if (it->type_path == "AB") {
if (it->type_run == "A")
num_AB_a++;
else if (it->type_run == "B")
num_AB_b++;
else if (it->type_run == "AB")
num_AB_ab++;
else if (it->type_run == "BA")
num_AB_ba++;
} else if (it->type_path == "cycle") {
continue;
} else {
cerr << "impossible type of path: " << it->type_path << endl;
}
}
// dist_log << "sum_lambda: " << sum_lambda << "\tAA_a: " << num_AA_a << "\tAA_b: " << num_AA_b << "\tAA_ab: " << num_AA_ab
// << "\tAB_a: " << num_AB_a << "\tAB_b: " << num_AB_b << "\tAB_ab: " << num_AB_ab << "\tAB_ba: " << num_AB_ba
// << "\tBB_a: " << num_BB_a << "\tBB_b: " << num_BB_b << "\tBB_ab: " << num_BB_ab << endl;
// Calculate # of P Q T S
int P = 0, Q = 0, T = 0, S = 0, M = 0, N = 0;
// P
if (num_AA_ab > 0 || num_BB_ab > 0) {
int min = num_AA_ab > num_BB_ab ? num_BB_ab : num_AA_ab;
if (min >= 0) {
P += min;
num_AA_ab -= min;
num_BB_ab -= min;
}
}
// Q 2AA_ab + BB_a + BB_b
if (num_AA_ab > 0 || num_BB_a > 0 || num_BB_b > 0) {
int min = (num_AA_ab / 2) > num_BB_a ? num_BB_a : (num_AA_ab / 2);
min = min > num_BB_b ? num_BB_b : min;
if (min >= 0) {
Q += min;
num_AA_ab -= 2 * min;
num_BB_a -= min;
num_BB_b -= min;
}
}
// Q 2BB_ab + AA_a + AA_b
if (num_BB_ab > 0 || num_AA_a > 0 || num_AA_b > 0) {
int min = (num_BB_ab / 2) > num_AA_a ? num_AA_a : (num_BB_ab / 2);
min = min > num_AA_b ? num_AA_b : min;
if (min >= 0) {
Q += min;
num_BB_ab -= 2 * min;
num_AA_a -= min;
num_AA_b -= min;
}
}
// T AA_ab + BB_a + AB_ab
if (num_AA_ab > 0 || num_BB_a > 0 || num_AB_ab > 0) {
int min = num_AA_ab > num_BB_a ? num_BB_a : num_AA_ab;
min = min > num_AB_ab ? num_AB_ab : min;
if (min >= 0) {
T += min;
num_AA_ab -= min;
num_BB_a -= min;
num_AB_ab -= min;
}
}
// T AA_ab + BB_b + AB_ba
if (num_AA_ab > 0 || num_BB_b > 0 || num_AB_ba > 0) {
int min = num_AA_ab > num_BB_b ? num_BB_b : num_AA_ab;
min = min > num_AB_ba ? num_AB_ba : min;
if (min >= 0) {
T += min;
num_AA_ab -= min;
num_BB_b -= min;
num_AB_ba -= min;
}
}
// T BB_ab + AA_a + AB_ba
if (num_BB_ab > 0 || num_AA_a > 0 || num_AB_ba > 0) {
int min = num_BB_ab > num_AA_a ? num_AA_a : num_BB_ab;
min = min > num_AB_ba ? num_AB_ba : min;
if (min >= 0) {
T += min;
num_BB_ab -= min;
num_AA_a -= min;
num_AB_ba -= min;
}
}
// T BB_ab + AA_b + AB_ab
if (num_BB_ab > 0 || num_AA_b > 0 || num_AB_ab > 0) {
int min = num_BB_ab > num_AA_b ? num_AA_b : num_BB_ab;
min = min > num_AB_ab ? num_AB_ab : min;
if (min >= 0) {
T += min;
num_BB_ab -= min;
num_AA_b -= min;
num_AB_ab -= min;
}
}
// T 2AA_ab + BB_a
if (num_AA_ab > 0 || num_BB_a > 0) {
int min = (num_AA_ab / 2) > num_BB_a ? num_BB_a : (num_AA_ab / 2);
if (min >= 0) {
T += min;
num_AA_ab -= 2 * min;
num_BB_a -= min;
}
}
// T 2AA_ab + BB_b
if (num_AA_ab > 0 || num_BB_b > 0) {
int min = (num_AA_ab / 2) > num_BB_b ? num_BB_b : (num_AA_ab / 2);
if (min >= 0) {
T += min;
num_AA_ab -= 2 * min;
num_BB_b -= min;
}
}
// T 2BB_ab + AA_a
if (num_BB_ab > 0 || num_AA_a > 0) {
int min = (num_BB_ab / 2) > num_AA_a ? num_AA_a : (num_BB_ab / 2);
if (min >= 0) {
T += min;
num_BB_ab -= 2 * min;
num_AA_a -= min;
}
}
// T 2BB_ab + AA_b
if (num_BB_ab > 0 || num_AA_b > 0) {
int min = (num_BB_ab / 2) > num_AA_b ? num_AA_b : (num_BB_ab / 2);
if (min >= 0) {
T += min;
num_BB_ab -= 2 * min;
num_AA_b -= min;
}
}
// S AA_a + BB_a
if (num_AA_a > 0 || num_BB_a > 0) {
int min = num_AA_a > num_BB_a ? num_BB_a : num_AA_a;
if (min >= 0) {
S += min;
num_AA_a -= min;
num_BB_a -= min;
}
}
// S AA_b + BB_b
if (num_AA_b > 0 || num_BB_b > 0) {
int min = num_AA_b > num_BB_b ? num_BB_b : num_AA_b;
if (min >= 0) {
S += min;
num_AA_b -= min;
num_BB_b -= min;
}
}
// S AB_ab + AB_ba
if (num_AB_ab > 0 || num_AB_ba > 0) {
int min = num_AB_ab > num_AB_ba ? num_AB_ba : num_AB_ab;
if (min >= 0) {
S += min;
num_AB_ab -= min;
num_AB_ba -= min;
}
}
// S AA_ab + BB_a
if (num_AA_ab > 0 || num_BB_a > 0) {
int min = num_AA_ab > num_BB_a ? num_BB_a : num_AA_ab;
if (min >= 0) {
S += min;
num_AA_ab -= min;
num_BB_a -= min;
}
}
// S AA_ab + BB_b
if (num_AA_ab > 0 || num_BB_b > 0) {
int min = num_AA_ab > num_BB_b ? num_BB_b : num_AA_ab;
if (min >= 0) {
S += min;
num_AA_ab -= min;
num_BB_b -= min;
}
}
// S BB_ab + AA_a
if (num_BB_ab > 0 || num_AA_a > 0) {
int min = num_BB_ab > num_AA_a ? num_AA_a : num_BB_ab;
if (min >= 0) {
S += min;
num_BB_ab -= min;
num_AA_a -= min;
}
}
// S BB_ab + AA_b
if (num_BB_ab > 0 || num_AA_b > 0) {
int min = num_BB_ab > num_AA_b ? num_AA_b : num_BB_ab;
if (min >= 0) {
S += min;
num_BB_ab -= min;
num_AA_b -= min;
}
}
// S AA_ab + AB_ab
if (num_AA_ab > 0 || num_AB_ab > 0) {
int min = num_AA_ab > num_AB_ab ? num_AB_ab : num_AA_ab;
if (min >= 0) {
S += min;
num_AA_ab -= min;
num_AB_ab -= min;
}
}
// S AA_ab + AB_ba
if (num_AA_ab > 0 || num_AB_ba > 0) {
int min = num_AA_ab > num_AB_ba ? num_AB_ba : num_AA_ab;
if (min >= 0) {
S += min;
num_AA_ab -= min;
num_AB_ba -= min;
}
}
// S BB_ab + AB_ab
if (num_BB_ab > 0 || num_AB_ab > 0) {
int min = num_BB_ab > num_AB_ab ? num_AB_ab : num_BB_ab;
if (min >= 0) {
S += min;
num_BB_ab -= min;
num_AB_ab -= min;
}
}
// S BB_ab + AB_ba
if (num_BB_ab > 0 || num_AB_ba > 0) {
int min = num_BB_ab > num_AB_ba ? num_AB_ba : num_BB_ab;
if (min >= 0) {
S += min;
num_BB_ab -= min;
num_AB_ba -= min;
}
}
// S AA_ab + AA_ab
if (num_AA_ab > 0) {
int min = (num_AA_ab / 2);
if (min >= 0) {
S += min;
num_AA_ab -= 2 * min;
}
}
// S BB_ab + BB_ab
if (num_BB_ab > 0) {
int min = (num_BB_ab / 2);
if (min >= 0) {
S += min;
num_BB_ab -= 2 * min;
}
}
// M 2AB_ab + AA_b + BB_a
if (num_AB_ab > 0 || num_AA_b > 0 || num_BB_a > 0) {
int min = (num_AB_ab / 2) > num_AA_b ? num_AA_b : (num_AB_ab / 2);
min = min > num_BB_a ? num_BB_a : min;
if (min >= 0) {
M += min;
num_AB_ab -= 2 * min;
num_AA_b -= min;
num_BB_a -= min;
}
}
// M 2AB_ba + AA_a + BB_b
if (num_AB_ba > 0 || num_AA_a > 0 || num_BB_b > 0) {
int min = (num_AB_ba / 2) > num_AA_a ? num_AA_a : (num_AB_ba / 2);
min = min > num_BB_b ? num_BB_b : min;
if (min >= 0) {
M += min;
num_AB_ba -= 2 * min;
num_AA_a -= min;
num_BB_b -= min;
}
}
// N AB_ab + AA_b + BB_a
if (num_AB_ab > 0 || num_AA_b > 0 || num_BB_a > 0) {
int min = num_AB_ab > num_AA_b ? num_AA_b : num_AB_ab;
min = min > num_BB_a ? num_BB_a : min;
if (min >= 0) {
N += min;
num_AB_ab -= min;
num_AA_b -= min;
num_BB_a -= min;
}
}
// N AB_ba + AA_a + BB_b
if (num_AB_ba > 0 || num_AA_a > 0 || num_BB_b > 0) {
int min = num_AB_ba > num_AA_a ? num_AA_a : num_AB_ba;
min = min > num_BB_b ? num_BB_b : min;
if (min >= 0) {
N += min;
num_AB_ba -= min;
num_AA_a -= min;
num_BB_b -= min;
}
}
// N 2AB_ab + AA_b
if (num_AB_ab > 0 || num_AA_b > 0) {
int min = (num_AB_ab / 2) > num_AA_b ? num_AA_b : (num_AB_ab / 2);
if (min >= 0) {
N += min;
num_AB_ab -= 2 * min;
num_AA_b -= min;
}
}
// N 2AB_ab + BB_a
if (num_AB_ab > 0 || num_BB_a > 0) {
int min = (num_AB_ab / 2) > num_BB_a ? num_BB_a : (num_AB_ab / 2);
if (min >= 0) {
N += min;
num_AB_ab -= 2 * min;
num_BB_a -= min;
}
}
// N 2AB_ba + AA_a
if (num_AB_ba > 0 || num_AA_a > 0) {
int min = (num_AB_ba / 2) > num_AA_a ? num_AA_a : (num_AB_ba / 2);
if (min >= 0) {
N += min;
num_AB_ba -= 2 * min;
num_AA_a -= min;
}
}
// N 2AB_ba + BB_b
if (num_AB_ba > 0 || num_BB_b > 0) {
int min = (num_AB_ba / 2) > num_BB_b ? num_BB_b : (num_AB_ba / 2);
if (min >= 0) {
N += min;
num_AB_ba -= 2 * min;
num_BB_b -= min;
}
}
int dcj_distance = num_shared_genes - num_cycle - (num_AB + num_BA) / 2;
int indel_distance = sum_lambda - (2 * P + 3 * Q + 2 * T + S + 2 * M + N);
dist_log.close();
return std::make_pair(dcj_distance, indel_distance);
}
int main(int argc, char** argv) {
if (argc != 4) {
std::cerr << "Usage: ./distance <first_genome> <second_genome> <out_file>" << std::endl
<< "Genome in basic grimm format" << std::endl;
if (argc == 2 && std::string(argv[1]) == "--help") {
return 0;
}
return 1;
}
IO input;
auto first_genome = input.ImportGenome(argv[1]);
auto second_genome = input.ImportGenome(argv[2]);
auto result = Distance(first_genome, second_genome);
std::ofstream stream_out(argv[3]);
stream_out << result.first << " " << result.second << std::endl;
stream_out.close();
return 0;
}
<file_sep>MGRA ESTIMATOR
----
This project contain different scripts for run and calculate different measures
for related mgra project (see https://github.com/ablab/mgra).
TBA
<file_sep>"""
Some basic functions which needed to script
"""
import os
def get_immediate_subdirectories(a_dir):
"""
This function get subdirectories
"""
return ((os.path.join(a_dir, name), name) for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name)))
def get_immediate_files(a_dir):
"""
This function get files
"""
return ((os.path.join(a_dir, name), name) for name in os.listdir(a_dir) if
os.path.isfile(os.path.join(a_dir, name)))
def which(program):
"""
Mimics UNIX "which" command
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None<file_sep>#!/usr/bin/python3.4
import argparse
import subprocess
import os
from shutil import move, copy
import fnmatch
import csv
import time
import logging
import sys
parser = argparse.ArgumentParser(description='Script for measuring working time of tools')
parser.add_argument('tools', type=list, help='List of tools you want to compare')
parser.add_argument('path', type=str, help='Path to folder with chosen parameters')
parser.add_argument('result', type=str, help='Path to and name of resulting csv table')
args = parser.parse_args()
tools = args.tools
path = args.path
result_path = args.result
class tester():
def run_procars(self, path, test_dir):
old_path = os.path.join(path, test_dir, 'Procars', '')
new_path = '/home/hamster/tools/procars/'
if not os.path.isdir(old_path + 'result'):
os.chdir(new_path)
operation = 'python2 procars_main ' \
'-t '+ old_path + 'tree.txt ' \
'-b ' + old_path + 'blocks.txt ' \
'-r ' + old_path + 'result'
print(subprocess.call(operation, shell=True))
def run_infercarspro(self, path, test_dir):
old_path = os.path.join(path, test_dir, 'InferCarsPro', '')
new_path = '/home/hamster/tools/InferCarsPro/'
if len(fnmatch.filter(os.listdir(old_path), '*.*')) > 2:
os.chdir(new_path)
operation = './InferCarsPro ' + old_path + 'tree_tag.txt ' \
'' + old_path + 'blocks.txt'
print(subprocess.call(operation, shell=True))
files = os.listdir(new_path)
infer_files = filter(lambda x: x.endswith('.txt') and x.startswith('Infer'), files)
infer_car_files = filter(lambda x: x.endswith('.car'), files)
for file in infer_files:
move(file, old_path + '/time')
for file in infer_car_files:
move(file, old_path + '/time')
def run_PMAG(self, path, test_dir):
old_path = os.path.join(path, test_dir, 'PMAG', '')
new_path = '/home/hamster/tools/PMAG/'
if len(fnmatch.filter(os.listdir(old_path), '*.*')) > 1:
copy(old_path + 'blocks.txt', new_path)
copy(old_path + 'tree.txt', new_path)
os.chdir(new_path)
operation = 'perl RunPMAG+.pl blocks.txt tree.txt result.txt'
print(subprocess.call(operation, shell=True))
move('result.txt', old_path + '/time')
os.remove('blocks.txt')
os.remove('tree.txt')
def run_MGRA(self, path, test_dir):
current_path = os.path.join(path, test_dir, 'MGRA', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 2:
operation = '~/tools/MGRA/build/mgra -c ' + \
current_path + 'sim.cfg -f grimm - g ' + current_path + \
'blocks.txt -o ' + current_path + ' 2>logerror.txt >/dev/null'
print(subprocess.call(operation, shell=True))
def run_GASTS(self, path, test_dir):
current_path = os.path.join(path, test_dir, 'GASTS', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 2:
copy('/home/hamster/tools/GASTS/gasts.jar', current_path + 'gasts.jar')
operation = 'java -jar ' + \
'gasts.jar ' + \
'tree.txt ' + \
'blocks.txt'
os.chdir(current_path)
print(subprocess.call(operation, shell=True))
os.remove(current_path + 'gasts.jar')
def run_GapAdj(self, path, test_dir):
current_path = os.path.join(path, test_dir, 'GapAdj', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 2:
files = os.listdir(current_path)
trees = filter(lambda x: x.endswith('.tree'), files)
for current_tree in trees:
dirName, fileName = os.path.split(current_tree)
fileBaseName, fileExtension = os.path.splitext(fileName)
name_gen = fileBaseName + '.gap_gen'
operation = '/home/hamster/tools/GapAdj/GapAdj ' \
+ current_tree + ' ' + dirName + \
'/blocks.txt ' + dirName + '/' + name_gen \
+ ' 25 0.6'
print(subprocess.call(operation, shell=True))
def run_rococo(self, path, test_dir):
current_path = os.path.join(path, test_dir, 'Rococo', '')
copy('/home/hamster/rococo/rococo-2.0.jar', current_path + 'rococo.jar')
operation = 'java -jar ' + \
'rococo.jar -m=u -p=s ' + \
'tree_tag.txt ' + \
'blocks.txt result'
os.chdir(current_path)
print(subprocess.call(operation, shell=True))
os.remove(current_path + 'rococo.jar')
def time_check(self, tool, path, test_dir):
start = time.time()
print('working with ' + test_dir)
if tool == 'GapAdj':
self.run_GapAdj(path, test_dir)
elif tool == 'PMAG':
self.run_PMAG(path, test_dir)
elif tool == 'MGRA':
self.run_MGRA(path, test_dir)
elif tool == 'GASTS':
self.run_GASTS(path, test_dir)
elif tool == 'Procars':
self.run_procars(path, test_dir)
elif tool == 'InferCarsPro':
self.run_infercarspro(path, test_dir)
elif tool == 'Rococo':
self.run_rococo(path, test_dir)
times.append(time.time() - start)
def test_time(tools, path, result_path):
with open(result_path, 'w') as out:
csv_out = csv.writer(out)
csv_out.writerow(['name', 'time'])
for tool in tools:
times = []
for i in [1,2,3,4,5,6,7,8,9,10]:
tester().time_check(tool, path, '1')
mean_time = sum(times)/len(times)
csv_out.writerow([tool, mean_time])
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
if (len(sys.argv) < 2):
sys.stderr.write("USAGE: time_tester.py <tool> <path> <result> \n")
sys.exit(1)
if os.path.isfile(path):
sys.stderr.write("<path> - is directory with strong hierarchy\n")
sys.exit(1)
test_time(tools, path, result_path)<file_sep>import os
import sys
import Handler
import utils.utils as utils
class SIMUL_handler(Handler.Handler):
def __init__(self):
super(SIMUL_handler, self).__init__("simul")
#self.name_tool = "simul"
def parse(self, dir_path):
genomes = {}
path = os.path.join(dir_path, self.name_tool)
for path_to_file, _ in utils.get_immediate_files(path):
genome = Handler.parse_genome_in_grimm_file(path_to_file)
genomes[genome.get_name()] = genome
return genomes
def save(self, dir_path):
ancestors_file = os.path.join(dir_path, self.ancestor_file)
if not os.path.isfile(ancestors_file):
sys.stderr.write("Directory need contain ancestral.txt\n")
sys.exit(1)
genomes = Handler.parse_genomes_in_grimm_file(ancestors_file)
simul_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(simul_dir):
os.makedirs(simul_dir)
Handler.write_genomes_with_grimm_by_name(simul_dir, genomes, ".sim_gen")
<file_sep>import networkx as nx
def parse(file_name):
event = {}
with open(file_name) as f:
for line in f:
k2 = line.split(':')[0].split(' ')
k1 = str(k2[0]) + ' ' + str(k2[2])
info = line.split(':')[1].split(', #')
summary = [info[0].split(' ')[2], info[1].split(' ')[2],
info[2].split(' ')[2], info[3].split(' ')[2]]
event[k1] = summary
return event
def count_overall_distance(file_name, start_genome, end_genome):
G = nx.DiGraph()
data = parse(file_name)
for i in data:
G.add_edge(i.split(' ')[0], i.split(' ')[1],weight = int(data[i][0]))
return nx.shortest_path_length(G, start_genome, end_genome, weight = 'weight')
<file_sep>__author__ = 'nikita_kartashov'
from sys import argv
import dendropy as dp
from unrooted_tree import UnrootedBinaryTree
taxa = dp.TaxonSet()
def nt(s):
return dp.Tree.get_from_string(s, 'newick', taxon_set=taxa, as_unrooted=True)
def strip_argument(argument):
return argument.strip("\"")
def main():
if len(argv) < 3:
print("Need to input 2 trees in newick format")
exit(1)
left_tree = nt(strip_argument(argv[1]))
right_tree = nt(strip_argument(argv[2]))
t1 = UnrootedBinaryTree(left_tree.nodes()[0])
t2 = UnrootedBinaryTree(right_tree.nodes()[0])
print('Left tree: {0}'.format(left_tree.as_newick_string()))
print('Right tree: {0}'.format(right_tree.as_newick_string()))
print(left_tree.symmetric_difference(right_tree))
print('\n'.join(t1.pretty_branches(t1.compare_branches(t2))))
print('Distance difference: {0}'.format(t1.compare_distances(t2)))
if __name__ == '__main__':
main()
<file_sep>#!/bin/bash
HOME_DIR=${PWD}
NAME_DIR=${HOME_DIR}/CLASSIC
TOOL_NAME=${HOME_DIR}/shiva
#######################################
## Parameters for generated datasets ##
#######################################
#>Parameters file
NUMBERGENE=(200 300 400)
NUMBERGENOMES=(6 9 12 15)
NUMBERCHR=5
PERBRANCH=(100 200)
VARIANCE=(50 100)
INVERSION=0.9
TRANSPOSITION=0.0
TRANSVERSION=0.0
FISSION=0.0
FUSSION=0.0
TRANSLOCATION=0.1
DELETION=0
LENGTH_DEL=0
INSERTION=0
LENGTH_INS=0
NUMBER_DATASETS=10
## Function for generation datasets with parameters ##
function build_datasets {
for numb_genome in ${NUMBERGENOMES[@]}
do
for numb_gene in ${NUMBERGENE[@]}
do
for per_branch in ${PERBRANCH[@]}
do
echo New dataset: ${numb_genome} ${numb_gene} ${per_branch}
name_dir=${numb_genome}_${numb_gene}_${per_branch}_0
current_dir=${NAME_DIR}/${name_dir}
mkdir ${current_dir}
for i in {1..10}
do
echo Dataset ${i}
mkdir ${current_dir}/${i}
## Save configuration file ##
echo ">Parameters file" > ${current_dir}/${i}/config.txt
echo >> ${current_dir}/${i}/config.txt
echo ${numb_gene} >> ${current_dir}/${i}/config.txt
echo ${numb_genome} >> ${current_dir}/${i}/config.txt
echo ${NUMBERCHR} >> ${current_dir}/${i}/config.txt
echo >> ${current_dir}/${i}/config.txt
variation=$(( per_branch / 2 ))
echo ${per_branch} >> ${current_dir}/${i}/config.txt
echo ${variation} >> ${current_dir}/${i}/config.txt
echo >> ${current_dir}/${i}/config.txt
echo ${INVERSION} >> ${current_dir}/${i}/config.txt
echo ${TRANSPOSITION} >> ${current_dir}/${i}/config.txt
echo ${TRANSVERSION} >> ${current_dir}/${i}/config.txt
echo ${FISSION} >> ${current_dir}/${i}/config.txt
echo ${FUSSION} >> ${current_dir}/${i}/config.txt
echo ${TRANSLOCATION} >> ${current_dir}/${i}/config.txt
echo ${DELETION} >> ${current_dir}/${i}/config.txt
echo ${LENGTH_DEL} >> ${current_dir}/${i}/config.txt
echo ${INSERTION} >> ${current_dir}/${i}/config.txt
echo ${LENGTH_INS} >> ${current_dir}/${i}/config.txt
## run shiva ##
cp ${TOOL_NAME} ${current_dir}/${i}/shiva
cd ${current_dir}/${i}
./shiva config.txt blocks.txt bad_tree.txt ancestral.txt tree.txt >log.txt
rm shiva
cd ${HOME_DIR}
done
done
done
done
}
##########
## Main ##
##########
if [ -d ${NAME_DIR} ]; then
rm -rf ${NAME_DIR}
fi
mkdir ${NAME_DIR}
build_datasets
##########
## END ##
##########
<file_sep>#!/usr/bin/python3.4
import argparse
import subprocess
import os
import logging
import sys
from shutil import copyfile, move, copy
import fnmatch
import csv
import time
parser = argparse.ArgumentParser(description='Script for running tools ')
parser.add_argument('tool', choices=['GapAdj', 'PMAG', 'MGRA',
'GASTS', 'Procars', 'InferCarsPro', 'Rococo'], type=str,
help='Run tool of your choice')
parser.add_argument('path', type=str, help='Path to folder with chosen parameters')
args = parser.parse_args()
tool = args.tool
path = args.path
# Version for small tests
def main_runner(tool, path):
for test_dir in os.listdir(path):
print('working with ' + path + ' ' + test_dir)
if tool == 'GapAdj':
run_GapAdj(path, test_dir)
if tool == 'PMAG':
run_PMAG(path, test_dir)
elif tool == 'MGRA':
run_MGRA(path, test_dir)
elif tool == 'GASTS':
run_GASTS(path, test_dir)
elif tool == 'Procars':
run_procars(path, test_dir)
elif tool == 'InferCarsPro':
run_infercarspro(path, test_dir)
elif tool == 'Rococo':
run_rococo(path, test_dir)
#version for tests on whole dataset
def main_runner_all(tool, path):
for dir in os.listdir(path):
print('working with ' + dir)
for test_dir in os.listdir(path + '/' + dir):
print('working with ' + test_dir)
if tool == 'GapAdj':
run_GapAdj(path + '/' + dir, test_dir)
elif tool == 'PMAG':
run_PMAG(path + '/' + dir, test_dir)
elif tool == 'MGRA':
run_MGRA(path + '/' + dir, test_dir)
elif tool == 'GASTS':
run_GASTS(path + '/' + dir, test_dir)
elif tool == 'Procars':
run_procars(path + '/' + dir, test_dir)
elif tool == 'InferCarsPro':
run_infercarspro(path + '/' + dir, test_dir)
elif tool == 'Rococo':
run_rococo(path + '/' + dir, test_dir)
def run_procars(path, test_dir):
old_path = os.path.join(path, test_dir, 'Procars', '')
new_path = '/home/hamster/tools/procars/'
os.chdir(new_path)
operation = 'python2 procars_main ' \
'-t '+ old_path + 'tree.txt ' \
'-b ' + old_path + 'blocks.txt ' \
'-r ' + old_path + 'result'
print(subprocess.call(operation, shell=True))
def run_infercarspro(path, test_dir):
old_path = os.path.join(path, test_dir, 'InferCarsPro', '')
new_path = '/home/hamster/tools/InferCarsPro/'
os.chdir(new_path)
operation = './InferCarsPro ' + old_path + 'tree_tag.txt ' \
'' + old_path + 'blocks.txt'
print(subprocess.call(operation, shell=True))
files = os.listdir(new_path)
infer_files = filter(lambda x: x.endswith('.txt') and x.startswith('Infer'), files)
infer_car_files = filter(lambda x: x.endswith('.car'), files)
for file in infer_files:
move(file, old_path)
for file in infer_car_files:
move(file, old_path)
def run_PMAG(path, test_dir):
old_path = os.path.join(path, test_dir, 'PMAG', '')
new_path = '/home/hamster/tools/PMAG/'
if len(fnmatch.filter(os.listdir(old_path), '*.*')) > 0:
copy(old_path + 'blocks.txt', new_path)
copy(old_path + 'tree.txt', new_path)
os.chdir(new_path)
operation = 'perl RunPMAG+.pl blocks.txt tree.txt result.txt'
print(subprocess.call(operation, shell=True))
move('result.txt', old_path)
os.remove('blocks.txt')
os.remove('tree.txt')
def run_MGRA(path, test_dir):
current_path = os.path.join(path, test_dir, 'MGRA', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 0:
operation = '~/tools/MGRA/build/mgra -c ' + \
current_path + 'sim.cfg -g ' + current_path + \
'blocks.txt -o ' + current_path
print(subprocess.call(operation, shell=True))
def run_GASTS(path, test_dir):
current_path = os.path.join(path, test_dir, 'GASTS', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 0:
copy('/home/hamster/tools/GASTS/gasts.jar', current_path + 'gasts.jar')
operation = 'java -jar ' + \
'gasts.jar ' + \
'tree.txt ' + \
'blocks.txt'
os.chdir(current_path)
print(subprocess.call(operation, shell=True))
os.remove(current_path + 'gasts.jar')
def run_GapAdj(path, test_dir):
current_path = os.path.join(path, test_dir, 'GapAdj', '')
if len(fnmatch.filter(os.listdir(current_path), '*.*')) > 0:
files = os.listdir(current_path)
trees = filter(lambda x: x.endswith('.tree'), files)
for current_tree in trees:
dirName, fileName = os.path.split(current_tree)
fileBaseName, fileExtension = os.path.splitext(fileName)
name_gen = fileBaseName + '.gap_gen'
operation = '/home/hamster/tools/GapAdj/GapAdj ' \
+ current_tree + ' ' + dirName + \
'/blocks.txt ' + dirName + '/' + name_gen \
+ ' 25 0.6'
print(subprocess.call(operation, shell=True))
def run_rococo(path, test_dir):
current_path = os.path.join(path, test_dir, 'Rococo', '')
tool_path = '/home/hamster/rococo/rococo-2.0.jar'
operation = 'java -jar ' + \
tool_path + ' -v -m=u -p=s ' + \
'tree_tag.txt ' + \
'blocks.txt result'
os.chdir(current_path)
print(subprocess.call(operation, shell=True))
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
if (len(sys.argv) < 2):
sys.stderr.write("USAGE: tester.py <tool> <path> \n")
sys.exit(1)
if os.path.isfile(path):
sys.stderr.write("<path> - is directory with strong hierarchy\n")
sys.exit(1)
main_runner(tool, path)
<file_sep>#!/usr/bin/python
import os
import re
import sys
import logging
from functools import partial
import Configure as conf
import parsers.GASTS_handler as gasts_handler
import graphics_drawer.bar_chart as bar_chart
import measures.Measures as measures
import utils.utils as utils
import utils.Wrapers as wrap
def dojob(number_tools, init_func, accumul_func, divide_func, dir_path, filter_func, procces_directory_func):
answer = {}
for path, name in utils.get_immediate_subdirectories(dir_path):
logging.info("Worked with " + name + " dataset")
expr = re.match('(\d+)_(\d+)_(\d+)_(\d+)', name)
params = (int(expr.group(1)), int(expr.group(2)), int(expr.group(3)), int(expr.group(4)))
if filter_func(params):
accamul = init_func(number_tools)
count = 0
for subpath, subname in utils.get_immediate_subdirectories(path):
logging.info("Process next example with number " + subname + " dataset")
current = procces_directory_func(subpath)
count += 1
for i in range(number_tools):
accamul[i] = accumul_func(accamul[i], current[i])
for i in range(number_tools):
accamul[i] = divide_func(accamul[i], count)
answer[params] = accamul
return answer
float_dojob = partial(dojob, len(conf.tools), wrap.init_float_list_func, wrap.accumulation_float_func,
wrap.divide_float_func)
tuple_dojob = partial(dojob, len(conf.tools), wrap.init_tuple_list_func, wrap.accumulation_tuple_func,
wrap.divide_tuple_func)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
if (len(sys.argv) < 3):
sys.stderr.write("USAGE: walker.py <destination> <output_dir>\n")
sys.stderr.write("destination - is directory with strong hierarchy created by PrepareInput\n")
sys.exit(1)
dir_path = os.path.abspath(sys.argv[1])
output_dir = os.path.join(sys.argv[2])
params_files = [6, 9, 12, 15]
for index in params_files:
print(index)
distance_file = os.path.join(output_dir, "distance" + str(index) + ".pdf")
answer = float_dojob(dir_path, partial(conf.filter_genomes_by_species, 12), wrap.distance_func)
bar_chart.draw_clustered_histogram(distance_file, answer)
accuracy_file = os.path.join(output_dir, "accuracy" + str(index) + ".pdf")
answer = tuple_dojob(dir_path, partial(conf.filter_genomes_by_species, index), wrap.accuracy_func)
name_labels, vals, min_y = bar_chart.prepare_unique_datasets(conf.tools, answer)
bar_chart.draw_clustered_stacked_histigram(accuracy_file, name_labels, vals, min_y, "Accuracy content", len(conf.tools))
'''
for key, res in answer.iteritems():
_, genes, rear, _ = key
name = "(" + str(5 * genes) + "," + str(rear) + ")"
print("Dataset: " + name)
print("MGRA")
print(res[0])
print("PMAG+")
print(res[1])
print("GapAdj")
print(res[2])
print("GASTS")
print(res[3])
'''
#distance_file = os.path.join(output_dir, "distance9.pdf")
#bar_chart.draw_clustered_histogram(distance_file, answer)
'''answer = dojob(dir_path, len(conf.tools),
partial(conf.filter_genomes_by_species, 9),
partial(process_classical_directory_with_errors, conf.tools, measures.calculate_accuracy_measure))
output_dir = os.path.join(sys.argv[2])
accuracy_file = os.path.join(output_dir, "accuracy9.pdf")
name_labels, vals, min_y = bar_chart.prepare_unique_datasets(conf.tools, answer)
bar_chart.draw_clustered_stacked_histigram(accuracy_file, name_labels, vals, min_y, "Accuracy content", len(conf.tools))
'''
<file_sep>DIST_DIR := measures/cpp_impl
BIN_DIR := $(shell pwd)/lib
#setting compiler (if not set)
ifeq (${CXX},)
IS_CLANG := $(shell which clang++ >/dev/null 2>&1; echo $$?)
IS_GCC := $(shell which g++ >/dev/null 2>&1; echo $$?)
ifeq (${IS_CLANG},0)
CXX := clang++
else ifeq (${IS_GCC},0)
CXX := g++
else
err:
$(error Neither gcc nor clang compilers were detected.)
endif
endif
#adding necessary flags
CXXFLAGS += -std=c++11
UNAME := $(shell uname -s)
ifeq ($(UNAME),Darwin)
CXXFLAGS += -stdlib=libc++
LDFLAGS += -lc++
endif
export CXX
export CXXFLAGS
export LDFLAGS
export BIN_DIR
.PHONY: all distance clean
all: distance
distance:
make -C ${DIST_DIR} all
clean:
make -C ${DIST_DIR} clean
<file_sep>"""
File contain functions for calculate different measures which we used for comparison:
gene content
accuracy
DCJ-indel distance
absolute difference between the tree branch lengths based on DCJ-indel distance
Need to add for future, when MGRA start reconstructed tree:
Common branch with input tree and reconstructed tree.
"""
import os
import subprocess
import parsers.Handler as handler
import utils.utils as utils
DCJ_DISTANCE_EXEC = "distance"
def calculate_gene_content_measure(simul_genome, real_genome):
"""
Calculate gene content between simulation genome and real.
Return True Positive, False Positive, True Negative
"""
simul = set()
real = set()
for chr in simul_genome:
for gene in chr:
simul.add(abs(gene))
for chr in real_genome:
for gene in chr:
real.add(abs(gene))
pretty = simul.union(real)
TP = (float(len(simul.intersection(real))) / len(pretty)) * 100
FN = (float(len(simul.difference(real))) / len(pretty)) * 100
FP = (float(len(real.difference(simul))) / len(pretty)) * 100
return TP, FN, FP
def calculate_accuracy_measure(simul_genome, real_genome):
"""
Calculate accuracy between simulation genome and real.
Return True Positive, False Positive, True Negative
"""
simul = set()
real = set()
def create_adjacency_set(input_set, genome):
get_left = lambda gene: gene
get_right = lambda gene: -gene
for chromosome in genome:
chr = list(chromosome)
if chromosome.is_circular():
input_set.add((min(get_right(chr[-1]), get_left(chr[0])), max(get_right(chr[-1]), get_left(chr[0]))))
elif not chromosome.is_circular():
input_set.add((min(0, get_left(chr[0])), max(0, get_left(chr[0]))))
input_set.add((min(get_right(chr[-1]), 0), max(get_right(chr[-1]), 0)))
for prev, next in zip(chr, chr[1:]):
input_set.add((min(get_right(prev), get_left(next)), max(get_right(prev), get_left(next))))
create_adjacency_set(simul, simul_genome)
create_adjacency_set(real, real_genome)
pretty = simul.union(real)
#print(str(simul.difference(real)))
#print(str(real.difference(simul)))
TP = (float(len(simul.intersection(real))) / len(pretty)) * 100
FN = (float(len(simul.difference(real))) / len(pretty)) * 100
FP = (float(len(real.difference(simul))) / len(pretty)) * 100
return TP, FN, FP
def calculate_distance_measure(first_genome, second_genome):
"""
Calculate distance between first genome and second genome.
Return DCJ distance and indel distance.
"""
dcj, indel = calculate_DCJ_distance_and_indel_measure(first_genome, second_genome)
return (dcj + indel)
def calculate_branch_length_measure(simul_first_genome, simul_second_genome, real_first_genome, real_second_genome):
"""
Calculate differences on branch length between simulated genomes and real genomes.
Return DCJ distance.
"""
return abs(calculate_distance_measure(simul_first_genome, simul_second_genome)
- calculate_distance_measure(real_first_genome, real_second_genome))
def calculate_DCJ_distance_and_indel_measure(first_genome, second_genome):
"""
Calculate distance between first genome and second genome.
Return DCJ distance and indel distance.
"""
def run_code(first_file, second_file, out_file):
if not _check_binary():
return False
cmdline = [DCJ_DISTANCE_EXEC, first_file, second_file, out_file]
try:
subprocess.check_call(cmdline)
except subprocess.CalledProcessError as e:
#logger.error("Some error inside native {0} module: {1}".format(OVERLAP_EXEC, e))
return False
return True
first_genome_file = "first.txt"
second_genome_file = "second.txt"
out_f = "result.txt"
handler.write_genome_with_grimm_in_file(first_genome_file, first_genome)
handler.write_genome_with_grimm_in_file(second_genome_file, second_genome)
if run_code(first_genome_file, second_genome_file, out_f):
with open(out_f, 'r') as input:
result = input.readline().strip(' \t\n').split(' ')
dcj, indel = int(result[0]), int(result[1])
os.remove(out_f)
os.remove(first_genome_file)
os.remove(second_genome_file)
return dcj, indel
else:
os.remove(first_genome_file)
os.remove(second_genome_file)
return 0, 0
def _check_binary():
"""
Checks if the native binary is available and runnable
"""
binary = utils.which(DCJ_DISTANCE_EXEC)
if not binary:
# logger.error("\"{0}\" native module not found".format(OVERLAP_EXEC))
return False
try:
devnull = open(os.devnull, "w")
subprocess.check_call([DCJ_DISTANCE_EXEC, "--help"], stderr=devnull)
except subprocess.CalledProcessError as e:
# logger.error("Some error inside native {0} module: {1}".format(OVERLAP_EXEC, e))
return False
return True<file_sep>import os
from utils.Genome import Genome, Chromosome
class Handler(object):
def __init__(self, name_tool):
self.name_tool = name_tool
self.tree_file_with_tag = "tree.txt"
self.tree_file = "bad_tree.txt"
self.input_blocks_file = "blocks.txt"
self.ancestor_file = "ancestral.txt"
def get_name_tool(self):
return self.name_tool
def parse_genome_in_grimm_file(full_name):
"""
This function parse genomes files in grimm format.
# - comments
> [number] - name on genome
return genome have genome type (see Genome class)
"""
genome = Genome()
with open(full_name, 'r') as f:
chromosome = Chromosome()
for line in f:
line = line.strip(' \n\t')
if line.find("#") != -1 or len(line) == 0:
continue
if line.find('>') != -1:
genome.set_name(line[1:])
continue
for gene in line.split(' '):
str_gene = gene.strip(' \n\t')
if str_gene == '$':
chromosome.set_circular(False)
genome.append(chromosome)
chromosome = Chromosome()
elif str_gene == '@':
chromosome.set_circular(True)
genome.append(chromosome)
chromosome = Chromosome()
elif len(str_gene) != 0:
chromosome.append(int(str_gene))
return genome
def parse_genomes_in_grimm_file(full_name):
"""
This function parse genomes files in grimm format.
# - comments
> [number] - name on genome
return [genomes] where genome have genome type (see Genome class)
"""
genomes = []
with open(full_name, 'r') as f:
genome = Genome()
chromosome = Chromosome()
for line in f:
line = line.strip(' \n\t')
if line.find("#") != -1 or len(line) == 0:
continue
if line.find('>') != -1:
if chromosome.size() != 0:
genome.append(chromosome)
genomes.append(genome)
chromosome = Chromosome()
genome = Genome()
genome.set_name(line[1:])
continue
for gene in line.split(' '):
str_gene = gene.strip(' \n\t')
if str_gene == '$':
chromosome.set_circular(False)
genome.append(chromosome)
chromosome = Chromosome()
elif str_gene == '@':
chromosome.set_circular(True)
genome.append(chromosome)
chromosome = Chromosome()
elif len(str_gene) != 0:
chromosome.append(int(str_gene))
if chromosome.size() != 0:
genome.append(chromosome)
genomes.append(genome)
return genomes[1:]
def parse_genome_in_procars_file(full_name):
genome = Genome()
with open(full_name, 'r') as f:
chromosome = Chromosome()
for line in f:
line = line.strip(' \n\t')
genome.set_name('Ancestor')
if line.find("#") != -1 or len(line) == 0 or line.startswith('>'):
continue
line = line.strip('_Q ')
line = line.strip(' Q_')
line = line.strip('_R ')
line = line.strip(' R_')
line = line.strip('T ')
chromosome = Chromosome()
for gene in line.split(' '):
str_gene = gene.strip(' \n\t')
if len(str_gene) != 0 and str_gene != 'Q_':
chromosome.append(int(str_gene))
chromosome.set_circular(False)
genome.append(chromosome)
return genome
def parse_genome_in_infercarspro_file(full_name):
genome = Genome()
with open(full_name, 'r') as f:
chromosome = Chromosome()
for line in f:
line = line.strip(' \n\t')
anc_name = full_name[-5]
genome.set_name(anc_name)
if line.find("#") != -1 or line.find('>') != -1 or len(line) == 0:
continue
chromosome = Chromosome()
for gene in line.split(' '):
str_gene = gene.strip(' \n\t')
if str_gene == '$':
chromosome.set_circular(False)
genome.append(chromosome)
chromosome = Chromosome()
elif str_gene == '@':
chromosome.set_circular(True)
genome.append(chromosome)
chromosome = Chromosome()
elif len(str_gene) != 0:
chromosome.append(int(str_gene))
return genome
def parse_genomes_in_rococo_file(full_name):
genomes = []
with open(full_name, 'r') as f:
for line in f:
if line.find('CARs') == -1:
continue
else:
line = line.split('\t')
genome = Genome()
genome.set_name(line[0].strip(':'))
chromosomes = line[2].split('[')
for chrom in chromosomes[1:]:
chrom = chrom.split(']')
for chr in chrom:
if chr != '};\n' and chr != ',':
chr = chr.split(', ')
chromosome = Chromosome()
for gene in chr:
if len(gene) != 0:
chromosome.append(int(gene))
chromosome.set_circular(False)
genome.append(chromosome)
genomes.append(genome)
return genomes
def parse_genomes_in_cars_file(full_name):
genomes = {}
with open(full_name, 'r') as f:
for line in f:
if line.find('>') != -1:
marker = int(line[1:])
elif line != '\n':
line = line.split('.')
if line[0] not in genomes:
chrom_number = line[1].split(':')[0]
orientation = line[1].split(':')[1].split(' ')[1].strip('\n')
position = line[1].split(':')[1].split(' ')[0].split('-')[1]
chromosome = []
if orientation == '-':
chromosome.append([(marker-2*marker), int(position)])
elif orientation == '+':
chromosome.append([marker, int(position)])
genomes[line[0]] = {chrom_number : chromosome}
else:
chrom_number = line[1].split(':')[0]
orientation = line[1].split(':')[1].split(' ')[1].strip('\n')
position = line[1].split(':')[1].split(' ')[0].split('-')[1]
if orientation == '-':
if chrom_number in genomes[line[0]]:
genomes[line[0]][chrom_number].append([(marker-2*marker), int(position)])
else:
chromosome = []
chromosome.append([(marker - 2 * marker), int(position)])
genomes[line[0]][chrom_number] = chromosome
elif orientation == '+':
if chrom_number in genomes[line[0]]:
genomes[line[0]][chrom_number].append([marker, int(position)])
else:
chromosome = []
chromosome.append([marker, int(position)])
genomes[line[0]][chrom_number] = chromosome
result_genomes = []
for i in genomes:
genome = Genome()
genome.set_name(i)
for j in genomes[i]:
chromosome = Chromosome()
chrom_list = []
for block in genomes[i][j]:
chrom_list.append(block)
chrom_list = sorted(chrom_list, key=lambda x: x[1])
for block in chrom_list:
chromosome.append(block[0])
genome.append(chromosome)
result_genomes.append(genome)
return result_genomes
def sort_by_marker_position(input_list):
return input_list[1]
def write_genomes_with_grimm_by_name(dir_path, genomes, type):
"""
Write genomes in files. Each file have name according genome name.
Save in grimm format.
"""
for genome in genomes:
name_genome_file = os.path.join(dir_path, genome.get_name() + type)
with open(name_genome_file, 'w') as out:
out.write(">%s\n" % genome.get_name())
for chromosome in genome:
for gene in chromosome:
out.write(str(gene) + " ")
if chromosome.is_circular():
out.write(" @\n")
else:
out.write(" $\n")
def write_genomes_with_grimm_in_file(path_to_file, genomes):
"""
Write all genomes in file.
Save in grimm format.
"""
with open(path_to_file, 'w') as out:
for genome in genomes:
out.write(">%s\n" % genome.get_name())
for chromosome in genome:
for gene in chromosome:
out.write(str(gene) + " ")
if chromosome.is_circular():
out.write(" @\n")
else:
out.write(" $\n")
def write_genomes_with_grimm_plus_chr_in_file(path_to_file, genomes):
"""
Write all genomes in file.
Save in grimm format.
"""
with open(path_to_file, 'w') as out:
for genome in genomes:
n = 1
blocks_number = 0
for chromosome in genome:
blocks_number += chromosome.size()
out.write(">%s\t#%s\t#%s\n" % (genome.get_name(), blocks_number, genome.get_length()))
for chromosome in genome:
out.write("#%s\n" % n)
n += 1
for gene in chromosome:
out.write(str(gene) + " ")
if chromosome.is_circular():
out.write(" @\n")
else:
out.write(" $\n")
def write_genome_with_grimm_in_file(path_to_file, genome):
"""
Write genome in file in grimm format.
"""
with open(path_to_file, 'w') as out:
if len(genome.get_name()) != 0:
out.write(">%s\n" % genome.get_name())
for chromosome in genome:
for gene in chromosome:
out.write(str(gene) + " ")
if chromosome.is_circular():
out.write(" @\n")
else:
out.write(" $\n")
def write_genomes_with_cars_in_file(path_to_file, genomes):
"""
Write all genomes in file.
Save in InferCARs format.
No circular chromosomes for now
"""
with open(path_to_file, 'w') as out:
blocks = {}
for genome in genomes:
chrom_index = 1
for chromosome in genome:
i = 1
for block in chromosome:
if abs(block) not in blocks:
if int(block) < 0:
blocks[abs(block)] = [[genome.get_name(), chrom_index,
str(i) + '-' + str(i + 98), '-']]
else:
blocks[block] = [[genome.get_name(), chrom_index,
str(i) + '-' + str(i + 98), '+']]
else:
if int(block) < 0:
blocks[abs(block)].append([genome.get_name(), chrom_index,
str(i) + '-' + str(i + 98), '-'])
else:
blocks[block].append([genome.get_name(), chrom_index,
str(i) + '-' + str(i + 98), '+'])
i += 100
chrom_index += 1
number = 1
for block in blocks:
out.write(">%s\n" % str(number))
for element in blocks[block]:
out.write('%s.%s:%s %s\n' % (str(element[0]), str(element[1]),
str(element[2]), str(element[3])))
number += 1
out.write('\n')
<file_sep>import os
import utils.utils as utils
import utils.Genome as Genome
from parsers import Handler
import shutil
import graphs.BPG_from_grimm as BPGscript
import measures.Measures as Measures
class Procars_handler(Handler.Handler):
def __init__(self):
super(Procars_handler, self).__init__("Procars")
'''
Blocks file in Cars format, trees without labels, ancestors position marked with @ and
save tree with labels for future parsing.
'''
def save(self, dir_path):
procars_dir = os.path.join(dir_path, self.name_tool)
if not os.path.exists(procars_dir):
os.makedirs(procars_dir)
blocks_txt = os.path.join(procars_dir, self.input_blocks_file)
procars_tree_with_tag = os.path.join(procars_dir, "tree_tag.txt")
procars_tree_txt = os.path.join(procars_dir, "tree.txt")
tree_file_with_tag = os.path.join(dir_path, "tree.txt")
tree_file_without_tag = os.path.join(dir_path, "bad_tree.txt")
genomes = Handler.parse_genomes_in_grimm_file(os.path.join(dir_path, self.input_blocks_file))
Handler.write_genomes_with_cars_in_file(blocks_txt, genomes)
with open(tree_file_without_tag, 'r') as f:
tree_str = f.readline().replace(';', '@;')
with open(procars_tree_txt, 'w') as f:
f.write(tree_str)
shutil.copyfile(tree_file_with_tag, procars_tree_with_tag)
def parse(self, path):
path_dir = os.path.join(path, 'Procars', "result", 'ProCars_PQtree.txt')
genome = Handler.parse_genome_in_procars_file(path_dir)
return genome
def compare_dist_procars(self, dir_path):
distances = {}
genome = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for j in anc_genomes:
genomes_list = [genome, j]
distances[j.get_name()] = BPGscript.BreakpointGraph(). \
DCJ_distance(BPGscript.BreakpointGraph().BPG_from_genomes(genomes_list))
return distances[max(distances)]
def compare_acc_procars(self, dir_path):
accuracies = {}
genome = self.parse(dir_path)
anc_genomes = Handler.parse_genomes_in_grimm_file(dir_path + '/ancestral.txt')
for j in anc_genomes:
print(j.get_name())
accuracies[j.get_name()] = Measures.calculate_accuracy_measure(genome, j)
return accuracies[min(accuracies)]
<file_sep>import operator
from functools import partial
import Configure as conf
import parsers.SIMUL_handler as simul_handler
import measures.Measures as measures
import logging
logger = logging.getLogger()
def accumulation_tuple_func(first, second):
return tuple(map(operator.add, first, second))
def accumulation_float_func(first, second):
return first + second
def divide_tuple_func(first, count):
TP, FN, FP = first
return (float(TP) / count, float(FN) / count, float(FP) / count)
def divide_float_func(first, count):
return (first / count)
def init_tuple_list_func(size):
return [(0.0, 0.0, 0.0) for _ in range(size)]
def init_float_list_func(size):
return [0.0 for _ in range(size)]
def process_classical_directory(tools, measure_func, init_func, accumul_func, divide_func, dir_path):
simul_pars = simul_handler.SIMUL_handler()
simul_genomes = simul_pars.parse(dir_path)
different_genomes = [tool.parse(dir_path) for tool in tools]
count = 0
accamul = init_func(len(different_genomes))
for name, simul_genome in simul_genomes.iteritems():
logger.info("Work with genome " + name)
for i in range(len(different_genomes)):
#logger.info("Work with " + str(i) + " tool")
accamul[i] = accumul_func(accamul[i], measure_func(simul_genome, different_genomes[i].get(name)))
count += 1
for i in range(len(different_genomes)):
accamul[i] = divide_func(accamul[i], count)
return accamul
distance_func = partial(process_classical_directory, conf.tools, measures.calculate_distance_measure,
init_float_list_func, accumulation_float_func, divide_float_func)
gene_content_func = partial(process_classical_directory, conf.tools, measures.calculate_gene_content_measure,
init_tuple_list_func, accumulation_tuple_func, divide_tuple_func)
accuracy_func = partial(process_classical_directory, conf.tools, measures.calculate_accuracy_measure,
init_tuple_list_func, accumulation_tuple_func, divide_tuple_func)
|
c158e87acc10e20d00a2a7008e3022ed0ac9845a
|
[
"Markdown",
"Makefile",
"Python",
"R",
"C++",
"Shell"
] | 37
|
Python
|
AvdeevPavel/mgra_estimator
|
3f552e6e9cb48f1fd6d58f02aacb92262cbbb6f7
|
27c3e2949ee0d8d513fa8eeb742a68d6cf401e3a
|
refs/heads/master
|
<file_sep>## 1.0.2 (2019-10-30)
### Bug Fixes
* bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d9c8e3cd2cc174c50b1db8f31f5389820f))
* bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5c79aa56738839f03911d279ff48bbb354))
* **fix:** fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c3f9a08a2edd340d81ab008b0091124278))
* **fix:** fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73facfb44623afbb5168be8dd075499b54a))
* fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecbc4de6b0bef494585c860264daec81ebfb))
### Code Refactoring
* onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba87d0dbc7292486d34495773e8e33849aa))
### Features
* aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b8426db5968603009d6692bb332a30bace57))
* fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659bd8cba825726bcd2864d1310d2a060343))
* fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3a07642d70ca534d0d725294c55810d875))
* fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056007a3e4811ef23616434a0e16007fc592))
* fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/83059588055e714f900f8118cf92ae6b2e57f281))
* fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d28ff2fa3c95b0291bf86e67de179e4fb4c))
* ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd054e1266239e2008f8587c950da85d571))
* fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c8132953d2f9995759bb8a805cbe5a2df9d7424))
* 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d4c07166bed7d5f2270ec270c045e2b754))
* **1.0.1:** v1.0.1-01 ([2799d16](https://github.com/astonesh/vue-ts-demo/commit/2799d16bc8bd2cf7ab6fef0f82f4dad0b57fa94a))
* **v1.0.1:** v1.0.1 ([770df30](https://github.com/astonesh/vue-ts-demo/commit/770df309f4407ea77c52ea7b57ead6afa0d53287))
* 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb81580ccc8ea05b8a6e680282434a95b420ef))
### Performance Improvements
* change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535d4ad828568ef30d3f758da7c6890fed9f))
* ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f9249972398f8417d0f8c3fa71ac108c075647df))
* 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6e61c6026d0658b1038ac989762e96f780))
### BREAKING CHANGES
* nothing
fix123
* nothing
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([770df30](https://github.com/astonesh/vue-ts-demo/commit/770df30))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-00 ([638e7b0](https://github.com/astonesh/vue-ts-demo/commit/638e7b0))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([8322b74](https://github.com/astonesh/vue-ts-demo/commit/8322b74))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([8322b74](https://github.com/astonesh/vue-ts-demo/commit/8322b74))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-29)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
<file_sep>#!/bin/sh
#复制副本
# cp CHANGELOG.md CHANGElOG1.md
#生成新的changelog
# npm run changelog >> CHANGELOG2.md
#比较两个log 生成一个新的md
# aNum=`cat CHANGELOG.md | wc -l`
# bNum=`cat CHANGELOG1.md | wc -l`
# aCount=3
# bCount=3
# aStr='a'
# bStr='a'
# if [[ $bNum -ge $aNum ]];
# then
# echo "生成的CHANGELOG不对"
# else
# while(($aCount<=$aNum))
# do
# aStr=`sed -n ${aCount}p ./CHANGELOG.md`
# bStr=`sed -n ${bCount}p ./CHANGELOG1.md`
# echo $aStr
# echo $bStr
# echo `[[ $aStr = $bStr ]]`
# # echo $aCount
# # if [[ $aStr = $bStr ]]
# # then
# # echo $aCount
# # let aCount++
# # let bCount++
# # elif [[ -z $aStr ]]
# # then
# # let aCount++
# # elif [[ -z $bStr ]]
# # then
# # let Count++
# # else
# # echo $aStr >> b.MD
# let aCount++
# # fi
# done
# fi
# a=`sed -n ${aCount}p CHANGELOG.md`
# echo $a
# echo `cat CHANGELOG1.md | wc -l`
# FS=$(ls ./build)
# echo ${FS}
# for skill in ${FS}; do
# echo "I am good at ${skill}Script"
# done
# echo $0
# echo $1
# while read line
# do
# echo $line
# done < CHANGELOG.MD
# npm run changelog >> a.MD
# a=0
# b='1'
# while read line
# do
# # echo $line
# if [[ $a -eq 0 ]]
# then
# b=$line
# let a++
# else
# break
# fi
# done < CHANGELOG.MD
# echo $b
# while read line2
# do
# c=$line2
# echo $c
# if test "$b" != "$c"
# then
# "$c" >> b.MD
# else
# break
# fi
# done < a.MD<file_sep>## 1.0.2 (2019-10-30)
### Bug Fixes
* bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d9c8e3cd2cc174c50b1db8f31f5389820f))
* bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5c79aa56738839f03911d279ff48bbb354))
* **fix:** fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c3f9a08a2edd340d81ab008b0091124278))
* **fix:** fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73facfb44623afbb5168be8dd075499b54a))
* fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecbc4de6b0bef494585c860264daec81ebfb))
### Code Refactoring
* onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba87d0dbc7292486d34495773e8e33849aa))
### Features
* aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b8426db5968603009d6692bb332a30bace57))
* fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659bd8cba825726bcd2864d1310d2a060343))
* fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3a07642d70ca534d0d725294c55810d875))
* fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056007a3e4811ef23616434a0e16007fc592))
* fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/83059588055e714f900f8118cf92ae6b2e57f281))
* fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d28ff2fa3c95b0291bf86e67de179e4fb4c))
* ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd054e1266239e2008f8587c950da85d571))
* fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c8132953d2f9995759bb8a805cbe5a2df9d7424))
* 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d4c07166bed7d5f2270ec270c045e2b754))
* **1.0.1:** v1.0.1-01 ([2799d16](https://github.com/astonesh/vue-ts-demo/commit/2799d16bc8bd2cf7ab6fef0f82f4dad0b57fa94a))
* **v1.0.1:** v1.0.1 ([770df30](https://github.com/astonesh/vue-ts-demo/commit/770df309f4407ea77c52ea7b57ead6afa0d53287))
* 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb81580ccc8ea05b8a6e680282434a95b420ef))
### Performance Improvements
* change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535d4ad828568ef30d3f758da7c6890fed9f))
* ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f9249972398f8417d0f8c3fa71ac108c075647df))
* 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6e61c6026d0658b1038ac989762e96f780))
### BREAKING CHANGES
* nothing
fix123
* nothing
<file_sep>## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([770df30](https://github.com/astonesh/vue-ts-demo/commit/770df30))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-00 ([638e7b0](https://github.com/astonesh/vue-ts-demo/commit/638e7b0))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([8322b74](https://github.com/astonesh/vue-ts-demo/commit/8322b74))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* feat(v1.0.1): v1.0.1 ([8322b74](https://github.com/astonesh/vue-ts-demo/commit/8322b74))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-30)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
* feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
* feat: fe-10-29-01 ([ac8b056](https://github.com/astonesh/vue-ts-demo/commit/ac8b056))
* feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
* feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
* feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
* feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
* feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
* feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
* fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
* fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
* fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
* fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
* fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
* refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
* refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
* docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
* docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
* style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
* improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
* perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
* perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
* perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
* chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
* test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
* [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
* fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
* for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
* Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
* one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
* one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
### BREAKING CHANGE
* nothing
* nothing
fix123
## <small>1.0.2 (2019-10-29)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
* feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
<file_sep>
> vue-ts-demo01@1.0.2 changelog D:\codePro\pratice\vue-ts-demo
> conventional-changelog -p angular -i CHANGELOG.md -r -u
## 1.0.2 (2019-10-29)
### Bug Fixes
* bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d9c8e3cd2cc174c50b1db8f31f5389820f))
* bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5c79aa56738839f03911d279ff48bbb354))
* **fix:** fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c3f9a08a2edd340d81ab008b0091124278))
* **fix:** fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73facfb44623afbb5168be8dd075499b54a))
* fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecbc4de6b0bef494585c860264daec81ebfb))
## <small>1.0.2 (2019-10-29)</small>
* feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
<file_sep>a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: aaa ([9415b84](https://github.com/astonesh/vue-ts-demo/commit/9415b84))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: fe-01 ([6dc0659](https://github.com/astonesh/vue-ts-demo/commit/6dc0659))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: fe-02 ([9e4aef3](https://github.com/astonesh/vue-ts-demo/commit/9e4aef3))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: fe-1029 ([8305958](https://github.com/astonesh/vue-ts-demo/commit/8305958))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: fea-003 ([401c2d2](https://github.com/astonesh/vue-ts-demo/commit/401c2d2))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: ff ([c94dafd](https://github.com/astonesh/vue-ts-demo/commit/c94dafd))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: fre-005 ([5c81329](https://github.com/astonesh/vue-ts-demo/commit/5c81329))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: 增加一个功能 ([97f555d](https://github.com/astonesh/vue-ts-demo/commit/97f555d))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh feat: 曾江了两个功能 ([89cb815](https://github.com/astonesh/vue-ts-demo/commit/89cb815))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fix: bug 1024 ([f814f0d](https://github.com/astonesh/vue-ts-demo/commit/f814f0d))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fix: bugfix ([6abf3f5](https://github.com/astonesh/vue-ts-demo/commit/6abf3f5))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fix: fix0000 ([c644ecb](https://github.com/astonesh/vue-ts-demo/commit/c644ecb))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fix(fix): fix 20489 ([b46e79c](https://github.com/astonesh/vue-ts-demo/commit/b46e79c))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fix(fix): fix2056 ([43c8b73](https://github.com/astonesh/vue-ts-demo/commit/43c8b73))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh refactor: dd ([59cb157](https://github.com/astonesh/vue-ts-demo/commit/59cb157))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh refactor: onething ([84b9cba](https://github.com/astonesh/vue-ts-demo/commit/84b9cba))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh docs: change changelog ([ec258dc](https://github.com/astonesh/vue-ts-demo/commit/ec258dc))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh docs: change log ([e950267](https://github.com/astonesh/vue-ts-demo/commit/e950267))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh style: change doc ([618980f](https://github.com/astonesh/vue-ts-demo/commit/618980f))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh improvement: try ([498509c](https://github.com/astonesh/vue-ts-demo/commit/498509c))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh perf: change component ([92ae535](https://github.com/astonesh/vue-ts-demo/commit/92ae535))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh perf: ggg ([f924997](https://github.com/astonesh/vue-ts-demo/commit/f924997))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh perf: 改进性能 ([d2ab5e6](https://github.com/astonesh/vue-ts-demo/commit/d2ab5e6))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh chore: cc ([81fde14](https://github.com/astonesh/vue-ts-demo/commit/81fde14))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh test: bb ([d2301d3](https://github.com/astonesh/vue-ts-demo/commit/d2301d3))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh [done:first commit] ([e9f09fd](https://github.com/astonesh/vue-ts-demo/commit/e9f09fd))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh fiv ([19af857](https://github.com/astonesh/vue-ts-demo/commit/19af857))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh for ([b48ac3e](https://github.com/astonesh/vue-ts-demo/commit/b48ac3e))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh Initial commit ([ac719d4](https://github.com/astonesh/vue-ts-demo/commit/ac719d4))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh one ([cf67996](https://github.com/astonesh/vue-ts-demo/commit/cf67996))
a.MD b.MD build CHANGELOG.md CHANGElOG1.md config index.html node_modules package.json package-lock.json README.md src static test try.sh one ([9fda10d](https://github.com/astonesh/vue-ts-demo/commit/9fda10d))
|
b6f60a76ae45170fd6aeb2f70ecbd87d303f3161
|
[
"Markdown",
"Shell"
] | 6
|
Markdown
|
astonesh/vue-ts-demo
|
9181cc4a8fb6f753e17631db80950c0285576b5f
|
ccfc8eca3197e785b629e71c9a2ab1afe25efbe3
|
refs/heads/master
|
<file_sep>package errors
import (
"massliking/backend/logger"
)
var INSTABOT_REQUEST_ERROR = BaseError{1010, "Request to instagram failed", ""}
var INSTABOT_LOGIN_ERROR = BaseError{1020, "Instagram login failed", ""}
var INSTABOT_BODY_PARSE_ERROR = BaseError{1030, "Error parse instagram response", ""}
var INSTABOT_FOLLOWERS_ERROR = BaseError{1040, "Error fetch followers list", ""}
var INSTABOT_SUSPECTED_ERROR = BaseError{1050, "Instagram account is suspected", ""}
var MODEL_INSTAGRAM_NOT_FOUND = BaseError{2010, "Instagram not found", ""}
var MODEL_INSTAGRAM_COLLECTION_NOT_FOUND = BaseError{2020, "Instagram collection not found", ""}
var MODEL_INSTAGRAM_NOT_CREATED = BaseError{2030, "Instagram not created", ""}
var MODEL_INSTAGRAM_NOT_UPDATED = BaseError{2040, "Instagram not updated", ""}
var MODEL_INSTAGRAM_NOT_DELETED = BaseError{2050, "Instagram not deleted", ""}
var MODEL_INSTAGRAM_UNDEFINED_ACTION = BaseError{2060, "Undefined action type", ""}
var MODEL_INSTAGRAM_LOGIN_ERROR = BaseError{2070, "Instagram login failed", ""}
var MODEL_INSTAGRAM_INFO_ERROR = BaseError{2080, "Instagram info fetching failed", ""}
var MODEL_INSTAGRAM_INACTIVE_ERROR = BaseError{2090, "Instagram account is inactive", ""}
var MODEL_USER_NOT_FOUND = BaseError{3010, "User not found", ""}
var MODEL_USER_NOT_CREATED = BaseError{3030, "User not created", ""}
var MODEL_CHANNEL_UNDEFINED_ACTION = BaseError{4010, "Undefined action type", ""}
var MODEL_CHANNEL_ACTION_ERROR = BaseError{4020, "Error during channel action execution", ""}
var MODEL_CHANNEL_UNDEFINED_TARGET = BaseError{4030, "Undefined target type", ""}
var MODEL_CHANNEL_TARGET_ERROR = BaseError{4040, "Error during channel queue filling", ""}
var MODEL_CHANNEL_NOT_FOUND = BaseError{4050, "Channel not found", ""}
var MODEL_CHANNEL_COLLECTION_NOT_FOUND = BaseError{4060, "Channel collection not found", ""}
var MODEL_CHANNEL_NOT_CREATED = BaseError{4070, "Channel not created", ""}
var MODEL_CHANNEL_NOT_UPDATED = BaseError{4080, "Channel not updated", ""}
var MODEL_CHANNEL_NOT_DELETED = BaseError{4090, "Channel not deleted", ""}
var MODEL_CHANNEL_ACTION_EMPTY = BaseError{4100, "Empty action", ""}
var UNKNOWN_ERROR = BaseError{9999, "Unknown error", ""}
type BaseError struct {
Code int `json:"code"`
Message string `json:"message"`
Payload string `json:"payload"`
}
func (e BaseError) Error() string {
return e.Message
}
func On(err error, berr BaseError) error {
if err != nil {
logger.Error.Println(err)
return berr
} else {
return nil
}
}
<file_sep>#!/bin/bash
ansible-playbook -i default.inventory -D rollout.yml --vault-password-file ~/.vault_pass.txt
<file_sep>package instabot
type UserInfo struct {
IsBusiness bool `json:"is_business"`
ProfilePicURL string `json:"profile_pic_url"`
HdProfilePicURLInfo struct {
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"hd_profile_pic_url_info"`
UsertagsCount int `json:"usertags_count"`
ExternalLynxURL string `json:"external_lynx_url"`
FollowingCount int `json:"following_count"`
HasAnonymousProfilePicture bool `json:"has_anonymous_profile_picture"`
GeoMediaCount int `json:"geo_media_count"`
ExternalURL string `json:"external_url"`
Username string `json:"username"`
Biography string `json:"biography"`
HasChaining bool `json:"has_chaining"`
FullName string `json:"full_name"`
IsPrivate bool `json:"is_private"`
PK int `json:"pk"`
FollowerCount int `json:"follower_count"`
ProfilePicID string `json:"profile_pic_id"`
IsVerified bool `json:"is_verified"`
HdProfilePicVersions []struct {
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"hd_profile_pic_versions"`
MediaCount int `json:"media_count"`
IsFavorite bool `json:"is_favorite"`
}
type User struct {
PK int `json:"pk"`
Username string `json:"username"`
FullName string `json:"full_name"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
ProfilePicURL string `json:"profile_pic_url"`
ProfilePicID string `json:"profile_pic_id,omitempty"`
HasAnonymousProfilePicture bool `json:"has_anonymous_profile_picture"`
IsFavorite bool `json:"is_favorite"`
IsUnpublished bool `json:"is_unpublished"`
FriendshipStatus *FriendshipStatus `json:"friendship_status"`
}
type FriendshipStatus struct {
IncomingRequest bool `json:"incoming_request"`
IsPrivate bool `json:"is_private"`
Following bool `json:"following"`
OutgoingRequest bool `json:"outgoing_request"`
FollowedBy bool `json:"followed_by"`
Blocking bool `json:"blocking"`
}
type LoggedInUser struct {
AllowContactsSync bool `json:"allow_contacts_sync"`
FullName string `json:"full_name"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
ProfilePic string `json:"profile_pic"`
Username string `json:"username"`
AnonProfilePic bool `json:"has_anonymous_profile_picture"`
PK int `json:"pk"`
}
type Item struct {
TakenAt int `json:"taken_at"`
PK int `json:"pk"`
ID string `json:"id"`
DeviceTimestamp int `json:"device_timestamp"`
MediaType int `json:"media_type"`
Code string `json:"code"`
ClientCacheKey string `json:"client_cache_key"`
FilterType int `json:"filter_type"`
ImageVersions2 struct {
Candidates []struct {
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"candidates"`
} `json:"image_versions2"`
OriginalWidth int `json:"original_width"`
OriginalHeight int `json:"original_height"`
User *User `json:"user"`
OrganicTrackingToken string `json:"organic_tracking_token"`
LikeCount int `json:"like_count"`
TopLikers []interface{} `json:"top_likers"`
HasLiked bool `json:"has_liked"`
CommentLikesEnabled bool `json:"comment_likes_enabled"`
HasMoreComments bool `json:"has_more_comments"`
MaxNumVisiblePreviewComments int `json:"max_num_visible_preview_comments"`
PreviewComments []interface{} `json:"preview_comments"`
Comments []interface{} `json:"comments"`
CommentCount int `json:"comment_count"`
Caption struct {
Pk int64 `json:"pk"`
UserID int `json:"user_id"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt int `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
ContentType string `json:"content_type"`
Status string `json:"status"`
BitFlags int `json:"bit_flags"`
User *User `json:"user"`
MediaID int64 `json:"media_id"`
} `json:"caption"`
CaptionIsEdited bool `json:"caption_is_edited"`
PhotoOfYou bool `json:"photo_of_you"`
NextMaxID int64 `json:"next_max_id,omitempty"`
Location struct {
Pk int `json:"pk"`
Name string `json:"name"`
Address string `json:"address"`
City string `json:"city"`
Lng float64 `json:"lng"`
Lat float64 `json:"lat"`
ExternalSource string `json:"external_source"`
FacebookPlacesID int64 `json:"facebook_places_id"`
} `json:"location,omitempty"`
Lat float64 `json:"lat,omitempty"`
Lng float64 `json:"lng,omitempty"`
ViewCount float64 `json:"view_count,omitempty"`
VideoVersions []struct {
Type int `json:"type"`
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"video_versions,omitempty"`
HasAudio bool `json:"has_audio,omitempty"`
VideoDuration float64 `json:"video_duration,omitempty"`
}
type HashtagItem struct {
TakenAt int `json:"taken_at"`
PK int `json:"pk"`
ID string `json:"id"`
DeviceTimestamp int `json:"device_timestamp"`
MediaType int `json:"media_type"`
Code string `json:"code"`
ClientCacheKey string `json:"client_cache_key"`
FilterType int `json:"filter_type"`
ImageVersions2 struct {
Candidates []struct {
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"candidates"`
} `json:"image_versions2"`
OriginalWidth int `json:"original_width"`
OriginalHeight int `json:"original_height"`
User *User `json:"user"`
OrganicTrackingToken string `json:"organic_tracking_token"`
LikeCount int `json:"like_count"`
HasLiked bool `json:"has_liked"`
CommentLikesEnabled bool `json:"comment_likes_enabled"`
HasMoreComments bool `json:"has_more_comments"`
MaxNumVisiblePreviewComments int `json:"max_num_visible_preview_comments"`
PreviewComments []interface{} `json:"preview_comments"`
Comments []interface{} `json:"comments"`
CommentCount int `json:"comment_count"`
Caption struct {
Pk int64 `json:"pk"`
UserID int64 `json:"user_id"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt int `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
ContentType string `json:"content_type"`
Status string `json:"status"`
BitFlags int `json:"bit_flags"`
User *User `json:"user"`
MediaID int64 `json:"media_id"`
} `json:"caption"`
CaptionIsEdited bool `json:"caption_is_edited"`
PhotoOfYou bool `json:"photo_of_you"`
NextMaxID int64 `json:"next_max_id,omitempty"`
Usertags struct {
In []interface{} `json:"in"`
} `json:"usertags,omitempty"`
}
<file_sep>var
shell = require('shelljs'),
path = require('path')
env = require('./env-utils'),
config = require('../config')
config_env = env.prod ? config.build.env : config.dev.env
shell.rm('-rf', path.resolve(__dirname, '../../' + config_env.BUILD_DIR + '/static'))
console.log(' Cleaned build artifacts.\n')
<file_sep>import Vue from 'vue'
import VueI18n from 'vue-i18n'
const locales = {
en: {
yes: 'Yes',
no: 'No',
dashboard: {
titles: {
greeting: 'Hi',
accounts: 'Accounts',
security: 'Security',
billing: 'Billing',
contacts: 'Contacts'
}
},
instagram: {
buttons: {
show: 'Show account info',
list: 'Accounts list',
edit: 'Edit account',
create: 'Create account',
delete: 'Delete account',
add: 'Add new account',
start: 'Start instagram',
stop: 'Stop instagram'
},
toasts: {
deleting: 'Deleting account',
start: 'Start instagram',
stop: 'Stop instagram',
inactive: 'Warning: There is impossible any account changes in the current state.'
},
titles: {
create: 'New instagram account',
edit: 'Edit instagram account'
},
fields: {
username: 'Username',
password: '<PASSWORD>',
hours: 'Activity hours (UTC)',
like_speed: 'Like speed',
comment_speed: 'Comment speed',
follow_speed: 'Follow speed',
unfollow_speed: 'Unfollow speed',
trusted: 'Trusted account',
media_count: 'Media count',
followers_count: 'Followers count',
following_count: 'Following count',
state: 'State',
channels_count: 'Channels count'
},
errors: {
username: {
required: 'Username is required.'
},
password: {
required: '<PASSWORD>.'
}
}
},
channel: {
buttons: {
add: 'Add new channel',
edit: 'Edit channel',
create: 'Create channel',
delete: 'Delete channel',
back_to_account: 'Back to account',
start: 'Start channel',
stop: 'Stop channel'
},
toasts: {
deleting: 'Deleting channel',
start: 'Start channel',
stop: 'Stop channel'
},
titles: {
create: 'New channel',
edit: 'Edit channel'
},
fields: {
value: 'Channel value',
target: 'Target',
action: 'Action',
state: 'State',
conversion: 'Conversion',
actions_count: 'Actions count',
queue: 'Queue',
comments: 'Comments'
},
errors: {
value: {
required: 'Channel value is required.'
},
target: {
required: 'Target value is required.'
},
action: {
required: 'Action value is required.'
}
}
},
common: {
buttons: {
login: 'Log In',
signup: 'Sign Up',
logout: 'Log Out'
},
titles: {
login: 'Log In',
signup: 'Sign Up',
header: 'MassLiking',
footer: 'MassLiking © 2017'
},
fields: {
email: 'Email',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
},
errors: {
fields: {
invalid: 'Please review fields again.'
},
credentials: {
invalid: 'Incorrect Username and/or Password.',
exists: 'User with this credentials already exists.'
},
email: {
required: 'Email is required.',
invalid: 'Email is invalid.'
},
password: {
required: 'Password is required.',
length: 'Password must have at least 6 letters.'
},
password_confirmation: {
mismatch: 'Passwords must be identical.'
}
}
},
landing: {
title: 'Get social media superpowers',
motto: 'Accelerate your life on Instagram for more targeted likes, comments and follows',
submit: 'Get 3 free days',
features: [
{
title: 'No downloads',
content: 'You can use MassLiking straight from the web on all browsers. You don\'t need to download or install anything to enjoy our service, which is why MassLiking is the safest Instagram bot available.'
},
{
title: 'Automate everything',
content: 'You can easily automate your liking, commenting and following activities based on specific hashtags and geolocations, as well as unfollow users from different sources.'
},
{
title: 'Start and close',
content: 'MassLiking conveniently works on our servers, which means you can feel free to logout, change accounts, or even close your browser window after you start your MassLiking activity.'
},
{
title: '3 day free trial',
content: 'We\'re confident that you\'ll love our service. Try MassLiking free for 3 days and you\'ll see why Instagrammers continue to use our service.'
},
{
title: 'Full control',
content: 'We provide tons of filters and customization options to help you increase your Instagram followers, likes and comments for the target audiences that make sense for you.'
},
{
title: 'Safe to use',
content: 'Our one of a kind service will automatically reduce its speed to ensure that your account is safe from hitting Instagram limits and we offer multiple speed settings for more advanced users.'
}
]
}
}
}
Vue.use(VueI18n)
Vue.config.lang = 'en'
Object.keys(locales).forEach(function (lang) {
Vue.locale(lang, locales[lang])
})
<file_sep>package workers
import (
"time"
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
const STATS_RELOAD_TIME = 15 * 60
const RELOGIN_TIME = 3 * 60 * 60
func StatsPoolWorker(client *instabot.Client, i *models.Instagram, pool *models.WorkersPool) {
logInfo, _, _ := logger.TaggedLoggers("workers/stats", "StatsPoolWorker", i.IdString())
logInfo("Start worker")
for true {
logInfo("Check commands")
select {
case command := <-pool.StatsCommandCh:
if command == WORKER_COMMAND_STOP {
logInfo("Command stop received")
return
}
case <-time.After(time.Second * time.Duration(STATS_RELOAD_TIME)):
UpdateStats(client, i, pool)
}
}
}
func UpdateStats(client *instabot.Client, i *models.Instagram, pool *models.WorkersPool) {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/stats", "UpdateStats", i.IdString())
logInfo("Validate account state")
err = i.ValidateState(client)
if err != nil {
logError("Validate account state", err)
return
}
if time.Since(client.LoggedAt) >= time.Second*time.Duration(RELOGIN_TIME) {
logInfo("Relogin account to update session")
client, err = instabot.Login(i.Username, i.Password)
if err != nil {
logError("Relogin account to update session", err)
return
}
}
logInfo("Update account info")
err = i.UpdateInfo(client)
if err != nil {
logError("Update account info", err)
}
logInfo("Fetch account channels")
channels, err := i.FindChannels()
if err != nil {
logError("Fetch account channels", err)
}
if len(channels) > 0 {
logInfo("Fetch account followers")
followers, err := client.GetTotalUserFollowers(i.Info.PK)
if err != nil {
logError("Fetch account followers", err)
}
// Compare leads and followers
for _, c := range channels {
counter := 0
for _, l := range c.Queue.Leads {
if followers[l] == true {
counter += 1
}
}
// ...and save the result
err = c.Save(func(c *models.Channel) {
c.FollowersCount = counter
})
if err != nil {
logError("Channel not updated", err)
}
}
}
}
<file_sep>package main
import (
"net/http"
"github.com/gin-gonic/gin"
"massliking/backend/auth"
"massliking/backend/config"
. "massliking/backend/handlers"
)
func InitRoutes(engine *gin.Engine) {
engine.LoadHTMLGlob("./static/*.html")
// NGINX serve static for production
if config.IsDevelop() {
engine.Static("/js", "./static/js")
engine.Static("/statics", "./static/statics")
engine.Static("/css", "./static/css")
engine.Static("/fonts", "./static/fonts")
}
engine.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
})
v1 := engine.Group("/api/v1")
{
v1.POST("/login", auth.JWT.LoginHandler)
v1.POST("/signup", SignupHandler)
user := v1.Group("/user")
user.Use(auth.JWT.MiddlewareFunc())
{
user.GET("", GetUserHandler)
user.GET("/refresh_token", auth.JWT.RefreshHandler)
}
instagram := v1.Group("/instagrams")
instagram.Use(auth.JWT.MiddlewareFunc())
{
instagram.POST("", CreateInstagramHandler)
instagram.GET("", FindInstagramsHandler)
instagram.GET("/:instagram_id", GetInstagramHandler)
instagram.GET("/:instagram_id/stop", StopInstagramHandler)
instagram.GET("/:instagram_id/start", StartInstagramHandler)
instagram.PUT("/:instagram_id", UpdateInstagramHandler)
instagram.DELETE("/:instagram_id", DeleteInstagramHandler)
}
channel := v1.Group("/instagram/:instagram_id/channels")
channel.Use(auth.JWT.MiddlewareFunc())
{
channel.POST("", CreateChannelHandler)
channel.GET("", FindChannelsHandler)
channel.GET("/:channel_id", GetChannelHandler)
channel.GET("/:channel_id/stop", StopChannelHandler)
channel.GET("/:channel_id/start", StartChannelHandler)
channel.PUT("/:channel_id", UpdateChannelHandler)
channel.DELETE("/:channel_id", DeleteChannelHandler)
}
}
engine.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
})
}
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import auth from './api/auth'
Vue.use(VueRouter)
const requireAuth = (to, _from, next) => {
if (!auth.checkAuth()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
else {
next()
}
}
const afterAuth = (_to, from, next) => {
if (auth.checkAuth()) {
next(from.path)
}
else {
next()
}
}
const authToDashboard = (_to, from, next) => {
if (auth.checkAuth()) {
next('/instagram')
}
else {
next()
}
}
function load (component) {
return () => System.import(`components/${component}.vue`)
}
function loadFrom (from, component) {
return () => System.import(`components/${from}/${component}.vue`)
}
export default new VueRouter({
mode: 'history',
routes: [
{ path: '/',
component: loadFrom('Layout', 'Landing'),
children: [
{ path: '', component: load('Landing'), beforeEnter: authToDashboard },
{ path: 'login', component: load('Login'), beforeEnter: afterAuth },
{ path: 'signup', component: load('Signup'), beforeEnter: afterAuth }
]
},
{ path: '/instagram',
component: loadFrom('Layout', 'Dashboard'),
beforeEnter: requireAuth,
children: [
{ path: '', name: 'instagram-list', component: loadFrom('Instagram', 'List') },
{ path: '/instagram/new', name: 'instagram-new', component: loadFrom('Instagram', 'Form') },
{ path: '/instagram/:instagram_id/edit', name: 'instagram-edit', component: loadFrom('Instagram', 'Edit') },
{ path: '/instagram/:instagram_id', name: 'instagram-show', component: loadFrom('Instagram', 'Show') },
{ path: '/instagram/:instagram_id/channel/new', name: 'channel-new', component: loadFrom('Channel', 'Form') },
{ path: '/instagram/:instagram_id/channel/:id/edit', name: 'channel-edit', component: loadFrom('Channel', 'Edit') },
{ path: '/instagram/:instagram_id/channel/:id', name: 'channel-show', component: loadFrom('Channel', 'Show') }
]
},
{ path: '*', component: load('Error404') }
]
})
<file_sep>#!/bin/bash
TARGET=targets/develop
cd $TARGET && APP_ENV=development GOMAXPROCS=2 ./massliking
<file_sep>package workers
import (
"math/rand"
"time"
. "massliking/backend/errors"
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
func RunAction(i *models.Instagram, c *models.Channel, client *instabot.Client) error {
var err error
logInfo, logWarn, logError := logger.TaggedLoggers("workers/actions_collection", "RunAction", i.IdString(), c.IdString())
logInfo("Checking channel queue size...")
if len(c.Queue.Targets) == 0 {
logWarn("Channel queue is empty")
return MODEL_CHANNEL_ACTION_ERROR
}
logInfo("Checking channel schedule...")
hour := time.Now().UTC().Hour()
if hour < i.Hours.Min || hour > i.Hours.Max {
logWarn("Channel out of schedule")
return MODEL_CHANNEL_ACTION_ERROR
}
logInfo("Checking channel limits...")
if !i.CheckLimits(c.Action) {
logWarn("Channel limits exceeded")
return MODEL_CHANNEL_ACTION_ERROR
}
logInfo("Running target action")
pk := c.Queue.Targets[0]
switch c.Action {
case "like":
err = RunActionLike(c, client, pk)
case "comment":
err = RunActionComment(c, client, pk)
case "follow":
err = RunActionFollow(c, client, pk)
case "unfollow":
err = RunActionUnfollow(c, client, pk)
default:
err = MODEL_CHANNEL_UNDEFINED_ACTION
}
if err != nil {
logError("Running target action", err)
logInfo("Skipping current target and move forward")
err = c.Save(func(c *models.Channel) {
c.Queue.Targets = c.Queue.Targets[1:]
})
if err != nil {
logError("Skipping current target and move forward", err)
return MODEL_CHANNEL_ACTION_ERROR
}
}
logInfo("Updating channel limits...")
err = i.UpdateLimits(c.Action)
if err != nil {
logError("Updating channel limits...", err)
return MODEL_CHANNEL_ACTION_ERROR
}
logInfo("Updating channel queue...")
err = c.Save(func(c *models.Channel) {
c.Queue.Targets = c.Queue.Targets[1:]
c.Queue.Leads = append(c.Queue.Leads, pk)
})
if err != nil {
logError("Updating channel queue...", err)
return MODEL_CHANNEL_ACTION_ERROR
}
logInfo(">>> Action completed successfully <<<")
return nil
}
func RunActionLike(c *models.Channel, client *instabot.Client, pk int) error {
var err error
// Looking for posts of the last year
t := time.Now().AddDate(-1, 0, 0).Unix()
feed, err := client.GetUserFeed(pk, "", t)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if len(feed.Items) == 0 {
return MODEL_CHANNEL_ACTION_EMPTY
}
mediaId := feed.Items[0].PK
like, err := client.Like(mediaId)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if like.Status != "ok" {
return MODEL_CHANNEL_ACTION_ERROR
}
return nil
}
func RunActionComment(c *models.Channel, client *instabot.Client, pk int) error {
var err error
if len(c.Comments) == 0 {
return MODEL_CHANNEL_ACTION_EMPTY
}
// Looking for posts of the last year
t := time.Now().AddDate(-1, 0, 0).Unix()
feed, err := client.GetUserFeed(pk, "", t)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if len(feed.Items) == 0 {
return MODEL_CHANNEL_ACTION_EMPTY
}
// Fetch the last post and random comment
mediaId := feed.Items[0].PK
text := c.Comments[rand.Intn(len(c.Comments))]
comment, err := client.Comment(mediaId, text)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if comment.Status != "ok" {
return MODEL_CHANNEL_ACTION_ERROR
}
return nil
}
func RunActionFollow(c *models.Channel, client *instabot.Client, pk int) error {
var err error
follow, err := client.Follow(pk)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if follow.Status != "ok" {
return MODEL_CHANNEL_ACTION_ERROR
}
return nil
}
func RunActionUnfollow(c *models.Channel, client *instabot.Client, pk int) error {
var err error
unfollow, err := client.Unfollow(pk)
if err != nil {
return On(err, MODEL_CHANNEL_ACTION_ERROR)
}
if unfollow.Status != "ok" {
return MODEL_CHANNEL_ACTION_ERROR
}
return nil
}
<file_sep>package workers
import (
"time"
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
const ACCOUNT_CHECK_TIME = 15 * 60
func InstagramPoolWorker(client *instabot.Client, i *models.Instagram, pool *models.WorkersPool) {
var err error
var writeOp *models.InstagramWriteOp
logInfo, _, logError := logger.TaggedLoggers("workers/instagram", "InstagramPoolWorker", i.IdString())
logInfo("Start worker")
for {
select {
case writeOp = <-pool.WriteOpCh:
err = writeOp.Instagram.SyncSave(writeOp.Callback)
writeOp.ReadChannel <- &models.InstagramReadOp{Error: err}
case command := <-pool.InstagramCommandCh:
if command == WORKER_COMMAND_STOP {
logInfo("Command stop received")
return
}
case <-time.After(time.Second * time.Duration(ACCOUNT_CHECK_TIME)):
logInfo("Validate account state")
err = i.ValidateState(client)
if err != nil {
logError("Validate account state", err)
return
}
}
}
}
<file_sep>#!/bin/bash
export APP_ENV=development
export NODE_ENV=development
export GOARCH=amd64
export GOOS=linux
TARGET=targets/develop
rm -rf ./targets;
mkdir -p ./targets;
mkdir -p ./$TARGET;
mkdir -p ./$TARGET/static;
mkdir -p ./$TARGET/config;
mkdir -p ./$TARGET/log;
mkdir -p ./$TARGET/pids;
cp -r ./config/dev.env.js ./frontend/config/;
cp -r ./config/development.yml ./$TARGET/config/;
cd ./frontend && npm run build && cd ../;
cd ./backend && go build -o ../$TARGET/massliking *go && cd ../;
<file_sep>package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func GetUserHandler(c *gin.Context) {
user, err := getUser(c)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, user)
}
<file_sep>#!/bin/bash
ansible-playbook -i default.inventory -D deploy.yml --vault-password-file ~/.vault_pass.txt
<file_sep>package models
import (
"time"
"gopkg.in/hlandau/passlib.v1"
. "massliking/backend/errors"
)
type User struct {
Id int64 `json:"id" xorm:"pk autoincr index"`
Username string `json:"username" xorm:"notnull index unique"`
Password string `json:"-" xorm:"varchar(200) notnull"`
CreatedAt time.Time `json:"created_at" xorm:"created"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated"`
}
func (u *User) Verify(password string) bool {
_, err := passlib.Verify(password, u.Password)
if err != nil {
return false
}
return true
}
func CreateUser(c *Credentials) (*User, error) {
user := &User{}
hash, err := passlib.Hash(c.Password)
if err != nil {
return user, On(err, MODEL_USER_NOT_CREATED)
}
user.Username = c.Username
user.Password = <PASSWORD>
_, err = Engine.Insert(user)
return user, On(err, MODEL_USER_NOT_CREATED)
}
func GetUser(username string) (*User, error) {
user := &User{}
_, err := Engine.
Where("username = ?", username).
Get(user)
return user, On(err, MODEL_USER_NOT_FOUND)
}
<file_sep>package models
import (
"time"
. "massliking/backend/errors"
)
func CreateInstagram(user *User, c *InstagramCredentials) (*Instagram, error) {
var err error
instagram := &Instagram{}
instagram.UserId = user.Id
instagram.Username = c.Username
instagram.Password = <PASSWORD>
instagram.Trusted = c.Trusted
instagram.State = INSTAGRAM_STATE_STOP
instagram.Hours = &Hours{
Max: c.Hours.Max,
Min: c.Hours.Min,
}
instagram.Counters = &Counters{
Like: 0,
Comment: 0,
Follow: 0,
Unfollow: 0,
StartedAt: time.Now(),
}
instagram.Speed = &Speed{
Like: c.Speed.Like,
Comment: c.Speed.Comment,
Follow: c.Speed.Follow,
Unfollow: c.Speed.Unfollow,
}
_, err = Engine.Insert(instagram)
return instagram, On(err, MODEL_INSTAGRAM_NOT_CREATED)
}
func GetInstagram(user *User, id int64) (*Instagram, error) {
var err error
instagram := &Instagram{}
has, err := Engine.
Id(id).
And("user_id = ?", user.Id).
Get(instagram)
if err != nil || has != true {
return instagram, MODEL_INSTAGRAM_NOT_FOUND
}
return instagram, nil
}
func FindInstagrams(user *User) ([]*Instagram, error) {
var err error
instagrams := []*Instagram{}
err = Engine.
Where("user_id = ?", user.Id).
Find(&instagrams)
return instagrams, On(err, MODEL_INSTAGRAM_COLLECTION_NOT_FOUND)
}
func FindAllInstagrams() ([]*Instagram, error) {
var err error
instagrams := []*Instagram{}
err = Engine.Find(&instagrams)
return instagrams, On(err, MODEL_INSTAGRAM_COLLECTION_NOT_FOUND)
}
func UpdateInstagramById(instagram *Instagram) (*Instagram, error) {
var err error
_, err = Engine.Id(instagram.Id).UseBool("trusted").Update(instagram)
if err != nil {
return instagram, On(err, MODEL_INSTAGRAM_NOT_UPDATED)
}
return instagram, nil
}
func UpdateInstagram(instagram *Instagram, c *InstagramCredentials) (*Instagram, error) {
var err error
err = instagram.Save(func(instagram *Instagram) {
instagram.Username = c.Username
instagram.Password = <PASSWORD>
instagram.Trusted = c.Trusted
instagram.Hours = &Hours{
Max: c.Hours.Max,
Min: c.Hours.Min,
}
instagram.Speed = &Speed{
Like: c.Speed.Like,
Comment: c.Speed.Comment,
Follow: c.Speed.Follow,
Unfollow: c.Speed.Unfollow,
}
})
return instagram, err
}
func DeleteInstagram(instagram *Instagram) error {
var err error
channels, err := instagram.FindChannels()
if err != nil {
return err
}
for _, c := range channels {
err = instagram.DeleteChannel(c)
if err != nil {
return err
}
}
_, err = Engine.
Id(instagram.Id).
Delete(&Instagram{})
return On(err, MODEL_INSTAGRAM_NOT_DELETED)
}
<file_sep>package logger
import (
"fmt"
"log"
"os"
"time"
"github.com/gin-gonic/gin"
)
var (
Info *log.Logger
Warn *log.Logger
Error *log.Logger
LogFile *os.File
)
func Init(logPath string) {
LogFile, err := os.OpenFile(logPath, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
log.Fatalf("Error open log file: %v", err)
}
Info = log.New(
LogFile,
"[ INFO] ",
log.Ldate|log.Ltime|log.Lmicroseconds,
)
Warn = log.New(
LogFile,
"[ WARN] ",
log.Ldate|log.Ltime|log.Lmicroseconds,
)
Error = log.New(
LogFile,
"[ERROR] ",
log.Ldate|log.Ltime|log.Lmicroseconds,
)
}
func TaggedLoggers(packageName string, functionName string, args ...string) (
func(data string), func(data string), func(data string, err error)) {
tags := fmt.Sprintf("[%s][%s]", packageName, functionName)
for _, a := range args {
tags = fmt.Sprintf("%s[%s]", tags, a)
}
logInfo := func(data string) {
Info.Printf("%s %s\n", tags, data)
}
logWarn := func(data string) {
Warn.Printf("%s %s\n", tags, data)
}
logError := func(data string, err error) {
Error.Printf("%s %s: %s\n", tags, data, err)
}
return logInfo, logWarn, logError
}
func Stop() {
err := LogFile.Close()
if err != nil {
log.Fatalf("Error closing file: %v", err)
}
}
func Logger(c *gin.Context) {
start := time.Now()
c.Next()
Info.Printf(
"| %6s %d | %12s | %s",
c.Request.Method,
c.Writer.Status(),
time.Since(start),
c.Request.URL.Path,
)
}
<file_sep>module.exports = {
NODE_ENV: '"production"',
API_URL: '"http://192.168.0.1/api/v1/"',
BUILD_DIR: 'targets/release',
DEBUG_MODE: false,
}
<file_sep>package main
import (
"math/rand"
"time"
"github.com/gin-gonic/gin"
"massliking/backend/auth"
"massliking/backend/config"
"massliking/backend/logger"
"massliking/backend/models"
"massliking/backend/workers"
)
func init() {
rand.Seed(time.Now().Unix())
// Initialize config
config.Init()
// Initialize logger
logger.Init(config.GetString("log_file"))
// Initialize db connection
models.Init(config.GetString("db_string"))
// Initialize jwt
auth.Init(
config.GetString("jwt.realm"),
config.GetString("jwt.secret"),
config.GetInt("jwt.ttl"),
)
// Launch all accounts workers
workers.StartAllInstagrams()
}
func stop() {
// Close db connection
models.Stop()
// Close logger
logger.Stop()
}
func main() {
// Build Gin instance and append middleware
engine := gin.New()
engine.Use(gin.Recovery())
engine.Use(logger.Logger)
// Build routes
InitRoutes(engine)
// Launch server
StartServer(engine)
}
<file_sep># Massliking
## Synopsis
Full featured mass-following service with an emphasis on marketing concepts.
Written with [Golang](https://golang.org/) and [Quasar](http://quasar-framework.org/) ([VueJS](https://vuejs.org/) under the hood)
This is a relatively stable application, but still in alpha.
## Core concepts
Each target account is considered as a separate channel for attracting followers.
Statistics per each channel gives you the ability to optimise attracting speed by throwing out slow channels.
This ability along with targets filtering makes your growth much faster (I hope it does, huh).
## Instagram client
An instabot package from the backend is a copy of https://github.com/instabot-py/instabot.py.git
There is a [separate document](LIMITS.md) for instagram limits used in the service.
Also, there is an [API description](backend/README.md) for backend.
## Requirements
* `Go` >= 1.8.3
* `Node.js` >= 4.2.6
* `NPM` >= 3.5.2
* `PostgreSQL` >= 9.5.6
#### For deploy
* `Ansible` >= 2.3.1.0
_Maybe it works with earlier versions, this is my current env._
## How to run local instance
1. Create a new database in PostgreSQL
2. Rename `.sample` files from `./config` directory
3. Open `config/development.yml` and edit `db_string` value
4. Compile project with `./bin/build.sh`
5. Run service with `./bin/run.sh`
6. [Here we go!](http://localhost:8080)
## How to deploy on hosting via Ansible
Check out [these instructions](playbook/README.md) for deployment via [Ansible](https://www.ansible.com/).
## TODO
- Implement per-channel filters for targets
- Implement user-friendly interface for channels (sorting, filters etc.)
- Implement signup confirmation via email
- Cover backend(at least) with tests
- Rewrite channels worker (fill queues in separate goroutines)
- Plug in the state machine library to the models
<file_sep>package models
import (
"github.com/go-xorm/xorm"
_ "github.com/lib/pq"
"massliking/backend/logger"
)
var Engine *xorm.Engine
func Init(dbstring string) {
var err error
Engine, err = xorm.NewEngine("postgres", dbstring)
if err != nil {
logger.Error.Fatalf("Error opening db connection: %v", err)
}
Engine.SetLogger(xorm.NewSimpleLogger(logger.LogFile))
err = Engine.Sync2(new(User))
if err != nil {
logger.Error.Fatalf("Error migrate model: User")
}
err = Engine.Sync2(new(Instagram))
if err != nil {
logger.Error.Fatalf("Error migrate model: Instagram")
}
err = Engine.Sync2(new(Channel))
if err != nil {
logger.Error.Fatalf("Error migrate model: Channel")
}
}
func Stop() {
Engine.Close()
}
<file_sep>package workers
import (
"massliking/backend/instabot"
"massliking/backend/models"
)
const WORKER_COMMAND_STOP = "stop"
const WRITE_OP_CAPACITY = 100
func BuildPool() *models.WorkersPool {
pool := &models.WorkersPool{}
pool.WriteOpCh = make(chan *models.InstagramWriteOp, WRITE_OP_CAPACITY)
pool.InstagramCommandCh = make(chan string)
pool.StatsCommandCh = make(chan string)
pool.ChannelCommandChs = map[string](chan string){}
for _, action := range models.ACTIONS {
pool.ChannelCommandChs[action] = make(chan string)
}
return pool
}
func StartPool(i *models.Instagram, client *instabot.Client) {
if models.INSTAGRAM_REGISTRY[i.Id] != nil {
StopPool(i)
}
pool := BuildPool()
go InstagramPoolWorker(client, i, pool)
go StatsPoolWorker(client, i, pool)
for _, action := range models.ACTIONS {
go ChannelsPoolWorker(client, i, action, pool)
}
models.INSTAGRAM_REGISTRY[i.Id] = pool
}
func StopPool(i *models.Instagram) {
if models.INSTAGRAM_REGISTRY[i.Id] == nil {
return
}
pool := models.INSTAGRAM_REGISTRY[i.Id]
pool.InstagramCommandCh <- WORKER_COMMAND_STOP
pool.StatsCommandCh <- WORKER_COMMAND_STOP
for _, action := range models.ACTIONS {
pool.ChannelCommandChs[action] <- WORKER_COMMAND_STOP
}
delete(models.INSTAGRAM_REGISTRY, i.Id)
}
<file_sep>package handlers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
. "massliking/backend/errors"
"massliking/backend/logger"
"massliking/backend/models"
)
func OnError(err error, c *gin.Context) {
logger.Error.Println(err)
switch parsedError := err.(type) {
case BaseError:
c.JSON(http.StatusBadRequest, parsedError)
default:
c.JSON(http.StatusBadRequest, UNKNOWN_ERROR)
}
}
func getUser(c *gin.Context) (*models.User, error) {
user := &models.User{}
username := c.Keys["userID"].(string)
user, err := models.GetUser(username)
if err != nil {
return user, err
}
return user, nil
}
func getInstagram(c *gin.Context) (*models.User, *models.Instagram, error) {
user := &models.User{}
instagram := &models.Instagram{}
user, err := getUser(c)
if err != nil {
return user, instagram, err
}
instagram_id, err := strconv.ParseInt(c.Param("instagram_id"), 10, 64)
if err != nil {
return user, instagram, err
}
instagram, err = user.GetInstagram(instagram_id)
if err != nil {
return user, instagram, err
}
return user, instagram, nil
}
func findInstagrams(c *gin.Context) (*models.User, []*models.Instagram, error) {
user := &models.User{}
instagrams := []*models.Instagram{}
user, err := getUser(c)
if err != nil {
return user, instagrams, err
}
instagrams, err = user.FindInstagrams()
if err != nil {
return user, instagrams, err
}
return user, instagrams, nil
}
func getChannel(c *gin.Context) (*models.Instagram, *models.Channel, error) {
instagram := &models.Instagram{}
channel := &models.Channel{}
_, instagram, err := getInstagram(c)
if err != nil {
return instagram, channel, err
}
id, err := strconv.ParseInt(c.Param("channel_id"), 10, 64)
if err != nil {
return instagram, channel, err
}
channel, err = instagram.GetChannel(id)
if err != nil {
return instagram, channel, err
}
return instagram, channel, nil
}
func findChannels(c *gin.Context) (*models.Instagram, []*models.Channel, error) {
instagram := &models.Instagram{}
channels := []*models.Channel{}
_, instagram, err := getInstagram(c)
if err != nil {
return instagram, channels, err
}
channels, err = instagram.FindChannels()
if err != nil {
return instagram, channels, err
}
return instagram, channels, nil
}
<file_sep>package workers
import (
"time"
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
const ACTION_EMPTY_TIMEOUT = 5 * 60
const ACTION_SUCCESS_TIMEOUT = 0
const ACTION_FAILURE_TIMEOUT = 5 * 60
func ChannelsPoolWorker(client *instabot.Client, i *models.Instagram, action string, pool *models.WorkersPool) {
logInfo, _, _ := logger.TaggedLoggers("workers/channel", "ChannelsPoolWorker", action, i.IdString())
logInfo("Start worker")
timeout := ACTION_SUCCESS_TIMEOUT
for true {
select {
case command := <-pool.ChannelCommandChs[action]:
if command == WORKER_COMMAND_STOP {
logInfo("Command stop received")
return
}
case <-time.After(time.Second * time.Duration(timeout)):
timeout = RunChannels(client, i, action)
}
}
}
func RunChannels(client *instabot.Client, i *models.Instagram, action string) int {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/channel", "RunChannels", action, i.IdString())
logInfo("Validate account state")
err = i.ValidateState(client)
if err != nil {
logError("Validate account state", err)
return ACTION_FAILURE_TIMEOUT
}
logInfo("Looking for active channels with action: " + action)
channels, err := i.FindActiveChannels(action)
if err != nil {
logError("Looking for active channels with action: "+action, err)
return ACTION_FAILURE_TIMEOUT
}
if len(channels) == 0 {
logInfo("Waiting for the next channels search")
return ACTION_EMPTY_TIMEOUT
}
logInfo("Looking for account followings for filtration")
followings, _ := client.GetTotalUserFollowings(i.Info.PK)
logInfo("Iterating over channels, filling queues, running actions")
for _, c := range channels {
_ = FillQueue(c, client, followings)
err = RunAction(i, c, client)
if err != nil {
return ACTION_FAILURE_TIMEOUT
}
time.Sleep(time.Duration(3600/i.ActionSpeed(action)) * time.Second)
}
return ACTION_SUCCESS_TIMEOUT
}
<file_sep>package workers
import (
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
func StartAllInstagrams() {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StartAllInstagrams")
logInfo("Find all accounts")
instagrams, err := models.FindAllInstagrams()
if err != nil {
logError("Find all accounts", err)
}
for _, i := range instagrams {
if i.State == models.INSTAGRAM_STATE_START {
_ = StartInstagram(i)
}
}
}
func StartInstagram(i *models.Instagram) error {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StartInstagram", i.IdString())
logInfo("Login account")
client, err := instabot.Login(i.Username, i.Password)
if err != nil {
logError("Login account", err)
return err
}
logInfo("Launch workers")
StartPool(i, client)
logInfo("Update account state")
err = i.Save(func(i *models.Instagram) {
i.State = models.INSTAGRAM_STATE_START
})
if err != nil {
logError("Update account state", err)
return err
}
logInfo("Update account info")
err = i.UpdateInfo(client)
if err != nil {
logError("Update account info", err)
return err
}
return nil
}
func StopInstagram(i *models.Instagram) error {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StopInstagram", i.IdString())
logInfo("Stop all account channels")
err = StopAllChannels(i)
if err != nil {
logError("Stop all account channels", err)
return err
}
logInfo("Update account state")
err = i.Save(func(i *models.Instagram) {
i.State = models.INSTAGRAM_STATE_STOP
})
if err != nil {
logError("Update account state", err)
return err
}
logInfo("Stop workers")
StopPool(i)
return nil
}
func StopAllChannels(i *models.Instagram) error {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StopAllChannels", i.IdString())
logInfo("Find all account channels")
channels, err := i.FindChannels()
if err != nil {
logError("Find all account channels", err)
return err
}
for _, channel := range channels {
_ = StopChannel(channel)
}
return nil
}
func StartChannel(c *models.Channel) error {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StartChannel", c.IdString())
logInfo("Update channel state")
err = c.Save(func(c *models.Channel) {
c.State = models.CHANNEL_STATE_START
})
if err != nil {
logError("Update channel state", err)
return err
}
return nil
}
func StopChannel(c *models.Channel) error {
var err error
logInfo, _, logError := logger.TaggedLoggers("workers/commands", "StopChannel", c.IdString())
logInfo("Update channel state")
err = c.Save(func(c *models.Channel) {
c.State = models.CHANNEL_STATE_STOP
})
if err != nil {
logError("Update channel state", err)
return err
}
return nil
}
<file_sep>package models
type Credentials struct {
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
}
type InstagramCredentials struct {
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
Trusted bool `json:"trusted"`
Speed `json:"speed"`
Hours `json:"hours"`
}
type ChannelCredentials struct {
Value string `json:"value"`
Action string `json:"action"`
Target string `json:"target"`
Comments []string `json:"comments"`
}
<file_sep>package auth
import (
"time"
"github.com/gin-gonic/gin"
"gopkg.in/appleboy/gin-jwt.v2"
"massliking/backend/models"
)
var JWT *jwt.GinJWTMiddleware
func Init(jwtRealm string, jwtSecret string, jwtTTL int) {
JWT = &jwt.GinJWTMiddleware{
Realm: jwtRealm,
Key: []byte(jwtSecret),
Timeout: time.Hour * time.Duration(jwtTTL),
MaxRefresh: time.Hour * time.Duration(jwtTTL),
Authenticator: func(userId string, password string, c *gin.Context) (string, bool) {
user, err := models.GetUser(userId)
if err != nil {
return userId, false
}
verified := user.Verify(password)
return userId, verified
},
Authorizator: func(userId string, c *gin.Context) bool {
_, err := models.GetUser(userId)
if err != nil {
return false
} else {
return true
}
},
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
},
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup: "header:Authorization",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
}
}
<file_sep>import auth from './auth'
import router from '../router'
const API_URL = process.env.API_URL
export default {
isEmptyChannelLists (context) {
return context.$store.state.instagramList.some((instagram, _index, _array) => {
!instagram.channels
})
},
updateAllChannels (context) {
context.$store.state.instagramList.forEach((instagram, _index, _array) => {
this.updateAccountChannels(context, instagram, false)
})
},
updateAccountChannels (context, instagram, redirect) {
var url = API_URL + 'instagram/' + instagram.id + '/channels'
context.$http.get(url, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('updateChannelList', { instagram: instagram, channelList: response.body })
context.$forceUpdate()
if (redirect) { router.push({path: redirect}) }
}, error => {
console.log(error)
// TODO: Переделать на правильную ошибку.
// if (error.status === 400) { context.errorInvalidCredentials = true }
})
},
createChannel (context, instagram, form, redirect) {
var url = API_URL + 'instagram/' + instagram.id + '/channels'
context.$http.post(url, form, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('addChannel', { instagram: instagram, channel: response.body })
if (redirect) { router.push({path: redirect}) }
}, error => {
console.log(error)
})
},
editChannel (context, instagram, channel, form, redirect) {
var url = API_URL + 'instagram/' + instagram.id + '/channels/' + channel.id
context.$http.put(url, form, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('updateChannel', { instagram: instagram, channel: response.body })
if (redirect) { router.push({path: redirect}) }
}, error => {
console.log(error)
})
},
deleteChannel (context, instagram, channel, redirect) {
var url = API_URL + 'instagram/' + instagram.id + '/channels/' + channel.id
context.$http.delete(url, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('deleteChannel', { instagram: instagram, channel: channel })
if (redirect) { router.push({path: redirect}) }
}, error => {
console.log(error)
})
},
startChannel (context, instagram, channel) {
var url = API_URL + 'instagram/' + instagram.id + '/channels/' + channel.id + '/start'
context.$http.get(url, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('updateChannel', { instagram: instagram, channel: response.body })
context.$forceUpdate()
}, error => {
console.log(error)
})
},
stopChannel (context, instagram, channel) {
var url = API_URL + 'instagram/' + instagram.id + '/channels/' + channel.id + '/stop'
context.$http.get(url, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('updateChannel', { instagram: instagram, channel: response.body })
context.$forceUpdate()
}, error => {
console.log(error)
})
}
}
<file_sep>import router from '../router'
const API_URL = process.env.API_URL
const LOGIN_URL = API_URL + 'login'
const SIGNUP_URL = API_URL + 'signup'
const REFRESH_URL = API_URL + 'user/refresh_token'
const TOKEN_ID = '<PASSWORD>'
export default {
user: {
authenticated: localStorage.getItem(TOKEN_ID) || false
},
checkAuth () {
const jwt = localStorage.getItem(TOKEN_ID)
return this.user.authenticated === jwt
},
login (context, creds, redirect) {
context.$http.post(LOGIN_URL, creds)
.then(response => {
localStorage.setItem(TOKEN_ID, response.body.token)
this.user.authenticated = response.body.token
if (redirect) {
router.push({path: redirect})
}
}, error => {
if (error.status === 401) {
context.errorInvalidCredentials = true
}
})
},
signup (context, creds, redirect) {
context.$http.post(SIGNUP_URL, creds)
.then(response => {
if (this.user.authenticated) {
localStorage.removeItem(TOKEN_ID)
this.user.authenticated = false
}
this.login(context, creds, redirect)
}, error => {
if (error.status === 401) {
context.errorAlreadyExists = true
}
})
},
logout (context, redirect) {
localStorage.removeItem(TOKEN_ID)
this.user.authenticated = false
context.$store.commit('deleteUser')
context.$store.commit('deleteInstagramList')
if (redirect) {
router.push({path: redirect})
}
},
refreshToken (context, redirect) {
context.$http.get(REFRESH_URL, {headers: this.getAuthHeader()})
.then(response => {
localStorage.setItem(TOKEN_ID, response.body.token)
this.user.authenticated = response.body.token
}, error => {
if (error.status !== 200) {
this.logout(context, redirect)
}
})
},
getAuthHeader () {
return {
'Authorization': 'Bearer ' + localStorage.getItem(TOKEN_ID)
}
}
}
<file_sep>package models
import (
. "massliking/backend/errors"
)
func CreateChannel(instagram *Instagram, c *ChannelCredentials) (*Channel, error) {
var err error
channel := &Channel{
InstagramId: instagram.Id,
Action: c.Action,
Target: c.Target,
Value: c.Value,
Comments: c.Comments,
State: CHANNEL_STATE_STOP,
LeadsCount: 0,
TargetsCount: 0,
Queue: &Queue{
MaxId: "",
Leads: []int{},
Targets: []int{},
},
}
_, err = Engine.Insert(channel)
return channel, On(err, MODEL_CHANNEL_NOT_CREATED)
}
func GetChannel(instagram *Instagram, id int64) (*Channel, error) {
var err error
channel := &Channel{}
has, err := Engine.
Id(id).
And("instagram_id = ?", instagram.Id).
Get(channel)
if err != nil || has != true {
return channel, On(err, MODEL_CHANNEL_NOT_FOUND)
}
return channel, nil
}
func FindChannels(instagram *Instagram) ([]*Channel, error) {
var err error
channels := []*Channel{}
err = Engine.
Where("instagram_id = ?", instagram.Id).
Find(&channels)
return channels, On(err, MODEL_CHANNEL_COLLECTION_NOT_FOUND)
}
func FindActiveChannels(instagram *Instagram, action string) ([]*Channel, error) {
var err error
channels := []*Channel{}
err = Engine.
Sql("SELECT * FROM channel WHERE instagram_id = ? AND action = ? AND ((state = ?) OR (state = ? AND targets_count > 0))",
instagram.Id,
action,
CHANNEL_STATE_START,
CHANNEL_STATE_EMPTY).
Find(&channels)
return channels, On(err, MODEL_CHANNEL_COLLECTION_NOT_FOUND)
}
func UpdateChannel(channel *Channel, c *ChannelCredentials) (*Channel, error) {
var err error
err = channel.Save(func(channel *Channel) {
channel.Action = c.Action
channel.Target = c.Target
channel.Value = c.Value
channel.Comments = c.Comments
})
return channel, err
}
func DeleteChannel(channel *Channel) error {
var err error
_, err = Engine.
Id(channel.Id).
Delete(&Channel{})
return On(err, MODEL_CHANNEL_NOT_DELETED)
}
<file_sep>package models
func (i *Instagram) CreateChannel(c *ChannelCredentials) (*Channel, error) {
return CreateChannel(i, c)
}
func (i *Instagram) GetChannel(id int64) (*Channel, error) {
return GetChannel(i, id)
}
func (i *Instagram) FindChannels() ([]*Channel, error) {
return FindChannels(i)
}
func (i *Instagram) FindActiveChannels(action string) ([]*Channel, error) {
return FindActiveChannels(i, action)
}
func (i *Instagram) UpdateChannel(channel *Channel, c *ChannelCredentials) (*Channel, error) {
return UpdateChannel(channel, c)
}
func (i *Instagram) DeleteChannel(channel *Channel) error {
return DeleteChannel(channel)
}
<file_sep># Deploying Massliking to hosting
This methods tested with $5 droplet on DigitalOcean and works pretty well
## Simple one
1. Make a droplet on DO or your favorite hosting service
2. Add your IP address to `./playbook/default.inventory` file
3. Open `./playbook/roles/web/templates/prod.env.js` and add your IP address into `API_URL` value
4. Go to `./playbook` directory and run `./rollout.sh`
5. For subsequent deploys use `./deploy.sh`
## Custom deployment
1. Make a droplet on DO or your favorite hosting service
2. Add your IP address to `default.inventory` file
3. Fork massliking repo
4. I used [Ansible Vault](http://docs.ansible.com/ansible/latest/playbooks_vault.html) for sensitive files:
1. Make local file `~/.vault_pass.txt` and save arbitrary password into it
2. Encrypt your ssh key into a file named `deploy_key`
3. Save it into `./playbook/roles/deploy_keys/files/`
5. Edit `./playbook/roles/web/vars/main.yml` and add your repo
6. Edit `./playbook/roles/postgresql/vars/main.yml` if you want to change the database settings
7. Edit `./playbook/roles/web/templates/production.yml` and respectively change `db_string` value
8. Open `./playbook/roles/web/templates/prod.env.js` and add your IP address into `API_URL` value
9. Go to `./playbook` directory and run `./rollout.sh`
10. For subsequent deploys use `./deploy.sh`
<file_sep>package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"massliking/backend/models"
"massliking/backend/workers"
)
func StopInstagramHandler(c *gin.Context) {
_, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
err = workers.StopInstagram(instagram)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagram)
}
func StartInstagramHandler(c *gin.Context) {
_, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
err = workers.StartInstagram(instagram)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagram)
}
func CreateInstagramHandler(c *gin.Context) {
user, err := getUser(c)
if err != nil {
OnError(err, c)
return
}
creds := &models.InstagramCredentials{}
c.BindJSON(creds)
instagram, err := user.CreateInstagram(creds)
if err != nil {
OnError(err, c)
return
}
err = workers.StartInstagram(instagram)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagram)
}
func FindInstagramsHandler(c *gin.Context) {
_, instagrams, err := findInstagrams(c)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagrams)
}
func GetInstagramHandler(c *gin.Context) {
_, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagram)
}
func UpdateInstagramHandler(c *gin.Context) {
user, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
creds := &models.InstagramCredentials{}
c.BindJSON(creds)
instagram, err = user.UpdateInstagram(instagram, creds)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, instagram)
}
func DeleteInstagramHandler(c *gin.Context) {
user, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
err = workers.StopInstagram(instagram)
if err != nil {
OnError(err, c)
return
}
err = user.DeleteInstagram(instagram)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, gin.H{})
}
<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
user: {},
instagramList: []
},
getters: {
findInstagram: (state, getters) => (id) => {
return state.instagramList.find(instagram => instagram.id.toString() === id.toString())
},
instagram: (state, getters) => (id) => {
return getters.findInstagram(id)
},
findChannel: (state, getters) => (instagramId, id) => {
var instagram = getters.findInstagram(instagramId)
return instagram.channels.find(channel => channel.id.toString() === id.toString())
},
channel: (state, getters) => (instagramId, id) => {
return getters.findChannel(instagramId, id)
}
},
mutations: {
updateUser (state, payload) {
state.user = { ...state.user, ...payload.user }
},
deleteUser (state) {
state.user = {}
},
updateInstagramList (state, payload) {
payload.instagramList.forEach((instagram, _index, _account) => {
var index = state.instagramList.findIndex(i => { return i.id === instagram.id })
if (instagram.channels === undefined || instagram.channels === null) {
instagram.channels = []
}
if (index === -1) {
state.instagramList.push(instagram)
}
else {
state.instagramList[index] = { ...state.instagramList[index], ...instagram }
}
})
},
updateInstagram (state, payload) {
var index = state.instagramList.findIndex(i => { return i.id === payload.instagram.id })
state.instagramList = Object.assign([], state.instagramList, {[index]: payload.instagram})
},
addInstagram (state, payload) {
state.instagramList = [ ...state.instagramList, payload.instagram ]
},
deleteInstagram (state, payload) {
var index = state.instagramList.indexOf(payload.instagram)
state.instagramList.splice(index, 1)
},
deleteInstagramList (state) {
state.instagramList = []
},
updateChannelList (state, payload) {
var instagram = state.instagramList.find(instagram => instagram.id === payload.instagram.id)
if (!instagram.channel) {
Vue.set(instagram, 'channels', payload.channelList)
}
else {
payload.channelList.forEach((channel, _index, _account) => {
var index = instagram.channels.findIndex(c => { return c.id.toString() === channel.id.toString() })
if (index === -1) {
instagram.channels.push(channel)
}
else {
instagram.channels[index] = { ...instagram.channels[index], ...channel }
}
})
}
},
addChannel (state, payload) {
var instagram = state.instagramList.find(instagram => instagram.id === payload.instagram.id)
instagram.channels = [ ...instagram.channels, payload.channel ]
},
updateChannel (state, payload) {
var instagram = state.instagramList.find(instagram => instagram.id === payload.instagram.id)
var index = instagram.channels.findIndex(c => { return c.id.toString() === payload.channel.id.toString() })
instagram.channels = Object.assign([], instagram.channels, {[index]: payload.channel})
},
deleteChannel (state, payload) {
var instagram = state.instagramList.find(instagram => instagram.id === payload.instagram.id)
var index = instagram.channels.findIndex(c => { return c.id.toString() === payload.channel.id.toString() })
instagram.channels.splice(index, 1)
}
}
})
<file_sep>package instabot
type GetUserFeedResponse struct {
Items []*Item `json:"items"`
NumResults int `json:"num_results"`
MoreAvailable bool `json:"more_available"`
NextMaxID string `json:"next_max_id"`
AutoLoadMoreEnabled bool `json:"auto_load_more_enabled"`
Status string `json:"status"`
}
type GetUserFollowersResponse struct {
Users []*User `json:"users"`
BigList bool `json:"big_list"`
PageSize int `json:"page_size"`
NextMaxID string `json:"next_max_id"`
Status string `json:"status"`
}
type GetUserFollowingsResponse struct {
Users []*User `json:"users"`
BigList bool `json:"big_list"`
PageSize int `json:"page_size"`
NextMaxID string `json:"next_max_id"`
Status string `json:"status"`
}
type GetHashtagFeedResponse struct {
Items []*HashtagItem `json:"items"`
NumResults int `json:"num_results"`
NextMaxID string `json:"next_max_id"`
MoreAvailable bool `json:"more_available"`
AutoLoadMoreEnabled bool `json:"auto_load_more_enabled"`
Status string `json:"status"`
}
type GetMediaCommentsResponse struct {
CommentLikesEnabled bool `json:"comment_likes_enabled"`
Comments []struct {
Pk int64 `json:"pk"`
UserID int `json:"user_id"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt int `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
ContentType string `json:"content_type"`
Status string `json:"status"`
BitFlags int `json:"bit_flags"`
User *User `json:"user"`
HasLikedComment bool `json:"has_liked_comment"`
CommentLikeCount int `json:"comment_like_count"`
} `json:"comments"`
CommentCount int `json:"comment_count"`
Caption struct {
Pk int64 `json:"pk"`
UserID int `json:"user_id"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt int `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
ContentType string `json:"content_type"`
Status string `json:"status"`
BitFlags int `json:"bit_flags"`
User *User `json:"user"`
} `json:"caption"`
CaptionIsEdited bool `json:"caption_is_edited"`
HasMoreComments bool `json:"has_more_comments"`
HasMoreHeadloadComments bool `json:"has_more_headload_comments"`
PreviewComments []struct {
Pk int64 `json:"pk"`
UserID int `json:"user_id"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt int `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
ContentType string `json:"content_type"`
Status string `json:"status"`
BitFlags int `json:"bit_flags"`
User *User `json:"user"`
} `json:"preview_comments"`
NextMaxID string `json:"next_max_id"`
Status string `json:"status"`
}
type GetMediaLikersResponse struct {
Users []*User `json:"users"`
UserCount int `json:"user_count"`
Status string `json:"status"`
}
type LikeResponse struct {
Status string `json:"status"`
}
type FollowResponse struct {
*FriendshipStatus `json:"friendship_status"`
Status string `json:"status"`
}
type UnfollowResponse struct {
LoggedInUser struct {
Pk int64 `json:"pk"`
Username string `json:"username"`
FullName string `json:"full_name"`
IsPrivate bool `json:"is_private"`
ProfilePicURL string `json:"profile_pic_url"`
IsVerified bool `json:"is_verified"`
HasAnonymousProfilePicture bool `json:"has_anonymous_profile_picture"`
AllowContactsSync bool `json:"allow_contacts_sync"`
} `json:"logged_in_user"`
Status string `json:"status"`
}
type CommentResponse struct {
Comment struct {
ContentType string `json:"content_type"`
User *User `json:"user"`
Pk int `json:"pk"`
Text string `json:"text"`
Type int `json:"type"`
CreatedAt float64 `json:"created_at"`
CreatedAtUtc int `json:"created_at_utc"`
MediaID int64 `json:"media_id"`
Status string `json:"status"`
} `json:"comment"`
Status string `json:"status"`
}
type LoginResponse struct {
*LoggedInUser `json:"logged_in_user"`
Status string `json:"status"`
}
type SearchUsernameResponse struct {
*UserInfo `json:"user"`
Status string `json:"status"`
}
<file_sep>package models
func (u *User) CreateInstagram(c *InstagramCredentials) (*Instagram, error) {
return CreateInstagram(u, c)
}
func (u *User) GetInstagram(id int64) (*Instagram, error) {
return GetInstagram(u, id)
}
func (u *User) FindInstagrams() ([]*Instagram, error) {
return FindInstagrams(u)
}
func (u *User) UpdateInstagram(instagram *Instagram, c *InstagramCredentials) (*Instagram, error) {
return UpdateInstagram(instagram, c)
}
func (u *User) DeleteInstagram(instagram *Instagram) error {
return DeleteInstagram(instagram)
}
<file_sep>package instabot
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"time"
. "massliking/backend/errors"
"massliking/backend/logger"
)
type Client struct {
PK int
Username string
Password string
Seed string
DeviceId string
GUUID string
Token string
RankToken string
Suspected bool
LastResponse []byte
LoggedAt time.Time
Cookies []*http.Cookie
}
func (c *Client) Init(username string, password string, cookies []*http.Cookie) {
c.Cookies = cookies
c.Username = username
c.Password = <PASSWORD>
c.Seed = generateSeed(c.Username, c.Password)
c.DeviceId = generateDeviceId(c.Seed)
c.GUUID = generateUUID(true)
c.Suspected = false
c.LoggedAt = time.Now().AddDate(0, 0, -30)
}
func (c *Client) sendRequest(endpoint string, params string) (int, error) {
var request *http.Request
var err error
logInfo, logWarn, logError := logger.TaggedLoggers("instabot/client", "sendRequest", c.Username, endpoint)
if c.Suspected {
logError("Client suspected, interrupting request", INSTABOT_SUSPECTED_ERROR)
return -1, INSTABOT_SUSPECTED_ERROR
}
logInfo(">>> Request " + params)
jar, _ := cookiejar.New(nil)
jar.SetCookies(JAR_URL, c.Cookies)
client := &http.Client{Jar: jar}
if params != "" {
request, err = http.NewRequest("POST", API_URL+endpoint, bytes.NewBuffer([]byte(params)))
if err != nil {
logError("Build POST request", err)
return -1, err
}
} else {
request, err = http.NewRequest("GET", API_URL+endpoint, nil)
if err != nil {
logError("Build GET request", err)
return -1, err
}
}
for k, v := range HEADERS {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
logError("Execute request", err)
return -1, err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
logError("Read response body", err)
return -1, err
}
response.Body.Close()
logInfo("<<< Response: " + response.Status)
logInfo("<<< Body: " + string(body))
if response.StatusCode != http.StatusOK {
logWarn("<<< Response: " + string(body))
return response.StatusCode, INSTABOT_REQUEST_ERROR
}
if response.StatusCode == http.StatusTooManyRequests {
c.Suspected = true
}
c.LastResponse = body
c.Cookies = client.Jar.Cookies(JAR_URL)
return response.StatusCode, nil
}
func (c *Client) findCookie(name string) string {
for _, cookie := range c.Cookies {
if cookie.Name == name {
return cookie.Value
}
}
return ""
}
<file_sep>package instabot
import (
"encoding/json"
"net/http"
"strconv"
"time"
. "massliking/backend/errors"
)
func Login(username string, password string) (*Client, error) {
var err error
client := Client{}
client.Init(username, password, []*http.Cookie{})
_, err = client.Login()
if err != nil {
return &client, On(err, MODEL_INSTAGRAM_LOGIN_ERROR)
}
return &client, nil
}
func (c *Client) SearchUsername(username string) (*SearchUsernameResponse, error) {
var err error
response := &SearchUsernameResponse{}
_, err = c.sendRequest("users/"+username+"/usernameinfo/", "")
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) GetUserFollowers(pk int, maxid string) (*GetUserFollowersResponse, error) {
var err error
response := &GetUserFollowersResponse{}
if maxid == "" {
_, err = c.sendRequest("friendships/"+strconv.Itoa(pk)+"/followers/?rank_token="+c.RankToken, "")
} else {
_, err = c.sendRequest("friendships/"+strconv.Itoa(pk)+"/followers/?rank_token="+c.RankToken+"&max_id="+maxid, "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) GetUserFollowings(pk int, maxid string) (*GetUserFollowingsResponse, error) {
var err error
response := &GetUserFollowingsResponse{}
if maxid == "" {
_, err = c.sendRequest("friendships/"+strconv.Itoa(pk)+"/following/?ig_sig_key_version="+SIG_KEY_VERSION+"&rank_token="+c.RankToken, "")
} else {
_, err = c.sendRequest("friendships/"+strconv.Itoa(pk)+"/following/?ig_sig_key_version="+SIG_KEY_VERSION+"&rank_token="+c.RankToken+"&max_id="+maxid, "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) GetHashtagFeed(hashtag string, maxid string) (*GetHashtagFeedResponse, error) {
var err error
response := &GetHashtagFeedResponse{}
if maxid == "" {
_, err = c.sendRequest("feed/tag/"+hashtag+"/?rank_token="+c.RankToken+"&ranked_content=true", "")
} else {
_, err = c.sendRequest("feed/tag/"+hashtag+"/?max_id="+maxid+"&rank_token="+c.RankToken+"&ranked_content=true", "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
// There is ids map for faster processing
func (c *Client) GetTotalUserFollowers(pk int) (map[int]bool, error) {
var err error
followers := map[int]bool{}
nextMaxID := ""
for true {
response, err := c.GetUserFollowers(pk, nextMaxID)
if err != nil {
return followers, err
}
for _, u := range response.Users {
followers[u.PK] = true
}
if response.BigList == false {
return followers, nil
}
nextMaxID = response.NextMaxID
}
return followers, err
}
func (c *Client) GetTotalUserFollowings(pk int) (map[int]bool, error) {
var err error
followings := map[int]bool{}
nextMaxID := ""
for true {
response, err := c.GetUserFollowings(pk, nextMaxID)
if err != nil {
return followings, err
}
for _, u := range response.Users {
followings[u.PK] = true
}
if response.BigList == false {
return followings, nil
}
nextMaxID = response.NextMaxID
}
return followings, err
}
func (c *Client) GetUserFeed(pk int, maxid string, minTimestamp int64) (*GetUserFeedResponse, error) {
var err error
response := &GetUserFeedResponse{}
if maxid == "" {
_, err = c.sendRequest("feed/user/"+strconv.Itoa(pk)+"/?min_timestamp="+strconv.FormatInt(minTimestamp, 10)+"&rank_token="+c.RankToken+"&ranked_content=true", "")
} else {
_, err = c.sendRequest("feed/user/"+strconv.Itoa(pk)+"/?max_id="+maxid+"&min_timestamp="+strconv.FormatInt(minTimestamp, 10)+"&rank_token="+c.RankToken+"&ranked_content=true", "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) GetMediaLikers(mediaPk int, maxid string) (*GetMediaLikersResponse, error) {
var err error
response := &GetMediaLikersResponse{}
if maxid == "" {
_, err = c.sendRequest("media/"+strconv.Itoa(mediaPk)+"/likers/", "")
} else {
_, err = c.sendRequest("media/"+strconv.Itoa(mediaPk)+"/likers/?max_id="+maxid, "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) GetMediaComments(mediaPk int, maxid string) (*GetMediaCommentsResponse, error) {
var err error
response := &GetMediaCommentsResponse{}
if maxid == "" {
_, err = c.sendRequest("media/"+strconv.Itoa(mediaPk)+"/comments/", "")
} else {
_, err = c.sendRequest("media/"+strconv.Itoa(mediaPk)+"/comments/?max_id="+maxid, "")
}
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) Follow(pk int) (*FollowResponse, error) {
var err error
response := &FollowResponse{}
data := map[string]interface{}{
"_uuid": c.GUUID,
"_uid": c.PK,
"user_id": strconv.Itoa(pk),
"_csrftoken": c.Token,
}
jsonData, _ := json.Marshal(data)
_, err = c.sendRequest("friendships/create/"+strconv.Itoa(pk)+"/", generateSignature(jsonData))
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) Comment(mediaPk int, text string) (*CommentResponse, error) {
var err error
response := &CommentResponse{}
data := map[string]interface{}{
"_uuid": c.GUUID,
"_uid": c.PK,
"_csrftoken": c.Token,
"comment_text": text,
}
jsonData, _ := json.Marshal(data)
_, err = c.sendRequest("media/"+strconv.Itoa(mediaPk)+"/comment/", generateSignature(jsonData))
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) Unfollow(pk int) (*UnfollowResponse, error) {
var err error
response := &UnfollowResponse{}
data := map[string]interface{}{
"_uuid": c.GUUID,
"_uid": c.PK,
"user_id": strconv.Itoa(pk),
"_csrftoken": c.Token,
}
jsonData, _ := json.Marshal(data)
_, err = c.sendRequest("friendships/destroy/"+strconv.Itoa(pk)+"/", generateSignature(jsonData))
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) Like(mediaId int) (*LikeResponse, error) {
var err error
response := &LikeResponse{}
data := map[string]interface{}{
"_uuid": c.GUUID,
"_uid": c.PK,
"_csrftoken": c.Token,
"media_id": mediaId,
}
jsonData, _ := json.Marshal(data)
_, err = c.sendRequest("media/"+strconv.Itoa(mediaId)+"/like/", generateSignature(jsonData))
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
return response, nil
}
func (c *Client) Login() (*LoginResponse, error) {
var err error
response := &LoginResponse{}
_, err = c.sendRequest("si/fetch_headers/?challenge_type=signup&guid="+generateUUID(false), "")
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
data := map[string]interface{}{
"phone_id": generateUUID(true),
"_csrftoken": c.findCookie("csrftoken"),
"username": c.Username,
"guid": c.GUUID,
"device_id": c.DeviceId,
"password": <PASSWORD>,
"login_attempt_count": "0",
}
jsonData, _ := json.Marshal(data)
_, err = c.sendRequest("accounts/login/", generateSignature(jsonData))
if err != nil {
return response, INSTABOT_REQUEST_ERROR
}
err = json.Unmarshal(c.LastResponse, response)
if err != nil {
return response, INSTABOT_BODY_PARSE_ERROR
}
if response.Status != "ok" {
return response, INSTABOT_LOGIN_ERROR
}
c.PK = response.LoggedInUser.PK
c.RankToken = strconv.Itoa(c.PK) + "_" + c.GUUID
c.Token = c.findCookie("csrftoken")
c.LoggedAt = time.Now()
return response, nil
}
<file_sep>package main
import (
"os"
"strconv"
"syscall"
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
"massliking/backend/config"
"massliking/backend/logger"
)
func SavePid(address string) {
pid := syscall.Getpid()
pidFile, err := os.OpenFile(config.GetString("pid_file"), os.O_APPEND|os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
logger.Error.Fatalf("Error creating pid file: %v", err)
}
_, err = pidFile.Write([]byte(strconv.Itoa(pid)))
if err != nil {
logger.Error.Fatalf("Error write to pid file: %v", err)
}
pidFile.Close()
logger.Info.Println("Listening and serving HTTP on", address)
logger.Info.Printf("Actual pid is %d", pid)
}
func StartServer(engine *gin.Engine) {
address := config.GetString("app_address")
server := endless.NewServer(address, engine)
server.BeforeBegin = SavePid
err := server.ListenAndServe()
if err != nil {
logger.Error.Fatalf("Server interrupted: %v", err)
}
}
<file_sep>package config
import (
"fmt"
"os"
"github.com/spf13/viper"
)
const RELEASE = "production"
const DEVELOP = "development"
var APP_ENV string
func Init() {
APP_ENV = os.Getenv("APP_ENV")
viper.SetConfigName(APP_ENV)
viper.AddConfigPath("./config/")
viper.AddConfigPath("/srv/release/config/")
viper.SetConfigType("yaml")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
func GetString(key string) string {
return viper.GetString(key)
}
func GetInt(key string) int {
return viper.GetInt(key)
}
func IsRelease() bool {
return APP_ENV == RELEASE
}
func IsDevelop() bool {
return APP_ENV == DEVELOP
}
<file_sep>package models
import (
"strconv"
"time"
. "massliking/backend/errors"
)
const CHANNEL_STATE_STOP = "stop"
const CHANNEL_STATE_START = "start"
const CHANNEL_STATE_EMPTY = "empty"
var ACTIONS = [4]string{
"like",
"comment",
"follow",
"unfollow",
}
var TARGETS = [5]string{
"followers",
"subscriptions",
"hashtag",
"likes",
"comments",
}
type Queue struct {
MaxId string
Leads []int
Targets []int
}
type Channel struct {
Id int64 `json:"id" xorm:"pk autoincr index"`
InstagramId int64 `json:"-" xorm:"index"`
Action string `json:"action" xorm:"varchar(250) notnull"`
Target string `json:"target" xorm:"varchar(250) notnull"`
Value string `json:"value" xorm:"varchar(250) notnull"`
Comments []string `json:"comments" xorm:"jsonb"`
State string `json:"state" xorm:"varchar(250) notnull default 'stop'"`
LeadsCount int `json:"leads_count" xorm:"integer"`
TargetsCount int `json:"targets_count" xorm:"integer"`
FollowersCount int `json:"followers_count" xorm:"integer default 0"`
Version int `json:"-" xorm:"version"`
CreatedAt time.Time `json:"created_at" xorm:"created"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated"`
*Queue `json:"-" xorm:"jsonb"`
}
func (c *Channel) IdString() string {
return strconv.FormatInt(c.Id, 10)
}
func (c *Channel) Leads() map[int]bool {
leads := map[int]bool{}
for _, l := range c.Queue.Leads {
leads[l] = true
}
return leads
}
func (c *Channel) Save(update func(c *Channel)) error {
var err error
channel := Channel{}
_, err = Engine.Id(c.Id).Get(&channel)
if err != nil {
return On(err, MODEL_CHANNEL_NOT_UPDATED)
}
*c = channel
update(c)
c.LeadsCount = len(c.Queue.Leads)
c.TargetsCount = len(c.Queue.Targets)
_, err = Engine.Id(c.Id).Update(c)
if err != nil {
return On(err, MODEL_CHANNEL_NOT_UPDATED)
}
return nil
}
func (c *Channel) Instagram() (*Instagram, error) {
var err error
instagram := &Instagram{}
_, err = Engine.Id(c.InstagramId).Get(instagram)
return instagram, On(err, MODEL_INSTAGRAM_NOT_FOUND)
}
<file_sep># Backend API
## Content
- [Dictionaries](#dictionaries)
- [Instagram states](#instagram-states)
- [Channel states](#channel-states)
- [Channel actions](#channel-actions)
- [Channel targets](#channel-targets)
- [Entities](#entities)
- [Token](#token)
- [User](#user)
- [Instagram](#instagram)
- [Channel](#channel)
- [Errors](#errors)
- [Methods](#methods)
- [POST /api/v1/login](#post-apiv1login)
- [POST /api/v1/signup](#post-apiv1signup)
- [GET /api/v1/user/refresh_token](#get-apiv1userrefresh_token)
- [GET /api/v1/user](#get-apiv1user)
- [POST /api/v1/instagrams](#post-apiv1instagrams)
- [GET /api/v1/instagrams](#get-apiv1instagrams)
- [GET /api/v1/instagrams/:id](#get-apiv1instagramsid)
- [GET /api/v1/instagrams/:id/stop](#get-apiv1instagramsidstop)
- [GET /api/v1/instagrams/:id/start](#get-apiv1instagramsidstart)
- [PUT /api/v1/instagrams/:id](#put-apiv1instagramsid)
- [DELETE /api/v1/instagrams/:id](#delete-apiv1instagramsid)
- [POST /api/v1/intagram/:instagram_id/channels](#post-apiv1instagraminstagram_idchannels)
- [GET /api/v1/instagram/:instagram_id/channels](#get-apiv1instagraminstagram_idchannels)
- [GET /api/v1/instagram/:instagram_id/channels/:id](#get-apiv1instagraminstagram_idchannelsid)
- [GET /api/v1/instagram/:instagram_id/channels/:id/stop](#get-apiv1instagraminstagram_idchannelsidstop)
- [GET /api/v1/instagram/:instagram_id/channels/:id/start](#get-apiv1instagraminstagram_idchannelsidstart)
- [PUT /api/v1/instagram/:instagram_id/channels/:id](#put-apiv1instagraminstagram_idchannelsid)
- [DELETE /api/v1/instagram/:instagram_id/channels/:id](#delete-apiv1instagraminstagram_idchannelsid)
## Dictionaries
#### Instagram states
- start
- stop
- suspected
#### Channel states
- start
- stop
- empty
#### Channel actions
- like
- comment
- follow
- unfollow
#### Channel targets
- followers
- subscriptions
- hashtag
- likes
- comments
## Entities
#### Token
```json
{
"expire": "2017-03-18T17:34:30+04:00",
"token": "<PASSWORD>"
}
```
#### User
```json
{
"id": "1",
"username": "<EMAIL>",
"created_at": "2017-01-21T13:18:32Z",
"updated_at": "2017-01-21T13:18:32Z"
}
```
#### Instagram
```json
{
"id": 20,
"info": {
"is_business": false,
"profile_pic_url": "https://profile_pic_url.jpg",
"hd_profile_pic_url_info": {
"width": 150,
"height": 150,
"url": "https://hd_profile_pic_url_info.jpg"
},
"usertags_count": 0,
"external_lynx_url": "http://l.instagram.com/external_lynx_url",
"following_count": 64,
"has_anonymous_profile_picture": true,
"geo_media_count": 0,
"external_url": "http://instagram.com/username",
"username": "username",
"biography": "biography",
"has_chaining": true,
"full_name": "full_name",
"is_private": false,
"pk": 1234567890,
"follower_count": 25,
"profile_pic_id": "",
"is_verified": false,
"hd_profile_pic_versions": [
{
"width": 320,
"height": 320,
"url": "https://hd_profile_pic_versions.jpg"
},
{
"width": 640,
"height": 640,
"url": "https://hd_profile_pic_versions.jpg"
}
],
"media_count": 5,
"is_favorite": false
},
"state": "start",
"username": "username",
"password": "<PASSWORD>",
"trusted": false,
"hours": {
"min": 0,
"max": 0
},
"speed": {
"like": 10,
"comment": 10,
"follow": 10,
"unfollow": 10
},
"created_at": "2017-07-21T12:40:45+04:00",
"updated_at": "2017-07-21T12:40:48.521987752+04:00"
}
```
#### Channel
```json
{
"id": 10,
"action": "like",
"target": "followers",
"value": "natgeo",
"comments": [],
"state": "empty",
"leads_count": 0,
"targets_count": 30,
"followers_count": 0,
"created_at": "2017-07-16T19:52:08+04:00",
"updated_at": "2017-07-21T12:49:37+04:00"
}
```
## Errors
#### HTTP 400 BAD REQUEST
```json
{"code": 1010, "message": "Request to instagram failed", "payload": ""}
{"code": 1020, "message": "Instagram login failed", "payload": ""}
{"code": 1030, "message": "Error parse instagram response", "payload": ""}
{"code": 1040, "message": "Error fetch followers list", "payload": ""}
{"code": 1050, "message": "Instagram account is suspected", "payload": ""}
{"code": 2010, "message": "Instagram not found", "payload": ""}
{"code": 2020, "message": "Instagram collection not found", "payload": ""}
{"code": 2030, "message": "Instagram not created", "payload": ""}
{"code": 2040, "message": "Instagram not updated", "payload": ""}
{"code": 2050, "message": "Instagram not deleted", "payload": ""}
{"code": 2060, "message": "Undefined action type", "payload": ""}
{"code": 2070, "message": "Instagram login failed", "payload": ""}
{"code": 2080, "message": "Instagram info fetching failed", "payload": ""}
{"code": 2090, "message": "Instagram account is inactive", "payload": ""}
{"code": 3010, "message": "User not found", "payload": ""}
{"code": 3030, "message": "User not created", "payload": ""}
{"code": 4010, "message": "Undefined action type", "payload": ""}
{"code": 4020, "message": "Error during channel action execution","payload": ""}
{"code": 4030, "message": "Undefined target type", "payload": ""}
{"code": 4040, "message": "Error during channel queue filling", "payload": ""}
{"code": 4050, "message": "Channel not found", "payload": ""}
{"code": 4060, "message": "Channel collection not found", "payload": ""}
{"code": 4070, "message": "Channel not created", "payload": ""}
{"code": 4080, "message": "Channel not updated", "payload": ""}
{"code": 4090, "message": "Channel not deleted", "payload": ""}
{"code": 4100, "message": "Empty action", "payload": ""}
{"code": 9999, "message": "Unknown error", "payload": ""}
```
#### HTTP 401 UNAUTHORIZED
```json
{ "code": 401, "message": "Incorrect Username / Password" }
{ "code": 401, "message": "auth header empty" }
{ "code": 401, "message": "signature is invalid" }
```
## Methods
#### POST /api/v1/login
###### Params
```json
Content-Type: application/json
{
"username": "<EMAIL>",
"password": "<PASSWORD>"
}
```
###### Response
```json
HTTP 200 OK
{
"expire": "2017-03-18T17:26:24+04:00",
"token": "xxx.xxx.xxx"
}
```
#### POST /api/v1/signup
###### Params
```json
Content-Type: application/json
{
"username": "<EMAIL>",
"password": "<PASSWORD>"
}
```
###### Response
```json
HTTP 200 OK
{
"id": "1",
"username": "<EMAIL>",
"created_at": "2017-01-21T13:18:32Z",
"updated_at": "2017-01-21T13:18:32Z"
}
```
#### GET /api/v1/user/refresh_token
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
{
"expire": "2017-03-18T17:34:30+04:00",
"token": "<PASSWORD>"
}
```
#### GET /api/v1/user
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<User>
```
#### POST /api/v1/instagrams/
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
{
"username": "instalogin",
"password": "<PASSWORD>",
"trusted": false,
"hours": {
"min": 7,
"max": 15
},
"speed": {
"like": 10,
"comment": 10,
"follow": 10,
"unfollow": 10
}
}
```
###### Response
```json
HTTP 200 OK
<Instagram>
```
#### GET /api/v1/instagrams/
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```
HTTP 200 OK
[
<Instagram_1>,
<Instagram_2>,
...
<Instagram_n>
]
```
#### GET /api/v1/instagrams/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Instagram>
```
#### GET /api/v1/instagrams/:id/stop
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Instagram>
```
#### GET /api/v1/instagrams/:id/start
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Instagram>
```
#### PUT /api/v1/instagrams/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
{
"username": "instalogin",
"password": "<PASSWORD>",
"trusted": false,
"hours": {
"min": 7,
"max": 15
},
"speed": {
"like": 10,
"comment": 10,
"follow": 10,
"unfollow": 10
}
}
```
###### Response
```json
HTTP 200 OK
<Instagram>
```
#### DELETE /api/v1/instagrams/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
{}
```
#### POST /api/v1/intagram/:instagram_id/channels
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
{
"action": "like",
"target": "followers",
"value": "natgeo",
"comments": []
}
```
###### Response
```json
HTTP 200 OK
<Channel>
```
#### GET /api/v1/instagram/:instagram_id/channels
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```
HTTP 200 OK
[
<Channel_1>,
<Channel_2>,
...
<Channel_n>
]
```
#### GET /api/v1/instagram/:instagram_id/channels/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Channel>
```
#### GET /api/v1/instagram/:instagram_id/channels/:id/stop
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Channel>
```
#### GET /api/v1/instagram/:instagram_id/channels/:id/start
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
<Channel>
```
#### PUT /api/v1/instagram/:instagram_id/channels/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
{
"action": "like",
"target": "followers",
"value": "natgeo",
"comments": []
}
```
###### Response
```json
HTTP 200 OK
<Channel>
```
#### DELETE /api/v1/instagram/:instagram_id/channels/:id
###### Params
```json
Content-Type: application/json
Authorization: Bearer xxx.xxx.xxx
```
###### Response
```json
HTTP 200 OK
{}
```
<file_sep>package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"massliking/backend/models"
"massliking/backend/workers"
)
func StartChannelHandler(c *gin.Context) {
_, channel, err := getChannel(c)
if err != nil {
OnError(err, c)
return
}
err = workers.StartChannel(channel)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channel)
}
func StopChannelHandler(c *gin.Context) {
_, channel, err := getChannel(c)
if err != nil {
OnError(err, c)
return
}
err = workers.StopChannel(channel)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channel)
}
func CreateChannelHandler(c *gin.Context) {
_, instagram, err := getInstagram(c)
if err != nil {
OnError(err, c)
return
}
creds := &models.ChannelCredentials{}
c.BindJSON(creds)
channel, err := instagram.CreateChannel(creds)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channel)
}
func FindChannelsHandler(c *gin.Context) {
_, channels, err := findChannels(c)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channels)
}
func GetChannelHandler(c *gin.Context) {
_, channel, err := getChannel(c)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channel)
}
func UpdateChannelHandler(c *gin.Context) {
instagram, channel, err := getChannel(c)
if err != nil {
OnError(err, c)
return
}
creds := &models.ChannelCredentials{}
c.BindJSON(creds)
channel, err = instagram.UpdateChannel(channel, creds)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, channel)
}
func DeleteChannelHandler(c *gin.Context) {
instagram, channel, err := getChannel(c)
if err != nil {
OnError(err, c)
return
}
err = instagram.DeleteChannel(channel)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, gin.H{})
}
<file_sep>package workers
import (
"math/rand"
"strconv"
"time"
. "massliking/backend/errors"
"massliking/backend/instabot"
"massliking/backend/logger"
"massliking/backend/models"
)
const MAX_TARGETS_PER_ONE_FILLING = 1000
const MIN_MEDIA_COUNT = 10
func FillQueue(c *models.Channel, client *instabot.Client, followings map[int]bool) error {
var err error
var users []*instabot.User
var targets []int
var leads map[int]bool
logInfo, logWarn, logError := logger.TaggedLoggers("workers/targets_collection", "FillQueue", c.IdString())
logInfo("Checking channel state...")
if c.State != models.CHANNEL_STATE_START {
logWarn("Exit due wrong channel state: " + c.State)
return nil
}
logInfo("Checking channel queue size...")
if len(c.Queue.Targets) > 0 {
logWarn("Channel queue is not empty")
return nil
}
logInfo("Looking for the next batch of targets")
switch c.Target {
case "followers":
users, err = FillQueueByFollowers(c, client)
case "subscriptions":
users, err = FillQueueBySubscriptions(c, client)
case "hashtag":
users, err = FillQueueByHashtag(c, client)
case "likes":
users, err = FillQueueByLikes(c, client)
case "comments":
users, err = FillQueueByComments(c, client)
default:
err = MODEL_CHANNEL_UNDEFINED_TARGET
}
if err != nil {
logError("Looking for the next batch of targets", err)
_ = StopChannel(c)
return err
}
logInfo("Targets amount: " + strconv.Itoa(len(users)))
// Looking for already processed targets
leads = c.Leads()
//TODO: We should somehow limit batch size
if len(users) > MAX_TARGETS_PER_ONE_FILLING {
users = users[:MAX_TARGETS_PER_ONE_FILLING]
}
logInfo("Iterating over users, filtering and updating queue...")
targets = filter(client, users, followings, leads)
logInfo("Updating channel targets...")
err = c.Save(func(c *models.Channel) {
c.Queue.Targets = append(c.Queue.Targets, targets...)
})
if err != nil {
logError("Updating channel targets...", err)
_ = StopChannel(c)
return err
}
return nil
}
func filter(client *instabot.Client, users []*instabot.User, followings map[int]bool, leads map[int]bool) []int {
targets := []int{}
for _, user := range users {
// Accept only public accounts
if user.IsPrivate == true {
continue
}
// Decline our leads
if leads[user.PK] == true {
continue
}
// Decline our followers
if followings[user.PK] == true {
continue
}
// Some magick delay to avoid HTTP 429
time.Sleep(time.Duration(1000+rand.Intn(1000)) * time.Millisecond)
// Fetch account info
response, err := client.SearchUsername(user.Username)
if err != nil {
continue
}
// Accept only real accounts, i.e. accounts with content
info := response.UserInfo
if info.MediaCount < MIN_MEDIA_COUNT {
continue
}
// Append account id into leads collection
leads[user.PK] = true
targets = append(targets, user.PK)
}
return targets
}
func FillQueueByFollowers(c *models.Channel, client *instabot.Client) ([]*instabot.User, error) {
var err error
users := []*instabot.User{}
info, err := client.SearchUsername(c.Value)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
pk := info.UserInfo.PK
followers, err := client.GetUserFollowers(pk, c.Queue.MaxId)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
err = c.Save(func(c *models.Channel) {
if followers.BigList != false {
c.Queue.MaxId = followers.NextMaxID
} else {
c.Queue.MaxId = ""
c.State = models.CHANNEL_STATE_EMPTY
}
})
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
return followers.Users, nil
}
func FillQueueBySubscriptions(c *models.Channel, client *instabot.Client) ([]*instabot.User, error) {
var err error
users := []*instabot.User{}
info, err := client.SearchUsername(c.Value)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
pk := info.UserInfo.PK
subscriptions, err := client.GetUserFollowings(pk, c.Queue.MaxId)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
err = c.Save(func(c *models.Channel) {
if subscriptions.BigList != false {
c.Queue.MaxId = subscriptions.NextMaxID
} else {
c.Queue.MaxId = ""
c.State = models.CHANNEL_STATE_EMPTY
}
})
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
return subscriptions.Users, nil
}
func FillQueueByHashtag(c *models.Channel, client *instabot.Client) ([]*instabot.User, error) {
var err error
users := []*instabot.User{}
feed, err := client.GetHashtagFeed(c.Value, c.Queue.MaxId)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
err = c.Save(func(c *models.Channel) {
if feed.MoreAvailable != false {
c.Queue.MaxId = feed.NextMaxID
} else {
c.Queue.MaxId = ""
c.State = models.CHANNEL_STATE_EMPTY
}
})
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
for _, item := range feed.Items {
users = append(users, item.User)
}
return users, nil
}
func FillQueueByLikes(c *models.Channel, client *instabot.Client) ([]*instabot.User, error) {
users := []*instabot.User{}
info, err := client.SearchUsername(c.Value)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
pk := info.UserInfo.PK
// Looking for posts of the last year
t := time.Now().AddDate(-1, 0, 0).Unix()
feed, err := client.GetUserFeed(pk, c.Queue.MaxId, t)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
err = c.Save(func(c *models.Channel) {
if feed.MoreAvailable != false {
c.Queue.MaxId = feed.NextMaxID
} else {
c.Queue.MaxId = ""
c.State = models.CHANNEL_STATE_EMPTY
}
})
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
//TODO: Skip likes pagination for now
for _, item := range feed.Items {
if item.LikeCount == 0 {
continue
}
likes, err := client.GetMediaLikers(item.PK, "")
if err != nil {
continue
}
if likes.UserCount == 0 {
continue
}
users = append(users, likes.Users...)
}
return users, nil
}
func FillQueueByComments(c *models.Channel, client *instabot.Client) ([]*instabot.User, error) {
users := []*instabot.User{}
info, err := client.SearchUsername(c.Value)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
pk := info.UserInfo.PK
// Looking for posts of the last year
t := time.Now().AddDate(-1, 0, 0).Unix()
feed, err := client.GetUserFeed(pk, c.Queue.MaxId, t)
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
err = c.Save(func(c *models.Channel) {
if feed.MoreAvailable != false {
c.Queue.MaxId = feed.NextMaxID
} else {
c.Queue.MaxId = ""
c.State = models.CHANNEL_STATE_EMPTY
}
})
if err != nil {
return users, On(err, MODEL_CHANNEL_ACTION_ERROR)
}
//TODO: Skip comments pagination for now
for _, item := range feed.Items {
if item.LikeCount == 0 {
continue
}
comments, err := client.GetMediaComments(item.PK, "")
if err != nil {
continue
}
if comments.CommentCount == 0 {
continue
}
for _, comment := range comments.Comments {
users = append(users, comment.User)
}
}
return users, nil
}
<file_sep>package models
import (
"strconv"
"time"
"massliking/backend/config"
. "massliking/backend/errors"
"massliking/backend/instabot"
)
var INSTAGRAM_REGISTRY map[int64]*WorkersPool = map[int64]*WorkersPool{}
const INSTAGRAM_STATE_STOP = "stop"
const INSTAGRAM_STATE_START = "start"
const INSTAGRAM_STATE_SUSPECTED = "suspected"
type WorkersPool struct {
WriteOpCh chan *InstagramWriteOp
InstagramCommandCh chan string
StatsCommandCh chan string
ChannelCommandChs map[string]chan string
}
type InstagramReadOp struct {
Error error
}
type InstagramWriteOp struct {
Instagram *Instagram
Callback func(i *Instagram)
ReadChannel chan *InstagramReadOp
}
type Limits struct {
Like int
Comment int
Follow int
Unfollow int
}
type Speed struct {
Like int `json:"like"`
Comment int `json:"comment"`
Follow int `json:"follow"`
Unfollow int `json:"unfollow"`
}
type Counters struct {
Like int
Comment int
Follow int
Unfollow int
StartedAt time.Time
}
type Hours struct {
Min int `json:"min"`
Max int `json:"max"`
}
//TODO: Add FollowersCount field for summary over the channels
type Instagram struct {
Id int64 `json:"id" xorm:"pk autoincr index"`
UserId int64 `json:"-" xorm:"index"`
Info *instabot.UserInfo `json:"info" xorm:"jsonb"`
State string `json:"state" xorm:"varchar(250) notnull default 'stop'"`
Username string `json:"username" xorm:"notnull index"`
Password string `json:"<PASSWORD>" xorm:"varchar(250) notnull"`
Trusted bool `json:"trusted" xorm:"bool notnull default false"`
*Hours `json:"hours" xorm:"jsonb"`
*Speed `json:"speed" xorm:"jsonb"`
*Counters `json:"-" xorm:"jsonb"`
Version int `json:"-" xorm:"version"`
CreatedAt time.Time `json:"created_at" xorm:"created"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated"`
}
func (i *Instagram) IdString() string {
return strconv.FormatInt(i.Id, 10)
}
func (i *Instagram) Save(callback func(i *Instagram)) error {
// Check account in the registry
if INSTAGRAM_REGISTRY[i.Id] == nil {
return MODEL_INSTAGRAM_NOT_FOUND
}
// Create message for async processing
writeOp := &InstagramWriteOp{
Instagram: i,
Callback: callback,
ReadChannel: make(chan *InstagramReadOp),
}
// Send message to goroutine
INSTAGRAM_REGISTRY[i.Id].WriteOpCh <- writeOp
// Call SyncSave inside goroutine and read response
readOp := <-writeOp.ReadChannel
// Return response
return readOp.Error
}
func (i *Instagram) SyncSave(callback func(i *Instagram)) error {
var err error
user, err := i.User()
if err != nil {
return err
}
instagram, err := GetInstagram(user, i.Id)
if err != nil {
return err
}
// Look ma, no hands!
*i = *instagram
callback(i)
instagram, err = UpdateInstagramById(i)
if err != nil {
return err
}
return nil
}
func (i *Instagram) FindLimits() *Limits {
key := ""
if i.Trusted {
key = "trusted"
} else {
key = "non_trusted"
}
return &Limits{
Like: config.GetInt("limits." + key + ".likes"),
Comment: config.GetInt("limits." + key + ".comments"),
Follow: config.GetInt("limits." + key + ".follows"),
Unfollow: config.GetInt("limits." + key + ".unfollows"),
}
}
func (i *Instagram) CheckLimits(action string) bool {
var err error
duration := time.Since(i.Counters.StartedAt)
if duration >= time.Hour*time.Duration(24) {
err = i.Save(func(instagram *Instagram) {
i.Counters = &Counters{
Like: 0,
Comment: 0,
Follow: 0,
Unfollow: 0,
StartedAt: time.Now(),
}
})
if err != nil {
return false
}
return true
}
limits := i.FindLimits()
switch action {
case "like":
if i.Counters.Like >= limits.Like {
return false
}
case "comment":
if i.Counters.Comment >= limits.Comment {
return false
}
case "follow":
if i.Counters.Follow >= limits.Follow {
return false
}
case "unfollow":
if i.Counters.Unfollow >= limits.Unfollow {
return false
}
default:
return false
}
return true
}
func (i *Instagram) ActionSpeed(action string) int {
var speed int
switch action {
case "like":
speed = i.Speed.Like
case "comment":
speed = i.Speed.Comment
case "follow":
speed = i.Speed.Follow
case "unfollow":
speed = i.Speed.Unfollow
default:
speed = 1
}
if speed <= 0 {
speed = 1
}
return speed
}
func (i *Instagram) UpdateLimits(action string) error {
var err error
err = i.Save(func(i *Instagram) {
switch action {
case "like":
i.Counters.Like += 1
case "comment":
i.Counters.Comment += 1
case "follow":
i.Counters.Follow += 1
case "unfollow":
i.Counters.Unfollow += 1
default:
//TODO: Process undefined action
}
})
if err != nil {
return err
}
return nil
}
func (i *Instagram) UpdateInfo(client *instabot.Client) error {
info, err := client.SearchUsername(i.Username)
if err != nil {
return On(err, MODEL_INSTAGRAM_INFO_ERROR)
}
err = i.Save(func(i *Instagram) {
i.Info = info.UserInfo
})
if err != nil {
return On(err, MODEL_INSTAGRAM_INFO_ERROR)
}
return nil
}
func (i *Instagram) User() (*User, error) {
var err error
user := &User{}
_, err = Engine.Id(i.UserId).Get(user)
return user, On(err, MODEL_USER_NOT_FOUND)
}
func (i *Instagram) ValidateState(client *instabot.Client) error {
var err error
user, err := i.User()
if err != nil {
return err
}
// Check account presence
instagram, err := GetInstagram(user, i.Id)
if err != nil {
return On(err, MODEL_INSTAGRAM_NOT_FOUND)
}
// Look ma, no hands!
*i = *instagram
// Check client validity
if client.Suspected {
err = i.Save(func(i *Instagram) {
i.State = INSTAGRAM_STATE_SUSPECTED
})
if err != nil {
return On(err, MODEL_INSTAGRAM_NOT_UPDATED)
}
}
// Check account state
if i.State != INSTAGRAM_STATE_START {
return MODEL_INSTAGRAM_INACTIVE_ERROR
}
return nil
}
<file_sep># Instagram limits
## Articles
- [Instagram Limits and Strategies](http://www.androidtipster.com/instagram-limits)
- [Instagram Rules and Restrictions: Limits for Likes, Followers and Comments](https://elfsight.com/blog/2016/12/instagram-restrictions-limits-likes-followers-comments)
## Important factors
- Age of Instagram account
- Size – Number of followers
- Overall engagement (commenting, liking)
- Active/inactive accounts
## New account
#### Total limit
- Maximum 500 actions per day
- One action with the interval of 36-48 seconds (75-100 per hour)
#### Followers limit
- 300 – 350 per day for the first week
- Increase that limit by between 50-70 every week
- Activity of 5-6 hours per day
#### Likes limit
- 1.5x from the followers limit
#### Comments limit
- Maximum 250 per day
#### Publishing images
- Maximum 2-3 per day
## Trusted account (> ~3 months)
#### Total limit
- Maximum 1000 actions per day
#### Followers limit
- One action with the interval of 28-36 seconds (100-128 per hour)
- Maximum 200 per hour
- Maximum 1000 per day
#### Likes limit
- One action with the interval of 28-36 seconds (100-128 per hour)
- Maximum 1000 per day
#### Followers + Likes limit
- One action with the interval of 28-38 seconds (94-128 per hour)
- Maximum 2000 per day (1000 + 1000)
#### Unfollow limit
- One action with the interval of 12-22 seconds (163-300 per hour)
- Maximum 1000 per day
#### Mentions limit
- 5 nicks in a message with the interval of 350-450 seconds
#### Comments limit
- No more than 12-14 an hour with the interval of 350-400 seconds
#### Publishing images
- Maximum 9-12 per day
<file_sep>module.exports = {
NODE_ENV: '"development"',
API_URL: '"http://localhost:8080/api/v1/"',
BUILD_DIR: 'targets/develop',
DEBUG_MODE: true,
}
<file_sep>module.exports = {
NODE_ENV: '"production"',
API_URL: '"http://massliking.com/api/v1/"',
BUILD_DIR: 'targets/release',
DEBUG_MODE: false,
}
<file_sep>package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"massliking/backend/models"
)
func SignupHandler(c *gin.Context) {
creds := &models.Credentials{}
c.BindJSON(creds)
user, err := models.CreateUser(creds)
if err != nil {
OnError(err, c)
return
}
c.JSON(http.StatusOK, user)
}
<file_sep>import auth from './auth'
const API_URL = process.env.API_URL
const USER_GET_URL = API_URL + 'user'
export default {
isEmpty (context) {
return Object.keys(context.$store.state.user).length === 0
},
updateUser (context) {
context.$http.get(USER_GET_URL, {headers: auth.getAuthHeader()})
.then(response => {
context.$store.commit('updateUser', { user: response.body })
}, error => {
if (error.status === 401) {
auth.logout(context, '/')
}
})
}
}
|
27c2b88cf83bd15af0e8a38f590b57609cab4d4d
|
[
"JavaScript",
"Go",
"Markdown",
"Shell"
] | 50
|
Go
|
dsaveliev/massliking
|
09ac2546595106620e9c563397d4cd4e8fc759e9
|
943f03d0f8725cf2457abd8bd9a810a1a3635d3c
|
refs/heads/master
|
<file_sep>$(document).ready(function(){
$('input[type="submit"]').click(function(){
var accessCode = $('#accessCode').val()
if(accessCode.length > 0) {
$('form').attr('action', '/loopback/comment/code')
}
return true;
})
});
|
cbf35450a124f03e6d949e8f254947f495eec741
|
[
"JavaScript"
] | 1
|
JavaScript
|
zanthrash/loopback
|
72366e20acc1efaa03a99e8e773394dc504b7656
|
d7b6765bde3f0bd18839a58bbf6934889d51dcb5
|
refs/heads/master
|
<repo_name>tindang17/LoL-Stat<file_sep>/client/src/store/actions/actions.js
export const SET_MATCHES = 'SET_MATCHES';
export const REQUEST_MATCHES = 'REQUEST_MATCHES';
export function getSummonerMatches(query) {
return dispatch => {
dispatch(requestMatches())
return fetch(`/api/summoner?name=${query}`, {
accept: "application/json"
})
.then(response => response.json())
.then(results => dispatch(setMatches(results)))
.catch(err => console.log(err))
}
}
export function requestMatches() {
return {
type: REQUEST_MATCHES
}
}
export function setMatches(matches) {
return {
type: SET_MATCHES,
matches
};
}
<file_sep>/db/migrations/20171129162923_matches.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('matches', table => {
table.increments('id');
table.integer('match_id');
table.boolean('win');
table.integer('kill');
table.integer('death');
table.integer('assist');
table.integer('game_length');
table.integer('creep_score')
table.integer('champion_id').unsigned();
table.foreign('champion_id').references('champions.champion_id');
table.integer('summoner_id').unsigned();
table.foreign('summoner_id').references('summoners.summoner_id');
});
};
exports.down = function(knex, Promise) {
return knex.raw('drop table matches cascade');
};
<file_sep>/db/migrations/20171129172455_summoners.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('summoners', table => {
table.increments('id');
table.string('name');
table.integer('summoner_id');
table.integer('level');
table.integer('account_id');
})
};
exports.down = function(knex, Promise) {
return knex.raw('drop table champions cascade');
};
<file_sep>/client/src/store/components/GetSummonerMatches.jsx
import React from 'react';
import { connect } from 'react-redux';
import { getSummonerMatches } from '../actions/actions';
let GetSummonerMatches = ({ dispatch }) => {
let input;
return <section className="inputForm">
<form style={{ marginTop: 15 }} onSubmit={e => {
e.preventDefault();
if (!input.value.trim()) {
return;
}
dispatch(getSummonerMatches(input.value));
input.value = "";
}}>
<label>Enter the summoner's name</label>
<input ref={node => {
input = node;
}} required="true" />
<button type="submit">Click</button>
</form>
</section>;
}
GetSummonerMatches = connect()(GetSummonerMatches);
export default GetSummonerMatches;<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
A personal project that make api call to Riot API to get League of Legends data.
Stacks:
Node.js, Express.js, React.js and Redux.
You can check out my app at lolstatsproject.herokuapp.com
To try out the app. Type <NAME> or your LoL summoner name into the input field.
<file_sep>/client/src/App.js
import React, { Component } from 'react';
import './App.css';
import GetSummonerMatches from './store/components/GetSummonerMatches';
import MatchList from './store/components/MatchList';
import Loading from './Loading';
import { connect } from "react-redux";
// import Loading from './Loading';
class App extends Component {
render() {
const { isFetching, items } = this.props.matches;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Look up the summoner that you want</h1>
</header>
<GetSummonerMatches />
{ isFetching ? <Loading /> : <MatchList matches = {items}/> }
</div>
);
}
}
const mapStateToProps = ({ matches }) => ({
matches
});
export default connect(mapStateToProps)(App);
<file_sep>/client/src/store/components/MatchList.js
import React, { Fragment } from 'react';
import SummonerInfo from './SummonerInfo';
import Match from './Match';
const MatchList = (props) => {
const {matches} = props;
let name;
let level;
if (matches[matches.length - 1]!== undefined) {
name = matches[0].summonerName;
level = `Level: ${matches[0].summonerLevel}`;
} else {
name = '';
level = '';
}
return (
<Fragment>
<SummonerInfo info={{name, level}} />
<div id='match-list' className='col-md-6'>
{matches.map(match => {
return (
<section style={{ 'display': 'inline-block', 'verticalAlign': 'text-top' }} key={match.gameId}>{Match(match)}</section>
)})
}
</div>
</Fragment>
);
}
export default MatchList;<file_sep>/server.js
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const request = require("request");
const rp = require("request-promise");
const ENV = process.env.ENV || "development";
const PORT = process.env.PORT || 3001;
const path = require('path');
const API_KEY =
process.env.API_KEY;
//helper-functions
const getData = require("./helper-functions/getData");
const getStaticData = require("./helper-functions/getStaticData");
const getPlayerStatOfMatch = require("./helper-functions/getPlayerStatOfMatch");
// middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.resolve(__dirname, './client/build')));
class HttpError extends Error {
constructor(response) {
super(`${response.status} for ${response.url}`);
this.name = "HttpError";
this.response = response;
}
}
/*
The function filteredData's job is the first step of extracting the nested data in the object.
First it will compare the summoner name in the participantsIdentities object with the playerName
that is provided to it. If the name match, the participant Id will be returned.
The participant Id will be used as the reference point to extract other info.
We then call the getPlayerStatOfMatch callback to get the player stat of the particular match.
*/
function filteredData(
playerName,
match,
cb,
items,
champions,
spells,
summonerLevel,
gameId
) {
const { participantIdentities } = match;
const { participants } = match;
const { gameDuration } = match;
let id;
for (let info of participantIdentities) {
if (info.player.summonerName === playerName) {
id = info.participantId;
break;
}
}
let result = cb(
id,
participants,
items,
champions,
spells,
gameDuration,
summonerLevel,
playerName,
gameId
);
return result;
}
app.get("/api/summoner", async (req, res) => {
// get data from client
let { name } = req.query;
let results = [];
let items = await getStaticData(
`https://na1.api.riotgames.com/lol/static-data/v3/items?locale=en_US&itemListData=image&api_key=${
API_KEY
}`,
HttpError
);
// get spells
let spells = await getStaticData(
`https://na1.api.riotgames.com/lol/static-data/v3/summoner-spells?locale=en_US&spellListData=image&dataById=false&api_key=${
API_KEY
}`,
HttpError
);
// get champions
let champions = await getStaticData(
`https://na1.api.riotgames.com/lol/static-data/v3/champions?locale=en_US&championListData=image&dataById=false&api_key=${
API_KEY
}`,
HttpError
);
//get summoner
const summoner = await getData(
`https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/${
name
}?api_key=${API_KEY}`,
HttpError
);
let { name: summonerName, summonerLevel } = summoner;
const { accountId } = summoner;
//get match details
const latestMatches = await getData(
`https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/${
accountId
}/recent?api_key=${API_KEY}`,
HttpError
);
const { matches } = latestMatches;
let detail;
let gameId;
// The gameId is assigned value inside the loop so that we can get multiple game ids.
for (let i = 0; i <= 3; i++) {
gameId = matches[i].gameId;
detail = await getData(
`https://na1.api.riotgames.com/lol/match/v3/matches/${
gameId
}?api_key=${API_KEY}`,
HttpError
);
results.push(
filteredData(
summonerName,
detail,
getPlayerStatOfMatch,
items,
champions,
spells,
summonerLevel,
gameId
)
);
}
res.json(results).status(200);
});
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, './client/build', 'index.html'));
});
app.listen(PORT, () => {
console.log("server is running on port 3001");
});<file_sep>/client/src/store/components/SummonerInfo.js
import React from "react";
const SummonerInfo = props => (
<div className="summoner">
<span>{props.info.name}</span>
<span>{props.info.level}</span>
</div>
);
export default SummonerInfo;
<file_sep>/client/src/store/reducers/matches.js
import { SET_MATCHES } from '../actions/actions';
import { REQUEST_MATCHES } from '../actions/actions';
const matches = (state = {isFetching: false, items: []}, action) => {
switch (action.type) {
case SET_MATCHES:
return Object.assign({}, state, {
isFetching: false,
items: action.matches
});
case REQUEST_MATCHES:
return Object.assign({}, state, {
isFetching: true
});
default:
return state;
}
}
export default matches;
|
7ef8c8df0ccbdf9e3339a886b6a5442c588fe26d
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
tindang17/LoL-Stat
|
aab31ee460a17cafc549af9335e7a4fb10cc6304
|
95262c5f456cd6b6dd9ce8c0733b996f514f6921
|
refs/heads/master
|
<file_sep>/*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>
#include <bb/data/SqlDataAccess>
using namespace bb::cascades;
using namespace bb::data;
ApplicationUI::ApplicationUI() :
QObject()
{
// prepare the localization
m_pTranslator = new QTranslator(this);
m_pLocaleHandler = new LocaleHandler(this);
bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this,
SLOT(onSystemLanguageChanged()));
// This is only available in Debug builds
Q_ASSERT(res);
// Since the variable is not used in the app, this is added to avoid a
// compiler warning
Q_UNUSED(res);
// initial load
onSystemLanguageChanged();
// Create scene document from main.qml asset, the parent is set
// to ensure the document gets destroyed properly at shut down.
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
qml->setContextProperty("nicobrowser", this);
// Create root object for the UI
AbstractPane *root = qml->createRootObject<AbstractPane>();
// Set created root object as the application scene
Application::instance()->setScene(root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(m_pTranslator);
// Initiate, load and install the application translation files.
QString locale_string = QLocale().name();
QString file_name = QString("NicoBrowser_%1").arg(locale_string);
if (m_pTranslator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(m_pTranslator);
}
}
bool ApplicationUI::initDatabase(bool forceInit)
{
QString srcDBPath = QDir::currentPath() + "/app/native/assets/" + "/nbsetting.db";
QString destDBPath = QDir::currentPath() + "/data/" + "nbsetting.db";
if (QFile::exists(destDBPath)) {
qDebug() << "database exist in data dir";
if (forceInit) {
QFile::remove(destDBPath);
if (QFile::exists(destDBPath)) {
qDebug() << "can't remove database in data dir";
} else {
qDebug() << "remove old database success";
}
}
}
//create own dir
QDir dir; // New QDir objects default to the application working directory.
dir.mkpath(QDir::currentPath() + "/shared/documents/nicobrowser");
if (QFile::copy(srcDBPath, destDBPath)) {
return true;
} else {
return false;
}
}
QUrl ApplicationUI::getDatabasePath()
{
QString destDBPath = QDir::currentPath() + "/data/" + "nbsetting.db";
return QUrl(destDBPath);
}
bool ApplicationUI::importBookmark()
{
QString filePath = QDir::currentPath() + "/shared/documents/nicobrowser/"
+ "nicobrowser_bookmark.txt";
QFile textfile(filePath);
SqlDataAccess sda(this->getDatabasePath().toString());
if (textfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&textfile);
QString line;
do {
line = stream.readLine();
//qDebug() << line;
QStringList list = line.split(",");
if(list.size()>1){
sda.execute("insert into bookmark (title, address) values ('"+list[0]+"','"+list[1]+"')");
//qDebug()<<list[0]<<list[1];
}
} while (!line.isNull());
}
textfile.close();
return true;
}
bool ApplicationUI::exportBookmark()
{
SqlDataAccess sda(this->getDatabasePath().toString());
QVariant result = sda.execute("select * from bookmark");
QVariantList list = result.value<QVariantList>();
QString filePath = QDir::currentPath() + "/shared/documents/nicobrowser/"
+ "nicobrowser_bookmark.txt";
QFile textfile(filePath);
textfile.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream fout(&textfile);
for (int i = 0; i < list.count(); i++) {
//qDebug() << list[i].toMap()["title"].toString() << "," << list[i].toMap()["address"].toString() ;
fout << list[i].toMap()["title"].toString() << "," << list[i].toMap()["address"].toString()
<< "\n";
}
textfile.close();
//QString extPath = QDir::currentPath() + "/shared/documents/" + "nicobrowser_bookmark.txt";
//qDebug() << filePath <<"\n"<< extPath;
// if (QFile::copy(filePath, extPath)) {
// return true;
// } else {
// return false;
// }
return true;
}
|
4573b119f91964cfa97ee1baeb7a5ac055b08f8b
|
[
"C++"
] | 1
|
C++
|
michaelhxf/NicoBrowser
|
e2ccb8c220ab0559778fca317e266ecbe52fce12
|
0ae7538666291125da89cc45fa6888baecb0ba05
|
refs/heads/master
|
<repo_name>mameg725/anilova<file_sep>/app/controllers/public/users_controller.rb
# frozen_string_literal: true
class Public::UsersController < ApplicationController
before_action :login_user, only: %i[edit update mypage create]
def show
@user = User.friendly.find(params[:id])
end
def mypage
@post = Post.new
@user = User.friendly.find(params[:id])
end
def edit
@user = User.friendly.find(params[:id])
end
def favoindex
@me = current_user
@post = Post.new
@user = User.friendly.find(params[:id])
@favorites = Favorite.where(user_id: @user.id)
end
def followpost
@me = User.friendly.find(params[:id])
@post = Post.new
@user = User.friendly.find(params[:id])
@follows = @user.following_user
end
def update
@user = User.friendly.find(params[:id])
if @user.update(user_params)
redirect_to users_mypage_path(current_user.friendly_id)
else
redirect_to request.referer, notice: "編集に失敗しました。"
end
end
def destroy
@user = User.friendly.find(params[:id])
@user.destroy
redirect_to "/"
end
private
def user_params
params.require(:user).permit(:name, :icon_image, :introduction, :website, :friendly_id)
end
def login_user
@user = User.friendly.find(params[:id])
redirect_to "/" unless @user.id == current_user.id
end
end
<file_sep>/spec/controllers/users/users_controller_spec.rb
require 'rails_helper'
describe 'ユーザーテスト' do
describe '新規登録' do
before do
visit "/users/sign_up"
end
context '新規登録画面に遷移' do
it '新規登録に成功' do
fill_in 'user[name]', with: Faker::Lorem.characters(number: 5)
fill_in 'user[friendly_url]', with: Faker::Lorem.characters(number: 5)
fill_in 'user[email]', with: Faker::Internet.email
fill_in 'user[password]', with: '<PASSWORD>'
fill_in 'user[password_confirmation]', with: '<PASSWORD>'
click_button 'Sign up'
end
it '新規登録に失敗する' do
fill_in 'user[name]', with: ''
fill_in 'user[friendly_url]', with: ''
fill_in 'user[email]', with: ''
fill_in 'user[password]', with: ''
fill_in 'user[password_confirmation]', with: ''
click_button 'Sign up'
end
end
end
describe 'ログイン画面' do
before do
visit "/users/sign_in"
@user = build(:user)
end
context 'ログイン画面に遷移' do
it 'ログインに成功' do
fill_in 'user[friendly_url]', with: @user.friendly_url
fill_in 'user[password]', with: <PASSWORD>
click_button 'Log in'
end
it 'ログインに失敗する' do
fill_in 'user[friendly_url]', with: ''
fill_in 'user[password]', with: ''
click_button 'Log in'
end
end
end
end<file_sep>/app/models/news.rb
# frozen_string_literal: true
class News < ApplicationRecord
has_many :notices, dependent: :destroy
belongs_to :user
validates :title, length: { in: 10..20, message: "10~20字までで入力してください。" }
validates :news_text, length: { in: 10..1000, message: "10~1000字までで入力してください。" }
end
<file_sep>/spec/models/users_spec.rb
require 'rails_helper'
RSpec.describe "Userモデルのテスト", type: :model do
before do
@user = build(:user)
end
describe 'バリデーションテスト' do
context 'nameカラム' do
it 'nameが空だとNG' do
@user.name = ''
# is_expected.to eq false;
expect(@user.valid?).to eq(false)
end
it '1文字以上であること' do
@user.name = Faker::Lorem.characters(number: 0)
expect(@user.valid?).to eq(false)
end
it '10文字以下であること' do
@user.name = Faker::Lorem.characters(number: 11)
expect(@user.valid?).to eq(false)
end
end
context 'friendly_urlカラム' do
it 'friendly_urlが空だとNG' do
@user.friendly_url = ''
expect(@user.valid?).to eq(false)
end
it '3文字以上であること' do
@user.friendly_url = Faker::Lorem.characters(number: 0)
expect(@user.valid?).to eq(false)
end
it '10文字以下であること' do
@user.friendly_url = Faker::Lorem.characters(number: 11)
expect(@user.valid?).to eq(false)
end
end
context 'introductionカラム' do
it '100文字以下であること' do
@user.introduction = Faker::Lorem.characters(number: 101)
expect(@user.valid?).to eq(false)
end
end
end
describe 'アソシエーション' do
context 'Post' do
it '1:Nか' do
expect(User.reflect_on_association(:posts).macro).to eq :has_many
end
end
context 'PostComment' do
it '1:Nか' do
expect(User.reflect_on_association(:post_comments).macro).to eq :has_many
end
end
context 'Favorite' do
it '1:Nか' do
expect(User.reflect_on_association(:favorites).macro).to eq :has_many
end
end
context 'News' do
it '1:Nか' do
expect(User.reflect_on_association(:news).macro).to eq :has_many
end
end
end
end
<file_sep>/spec/models/relationships_spec.rb
require 'rails_helper'
RSpec.describe "Relationshipモデルのテスト", type: :model do
before do
@relationship = build(:relationship)
end
describe 'アソシエーション' do
context 'Follower' do
it 'N:1か' do
expect(Relationship.reflect_on_association(:follower).macro).to eq :belongs_to
end
end
context 'Followed' do
it 'N:1か' do
expect(Relationship.reflect_on_association(:followed).macro).to eq :belongs_to
end
end
end
end
<file_sep>/spec/controllers/owner/owner_controllor_spec.rb
require 'rails_helper'
describe 'ユーザーテスト' do
describe 'ログイン画面' do
before do
visit "/owners/sign_in"
@owner = build(:owner)
end
context 'ログイン画面に遷移' do
it 'ログインに成功' do
fill_in 'owner[email]', with: @owner.email
fill_in 'owner[password]', with: <PASSWORD>
click_button 'Log in'
end
it 'ログインに失敗する' do
fill_in 'owner[email]', with: ''
fill_in 'owner[password]', with: ''
click_button 'Log in'
end
end
end
end<file_sep>/app/controllers/admin/users_controller.rb
# frozen_string_literal: true
class Admin::UsersController < ApplicationController
before_action :authenticate_owner!
def top
@posts = Post.all.order("id DESC")
end
def index
@users = User.with_deleted.order("id DESC")
end
def show
@user = User.friendly.with_deleted.find(params[:id])
end
end
<file_sep>/app/helpers/public/searches_helper.rb
# frozen_string_literal: true
module Public::SearchesHelper
end
<file_sep>/spec/models/favorites_spec.rb
require 'rails_helper'
RSpec.describe "Newsモデルのテスト", type: :model do
before do
@news = build(:news)
end
describe 'アソシエーション' do
context 'User' do
it 'N:1か' do
expect(Favorite.reflect_on_association(:user).macro).to eq :belongs_to
end
end
context 'Post' do
it 'N:1か' do
expect(Favorite.reflect_on_association(:post).macro).to eq :belongs_to
end
end
end
end
<file_sep>/app/controllers/admin/posts_controller.rb
# frozen_string_literal: true
class Admin::PostsController < ApplicationController
before_action :authenticate_owner!
def index
@posts = Post.all.order("id DESC")
@posts = @posts.tagged_with(params[:tag_name].to_s) if params[:tag_name]
end
def show
@user = User.friendly.find(params[:id])
@post = Post.find(params[:id])
@post_comments = @post.post_comments
end
end
<file_sep>/app/controllers/public/newss_controller.rb
# frozen_string_literal: true
class Public::NewssController < ApplicationController
before_action :login_user, only: [:message]
def index
@messages = News.where(user_id: 1).order("id DESC")
end
def message
@messages = News.where(user_id: current_user.id).or(News.where(user_id: nil))
end
def show
@news = News.find(params[:id])
end
private
def login_user
@user = User.friendly.find(params[:id])
redirect_to "/" unless @user.id == current_user.id
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Owner.create!(
email: "<EMAIL>",
password: "<PASSWORD>"
)
User.create!([
{
name: "Anilova",
friendly_url: "anilova",
introduction: "管理者用ユーザー",
website: "http://18.216.190.125/",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
name: "まめ",
friendly_url: "mame",
introduction: "にゃんこ最高!",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
name: "ぽち",
friendly_url: "pochi",
introduction: "犬が好きです。",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
name: "たま",
friendly_url: "tama",
introduction: "猫大好き。",
email: "<EMAIL>",
password: "<PASSWORD>"
}]
)
<file_sep>/app/models/post.rb
# frozen_string_literal: true
class Post < ApplicationRecord
has_many :post_comments, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :notices, dependent: :destroy
belongs_to :user
validates :murmur, length: { maximum: 200, message: "200字までで入力してください。" }
validates :dopost, presence: true
acts_as_taggable
attachment :post_image
def favorite_by?(user)
favorites.where(user_id: user.id).exists?
end
def created_notice_favorite!(current_user)
tmp = Notice.where(["visitor_id = ? & visited_id = ? & post_id = ? & action = ?", current_user.id, user_id, id, "favorite"])
if tmp.blank?
notice = current_user.active_notice.new(
post_id: id,
visited_id: user_id,
action: "favorite"
)
notice.checked = true if notice.visitor_id == notice.visited_id
notice.save if notice.valid?
end
end
def created_notice_comment!(current_user, post_comment_id)
tmp_ids = PostComment.select(:user_id).where(post_id: id).where.not(user_id: current_user.id).distinct
tmp_ids.each do |tmp_id|
save_notice_comment!(current_user, post_comment_id, tmp_id["user_id"])
end
save_notice_comment!(current_user, post_comment_id, user_id) if tmp_ids.blank?
end
def save_notice_comment!(current_user, post_comment_id, visited_id)
notice = current_user.active_notice.new(
post_id: id,
post_comment_id: post_comment_id,
visited_id: visited_id,
action: "comment"
)
notice.checked = true if notice.visitor_id == notice.visited_id
notice.save if notice.valid?
end
private
def dopost
murmur.presence || post_image_id.presence
end
end
<file_sep>/app/controllers/public/notices_controller.rb
# frozen_string_literal: true
class Public::NoticesController < ApplicationController
before_action :authenticate_user!
def index
@notice = Notice.where.not(visitor_id: current_user.id).order("id DESC")
end
end
<file_sep>/app/controllers/admin/messages_controller.rb
# frozen_string_literal: true
class Admin::MessagesController < ApplicationController
before_action :authenticate_owner!
def index
@messages = News.where.not(user_id: 1)
@message = News.new
end
def show
@user = User.friendly.with_deleted.find(params[:id])
@messages = @user.news.all
@message = News.new
end
def create
@message = News.new(news_params)
if @message.save
@notice = Notice.new
@notice.visitor_id = 1
@notice.visited_id = @message.user_id
@notice.news_id = @message.id
@notice.action = "news"
@notice.save
else
redirect_to request.referer, notice: "メッセージの作成に失敗しました。"
end
end
private
def news_params
params.require(:news).permit(:news_text, :title, :user_id)
end
end
<file_sep>/app/models/post_comment.rb
# frozen_string_literal: true
class PostComment < ApplicationRecord
has_many :notices, dependent: :destroy
belongs_to :user
belongs_to :post
validates :reaction, length: { maximum: 100, message: "100字までで入力してください。" }
end
<file_sep>/spec/factories/notices.rb
FactoryBot.define do
factory :notice do
end
end
<file_sep>/app/helpers/admin/newss_helper.rb
# frozen_string_literal: true
module Admin::NewssHelper
end
<file_sep>/db/migrate/20200212055757_create_notices.rb
class CreateNotices < ActiveRecord::Migration[5.2]
def change
create_table :notices do |t|
t.timestamps
t.integer :visitor_id
t.integer :visited_id
t.integer :post_id
t.integer :post_comment_id
t.integer :news_id
t.string :action
t.boolean :checked
end
add_index :notices, :visitor_id
add_index :notices, :visited_id
add_index :notices, :post_id
add_index :notices, :post_comment_id
add_index :notices, :news_id
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
sessions: 'users/sessions',
passwords: '<PASSWORD>',
registrations: 'users/registrations'
}
devise_for :owners, controllers: {
sessions: 'owners/sessions',
passwords: '<PASSWORD>',
registrations: 'owners/registrations'
}
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root "public/posts#index"
scope module: "public" do
resources :users, only: [:mypage, :show, :favoindex, :followpost, :edit, :update, :destroy] do
resource :relationships, only: [:create, :destroy]
get "follows" => "relationships#follower", as: "follows"
get "followers" => "relationships#followed", as: "followers"
end
get "users/mypage/:id" => "users#mypage", as: "users_mypage"
get "users/favoindex/:id" => "users#favoindex", as: "users_favoindex"
get "users/followpost/:id" => "users#followpost", as: "users_followpost"
resources :posts, only: [:index, :show, :create, :destroy] do
resource :favorites, only: [:create, :destroy]
resource :post_comments, only: [:create, :destroy]
end
resources :newss, only: [:index, :show, :message]
get "newss/message/:id" => "newss#message", as: "newss_message"
resources :searches, only: [:search]
get "searches/search" => "searches#search"
resources :notices, only: [:index]
end
namespace :admin do
get "users/top" => "users#top"
resources :users, only: [:top, :index, :show]
resources :messages, only: [:index, :show, :create, :destroy]
resources :newss, only: [:index, :show, :create, :destroy]
resources :posts, only: [:index, :show, :destroy] do
resource :post_comments, only: [:destroy]
end
resources :searches, only: [:search]
get "searches/search" => "searches#search"
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end<file_sep>/app/models/relationship.rb
# frozen_string_literal: true
class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
def created_notice_follow!(current_user, user_id)
tmp = Notice.where(["visitor_id = ? & visited_id = ? & action = ?", current_user.id, user_id, "follow"])
if tmp.blank?
notice = current_user.active_notice.new(
visited_id: user_id,
action: "follow"
)
notice.save if notice.valid?
end
end
end
<file_sep>/test/controllers/public/users_controller_test.rb
require 'test_helper'
class Public::UsersControllerTest < ActionDispatch::IntegrationTest
test "should get show" do
get public_users_show_url
assert_response :success
end
test "should get mypage" do
get public_users_mypage_url
assert_response :success
end
test "should get edit" do
get public_users_edit_url
assert_response :success
end
test "should get follower" do
get public_users_follower_url
assert_response :success
end
test "should get followed" do
get public_users_followed_url
assert_response :success
end
test "should get favoindex" do
get public_users_favoindex_url
assert_response :success
end
end
<file_sep>/spec/factories/post_comments.rb
FactoryBot.define do
factory :post_comment do
sequence(:reaction) { |n| "TEST#{n}" }
end
end
<file_sep>/spec/models/news_spec.rb
require 'rails_helper'
RSpec.describe "Newsモデルのテスト", type: :model do
before do
@news = build(:news)
end
describe 'バリデーションテスト' do
context 'titleカラム' do
it 'titleが空だとNG' do
@news.title = ''
# is_expected.to eq false;
expect(@news.valid?).to eq(false)
end
it '10文字以上であること' do
@news.title = Faker::Lorem.characters(number: 9)
expect(@news.valid?).to eq(false)
end
it '20文字以下であること' do
@news.title = Faker::Lorem.characters(number: 21)
expect(@news.valid?).to eq(false)
end
end
context 'news_textカラム' do
it 'news_textが空だとNG' do
@news.news_text = ''
# is_expected.to eq false;
expect(@news.valid?).to eq(false)
end
it '10文字以上であること' do
@news.news_text = Faker::Lorem.characters(number: 9)
expect(@news.valid?).to eq(false)
end
it '1000文字以下であること' do
@news.news_text = Faker::Lorem.characters(number: 1001)
expect(@news.valid?).to eq(false)
end
end
end
describe 'アソシエーション' do
context 'Notice' do
it '1:Nか' do
expect(News.reflect_on_association(:notices).macro).to eq :has_many
end
end
context 'User' do
it 'N:1か' do
expect(News.reflect_on_association(:user).macro).to eq :belongs_to
end
end
end
end
<file_sep>/app/controllers/public/favorites_controller.rb
# frozen_string_literal: true
class Public::FavoritesController < ApplicationController
before_action :authenticate_user!
def create
post = Post.find(params[:post_id])
favorite = current_user.favorites.new(post_id: post.id)
favorite.save
post.created_notice_favorite!(current_user)
redirect_to request.referer
end
def destroy
post = Post.find(params[:post_id])
favorite = current_user.favorites.find_by(post_id: post.id)
favorite.destroy
redirect_to request.referer
end
end
<file_sep>/app/helpers/public/notices_helper.rb
# frozen_string_literal: true
module Public::NoticesHelper
end
<file_sep>/app/controllers/public/searches_controller.rb
# frozen_string_literal: true
class Public::SearchesController < ApplicationController
def search
@model = params["search"]["model"]
@content = params["search"]["content"]
@records = search_for(@model, @content)
end
def search_for(model, content)
if model == 'users'
User.where('name LIKE ?', '%' + content + '%')
elsif model == 'posts'
Post.where('murmur LIKE ?', '%' + content + '%')
elsif model == "tags"
ActsAsTaggableOn::Tag.where("name LIKE ?", '%' + content + '%')
end
end
end
<file_sep>/spec/controllers/admin/user_controller_spec.rb
require 'rails_helper'
describe "UserController" do
context "トップページが表示される" do
it 'top' do
visit "admin/users/top"
end
end
end
<file_sep>/app/helpers/public/newss_helper.rb
# frozen_string_literal: true
module Public::NewssHelper
end
<file_sep>/spec/controllers/public/posts_controller_spec.rb
require 'rails_helper'
describe "PostController" do
before do
@user1 = build(:user)
@post1 = build(:post)
@post2 = build(:post)
end
describe 'index' do
context "index" do
before do
visit "posts"
end
it 'オススメタグの表記はあるか' do
expect(page).to have_content "オススメタグ"
end
end
context 'show' do
it 'Post詳細画面が表示されるか' do
visit "posts/#{@post1.id}"
end
end
end
end
<file_sep>/spec/models/notices_spec.rb
require 'rails_helper'
RSpec.describe "Noticeモデルのテスト", type: :model do
before do
@notices = build(:notice)
end
describe 'アソシエーション' do
context 'User' do
it 'N:1か' do
expect(Notice.reflect_on_association(:visitor).macro).to eq :belongs_to
expect(Notice.reflect_on_association(:visited).macro).to eq :belongs_to
end
end
context 'Post' do
it 'N:1か' do
expect(Notice.reflect_on_association(:post).macro).to eq :belongs_to
end
end
context 'PostComment' do
it 'N:1か' do
expect(Notice.reflect_on_association(:post_comment).macro).to eq :belongs_to
end
end
context 'News' do
it 'N:1か' do
expect(Notice.reflect_on_association(:news).macro).to eq :belongs_to
end
end
end
end
<file_sep>/app/controllers/public/posts_controller.rb
# frozen_string_literal: true
class Public::PostsController < ApplicationController
before_action :authenticate_user!, only: %i[create destroy]
def index
@posts = Post.all.order("id DESC")
@me = current_user
@posts = @posts.tagged_with(params[:tag_name].to_s) if params[:tag_name]
end
def show
@post = Post.find(params[:id])
@user = @post.user
@post_comment = PostComment.new
@post_comments = @post.post_comments
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
@post.save
redirect_to request.referer
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to request.referer
end
private
def post_params
params.require(:post).permit(:user_id, :murmur, :post_image, :tag_list)
end
end
<file_sep>/spec/models/posts_spec.rb
require 'rails_helper'
RSpec.describe "Postモデルのテスト", type: :model do
before do
@post = build(:post)
end
describe 'バリデーションテスト' do
context 'murmurカラム' do
it '200文字以下であること' do
@post.murmur = Faker::Lorem.characters(number: 201)
expect(@post.valid?).to eq(false)
end
end
end
describe 'アソシエーション' do
context 'PostComment' do
it '1:Nか' do
expect(Post.reflect_on_association(:post_comments).macro).to eq :has_many
end
end
context 'Favorite' do
it '1:Nか' do
expect(Post.reflect_on_association(:favorites).macro).to eq :has_many
end
end
context 'Notice' do
it '1:Nか' do
expect(Post.reflect_on_association(:notices).macro).to eq :has_many
end
end
context 'User' do
it 'N:1か' do
expect(Post.reflect_on_association(:user).macro).to eq :belongs_to
end
end
end
end
<file_sep>/app/helpers/admin/messages_helper.rb
# frozen_string_literal: true
module Admin::MessagesHelper
end
<file_sep>/app/controllers/admin/newss_controller.rb
# frozen_string_literal: true
class Admin::NewssController < ApplicationController
before_action :authenticate_owner!
def index
@message = News.new
end
def show
@news = News.find(params[:id])
end
end
|
c6a3d004aa6c6c27f6429ecf2b6c86ddbb2e1c4b
|
[
"Ruby"
] | 35
|
Ruby
|
mameg725/anilova
|
fd3e927d5f39a7d21b3f01405b611b9f6c152db4
|
f34e552afc4cdc296e235bde853aa3890a77a9c6
|
refs/heads/master
|
<repo_name>littelStarBling/laibatrip<file_sep>/script.js
//burger nav toggle
const menu = document.querySelector('.nav-links');
const burger = document.querySelector('.burger');
const pageName =document.querySelectorAll('.nav-links li a')
const navSlide =()=>{
burger.addEventListener('click',()=>{
burger.classList.toggle('toggle');
menu.classList.toggle('open-menu');
});
}
const navClose = () => {
pageName.forEach(function(obj){
obj.addEventListener('click',()=>{
burger.classList.toggle('toggle');
menu.classList.toggle('open-menu');
})
})
}
navClose();
navSlide();
const dataOpenButton = document.querySelectorAll('[data-open-target]')
const dataCloseButton = document.querySelectorAll('[data-close-button]')
const overlay = document.getElementById('overlay')
//each tour detail information
dataOpenButton.forEach(button=>{
button.addEventListener('click',()=>{
const modal = document.querySelector(button.dataset.openTarget)
openModal(modal)
})
});
overlay.addEventListener('click', () => {
const modals = document.querySelectorAll('.modal.active')
modals.forEach(modal=>{
closeModal(modal)
})
});
dataCloseButton.forEach(button=>{
button.addEventListener('click',()=>{
const modal = button.closest('.modal')
closeModal(modal)
})
});
function openModal(modal){
if(modal==null) return
modal.classList.add('active')
overlay.classList.add('active')
}
function closeModal(modal){
if(modal==null) return
modal.classList.remove('active')
overlay.classList.remove('active')
}
//slide in animation effect
AOS.init({
offset: 400,
duration: 1000
});
|
abb79341c00b4cb689043d4ea2725f179202b8fc
|
[
"JavaScript"
] | 1
|
JavaScript
|
littelStarBling/laibatrip
|
f299282b6c1be0dedff7e1673e14775cd76f0f85
|
8086d54be85265053f26eaba27396ec12ac95270
|
refs/heads/master
|
<repo_name>caotuan1420008/HotelReservation<file_sep>/app/src/main/java/com/example/an/hotel/Adapter/AdminRoomList.java
package com.example.an.hotel.Adapter;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.an.hotel.Fragments.RoomAddFragment;
import com.example.an.hotel.R;
import com.example.an.hotel.RoomDetailActivity;
import com.example.an.hotel.models.roomObj;
import io.realm.Realm;
import io.realm.RealmResults;
public class AdminRoomList extends AppCompatActivity {
private Realm realm;
public String id;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_room_list);
realm = Realm.getDefaultInstance();
RealmResults<roomObj> rooms = realm.where(roomObj.class).findAll();
rooms = rooms.sort("name");
final RoomAdapterAdmin adapter = new RoomAdapterAdmin(this , rooms);
listView = (ListView) findViewById(R.id.room_list);
listView.setAdapter(adapter);
//detail look
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final roomObj room = (roomObj) adapterView.getAdapter().getItem(i);
// click on list
Intent roomDetailIntent = new Intent(AdminRoomList.this,RoomDetailActivity.class);
AdminRoomList.this.startActivity(roomDetailIntent);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RoomAddFragment dialog1 = new RoomAddFragment();
dialog1.show(getFragmentManager(),"aab");
}
});
//xoa + edit
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View arg1,
int pos, long id) {
final roomObj room = (roomObj) adapter.getAdapter().getItem(pos);
AlertDialog dialog = new AlertDialog.Builder(AdminRoomList.this)
.setTitle("Delete Task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteTask(room.getId());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// deleteTask(task.getId());
}
})
.create();
dialog.show();
return true;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
private void deleteTask(final String roomID) {
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.where(roomObj.class).equalTo("id", roomID)
.findFirst()
.deleteFromRealm();
}
});
}
public String getId() {
return id;
}
}
<file_sep>/app/src/main/java/com/example/an/hotel/Login.java
package com.example.an.hotel;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import com.example.an.hotel.Adapter.AdminRoomList;
import com.example.an.hotel.Adapter.MainActivity;
public class Login extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText loginID = (EditText) findViewById(R.id.loginID);
final EditText loginPass = (EditText) findViewById(R.id.loginPass);
final Button btnRegister = (Button) findViewById(R.id.btnRegister);
final Button btnLogin = (Button) findViewById(R.id.btnLogin);
final Switch swAdmin = (Switch) findViewById(R.id.switchAdmin);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registerIntent = new Intent(Login.this,Register.class);
Login.this.startActivity(registerIntent);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!swAdmin.isChecked()) {
Intent loginIntent = new Intent(Login.this, MainActivity.class);
Login.this.startActivity(loginIntent);
}else
{
Intent loginIntentAdmin = new Intent(Login.this, AdminRoomList.class);
Login.this.startActivity(loginIntentAdmin);
}
}
});
}
}
<file_sep>/app/src/main/java/com/example/an/hotel/RoomDetailAdapter.java
package com.example.an.hotel;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.an.hotel.models.roomObj;
import io.realm.OrderedRealmCollection;
import io.realm.RealmBaseAdapter;
public class RoomDetailAdapter extends RealmBaseAdapter<roomObj> implements ListAdapter {
private RoomDetailActivity activity;
private static class ViewHolder {
TextView roomName;
}
RoomDetailAdapter(RoomDetailActivity activity, OrderedRealmCollection<roomObj> data) {
super(data);
this.activity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.room_list_row, parent, false);
viewHolder = new ViewHolder();
viewHolder.roomName = (TextView) convertView.findViewById(R.id.room_item_name);
// viewHolder.roomName.setOnClickListener(listener);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (adapterData != null) {
roomObj room = adapterData.get(position);
viewHolder.roomName.setText(room.getName());
}
return convertView;
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
// open room detail
}
};
}
<file_sep>/app/src/main/java/com/example/an/hotel/FinderActivity.java
package com.example.an.hotel;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import com.example.an.hotel.Adapter.RoomListActivity;
import java.util.Calendar;
public class FinderActivity extends AppCompatActivity {
private EditText txtDateFrom;
private EditText txtDateTo;
private Calendar myCalendar;
private int year;
private int month;
private int day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finder);
txtDateFrom = (EditText) findViewById(R.id.dateFrom);
txtDateTo = (EditText) findViewById(R.id.dateTO);
txtDateFrom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDate(v,txtDateFrom);
}
});
txtDateTo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDate(v,txtDateTo);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent roomIntent = new Intent(FinderActivity.this,RoomListActivity.class);
FinderActivity.this.startActivity(roomIntent);
}
});
}
public void setDate(View v,final EditText ed) {
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
ed.setText(dayofmonth + "-" + monthofyear + "-" + year);
}
}, year, month, day);
dpd.show();
}
}
|
d95650d6fffba158153603f26cdccdf592f48481
|
[
"Java"
] | 4
|
Java
|
caotuan1420008/HotelReservation
|
f4dc2cb00ee5357d88a6fc994c9fbcf07e72dc24
|
16c5454bf96c2d6ac0889594ba90ffe01cf2a6a3
|
refs/heads/master
|
<repo_name>slsan/DataStructures<file_sep>/Array/src/Main.java
import array.Array;
import queue.ArrayQueue;
import queue.LinkedListQueue;
import queue.LoopQueue;
import queue.Queue;
import stack.ArrayStack;
import stack.LinkedListStack;
import stack.Stack;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Array<Integer> arr = new Array<>();
//
// for (int i = 0; i < 10 ;i++){
// arr.addLast(i);
// }
//
// System.out.println(arr);
//
// arr.add(2,20);
// System.out.println(arr);
//
// arr.addFirst(100);
// System.out.println(arr);
//
// arr.remove(3);
// System.out.println(arr);
//
// arr.removeElement(100);
// System.out.println(arr);
//
// arr.remove(2);
// System.out.println(arr);
int count = 100000;
ArrayQueue<Integer> arr = new ArrayQueue<>();
double time1 = testQueue(arr, count);
System.out.println("ArrayQueue time = " + time1 + " s");
LoopQueue<Integer> loop = new LoopQueue<>();
double time2 = testQueue(loop, count);
System.out.println("LoopQueue time = " + time2 + " s");
LinkedListQueue<Integer> link = new LinkedListQueue<>();
double time3 = testQueue(link, count);
System.out.println("LinkedListQueue time = " + time3 + " s");
// ArrayStack<Integer> arr = new ArrayStack<>();
// double time1 = testStack(arr, count);
// System.out.println("ArrayStack time = " + time1 + " s");
//
//
// LinkedListStack<Integer> linkedListStack = new LinkedListStack<>();
// double time2 = testStack(linkedListStack, count);
// System.out.println("LoopQueue time = " + time2 + " s");
}
private static double testQueue(Queue<Integer> queue, int count) {
double startTime = System.nanoTime();
Random random = new Random();
for (int i = 0; i < count; i++) {
queue.enQueue(random.nextInt(Integer.MAX_VALUE));
}
for (int i = 0; i < count; i++)
queue.deQueue();
double endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
private static double testStack(Stack<Integer> stack, int count) {
double startTime = System.nanoTime();
Random random = new Random();
for (int i = 0; i < count; i++) {
stack.push(random.nextInt(Integer.MAX_VALUE));
}
for (int i = 0; i < count; i++)
stack.pop();
double endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
}
<file_sep>/Array/src/map/LinkedListMap.java
package map;
import set.FileOPerate;
import java.util.ArrayList;
/**
* Created by slsan on 2018/9/12.
*/
public class LinkedListMap<K, V> implements Map<K, V> {
private class Node {
private K key;
private V value;
private Node next;
public Node(K key, V value, Node node) {
this.key = key;
this.value = value;
this.next = node;
}
public Node(K key) {
this(key, null, null);
}
public Node() {
this(null, null, null);
}
@Override
public String toString() {
return key.toString() + " : " + value.toString();
}
}
private Node dummyHead;
private int size;
public LinkedListMap() {
dummyHead = new Node();
size = 0;
}
@Override
public void add(K key, V value) {
Node node = getNode(key);
if (node == null){
// 没有当前可以存在,直接添加到头结点
dummyHead.next = new Node(key,value,dummyHead.next);
size++;
}else {
// 否则认为出异常或者更新对应的值
node.value = value;
}
}
@Override
public V remove(K key) {
Node prev = dummyHead;
while (prev.next != null){
if (prev.next.key.equals(key))
break;
prev = prev.next;
}
if (prev.next != null){
Node delNode = prev.next;
prev.next = delNode.next;
delNode.next = null;
return delNode.value;
}
return null;
}
@Override
public boolean contains(K key) {
return getNode(key) != null;
}
@Override
public void set(K key, V value) {
Node node = getNode(key);
if (node == null)
throw new IllegalArgumentException(key + " not exist!");
node.value = value;
}
@Override
public V get(K key) {
Node node = getNode(key);
return node == null ? null : node.value;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int getSize() {
return size;
}
private Node getNode(K key) {
Node cur = dummyHead.next;
while (cur != null) {
if (key.equals(cur.key))
return cur;
cur = cur.next;
}
return null;
}
public static void main(String[] args){
System.out.println("---------------统计字数-------------");
ArrayList<String> words = new ArrayList<>();
if (FileOPerate.readFile("a.txt",words)){
System.out.println("total size =" + words.size());
LinkedListMap<String,Integer> map = new LinkedListMap<>();
for (String word : words){
if (map.contains(word)){
map.set(word,map.get(word) + 1);
}else {
map.add(word,1);
}
}
System.out.println("Total diffent word =" + map.size);
System.out.println("Total word is have = " + map.get("is"));
System.out.println("Total word pride have = " + map.get("pride"));
}
}
}<file_sep>/Array/src/set/BSTSet.java
package set;
import binarysearch.BST;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
/**
* Created by slsan on 2018/9/12.
*/
public class BSTSet<E extends Comparable<E>> implements Set<E> {
private BST<E> bst;
public BSTSet(){
bst = new BST<>();
}
@Override
public void add(E e) {
bst.add(e);
}
@Override
public void remove(E e) {
bst.remove(e);
}
@Override
public int getSize() {
return bst.getSize();
}
@Override
public boolean contains(E e) {
return bst.contains(e);
}
@Override
public boolean isEmpty() {
return bst.isEmpty();
}
public static void main(String[] args){
System.out.println("Pride and Prejudice");
ArrayList<String> words1 = new ArrayList<>();
if(FileOPerate.readFile("a.txt", words1)) {
System.out.println("Total words: " + words1.size());
BSTSet<String> set1 = new BSTSet<>();
for (String word : words1)
set1.add(word);
System.out.println("Total different words: " + set1.getSize());
}
System.out.println();
System.out.println("A Tale of Two Cities");
ArrayList<String> words2 = new ArrayList<>();
if(FileOPerate.readFile("b.txt", words2)){
System.out.println("Total words: " + words2.size());
BSTSet<String> set2 = new BSTSet<>();
for(String word: words2)
set2.add(word);
System.out.println("Total different words: " + set2.getSize());
}
}
}
<file_sep>/Array/src/solution/Solution4.java
package solution;
import java.util.TreeSet;
/**
* Created by slsan on 2018/9/12.
*/
public class Solution4 {
public int solution(String[] words) {
String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-",
".--", "-..-", "-.--", "--.."};
TreeSet<String> tree = new TreeSet<>();
for (String word : words) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < word.length() ; i++) {
res.append(codes[word.charAt(i) - 'a']);
}
tree.add(res.toString());
}
return tree.size();
}
}
<file_sep>/Array/src/tree/SegmentTree.java
package tree;
/**
* Created by slsan on 2018/9/20.
*/
public class SegmentTree<E> {
private E[] data;
private E[] tree;
private Merger<E> merger;
public SegmentTree(E[] arr,Merger<E> merger) {
this.merger = merger;
data = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++)
data[i] = arr[i];
tree = (E[]) new Object[4 * arr.length];
buildSegmentTree(0, 0, data.length - 1);
}
private void buildSegmentTree(int index, int l, int r) {
if (l == r) {
tree[index] = tree[l];
return;
}
int leftChildIndex = leftChild(index);
int rightChildIndex = rightChild(index);
int mid = l + (r - l) / 2;
buildSegmentTree(leftChildIndex,l,mid);
buildSegmentTree(rightChildIndex,mid + 1,r);
tree[index] = merger.merge(tree[leftChildIndex],tree[rightChildIndex]);
}
public int getSize() {
return data.length;
}
public E get(int index) {
if (index < 0 || index >= data.length)
throw new IllegalArgumentException("index is illegal");
return data[index];
}
private int leftChild(int index) {
return 2 * index + 1;
}
private int rightChild(int index) {
return 2 * index + 2;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("[");
for (int i = 0; i < tree.length;i++){
if (tree[i] != null){
res.append(tree[i]);
}else {
res.append("null");
}
if (i != tree.length -1)
res.append(", ");
}
res.append("]");
return res.toString();
}
public static void main(String[] args){
Integer[] nums = {-2,0,3,-5,2,-1};
SegmentTree<Integer> segment = new SegmentTree<>(nums,new Merger<Integer>(){
@Override
public Integer merge(Integer a, Integer b) {
return a + b;
}
});
System.out.println(segment);
}
}
<file_sep>/Array/src/solution/Solution5.java
package solution;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
/**
* Created by slsan on 2018/9/14.
*/
public class Solution5 {
public int[] test5(int[] nums1,int[] nums2){
TreeSet<Integer> tree = new TreeSet<>();
for (int nums : nums1){
tree.add(nums);
}
List<Integer> list = new ArrayList<>();
for (int num : nums2){
if (tree.contains(num)){
list.add(num);
tree.remove(num);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i ++)
res[i] = list.get(i);
return res;
}
}
<file_sep>/Array/src/others/ListNode.java
package others;
/**
* Created by slsan on 2018/9/6.
*/
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
public ListNode(int[] x) {
if (x == null || x.length == 0)
throw new IllegalArgumentException("x cannot be null");
this.val = x[0];
ListNode cur = this;
for (int i = 1; i < x.length; i++) {
cur.next = new ListNode(x[i]);
cur = cur.next;
}
}
@Override
public String toString(){
StringBuilder s = new StringBuilder();
ListNode cur = this;
while(cur != null){
s.append(cur.val + "->");
cur = cur.next;
}
s.append("NULL");
return s.toString();
}
}
<file_sep>/Array/src/solution/Solution6.java
package solution;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
/**
* Created by slsan on 2018/9/14.
*/
public class Solution6 {
public int[] test(int[] sums1, int[] sums2){
TreeMap<Integer,Integer> map = new TreeMap<>();
for (int sum : sums1){
if (map.containsKey(sum)){
map.put(sum,map.get(sum) + 1);
}else {
map.put(sum,1);
}
}
List<Integer> list = new ArrayList<>();
for (int sum : sums2){
if (map.containsKey(sum)){
list.add(sum);
map.put(sum,map.get(sum)-1);
if (map.get(sum) == 0)
map.remove(sum);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++){
res[i] = list.get(i);
}
return res;
}
}
<file_sep>/Array/src/array/Array.java
package array;
/**
* Created by slsan on 2018/9/4.
*/
public class Array<E> {
private E[] datas;
private int size;
// 默认构造,默认容量为10
public Array(){
this(10);
}
// 构造,capacity 数组容量
public Array(int capacity){
this.datas = (E[]) new Object[capacity];
size = 0;
}
public Array(E[] arr){
datas = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++)
datas[i] = arr[i];
size = arr.length;
}
// 获取数组大小
public int getSize(){
return size;
}
// 获取数组容量
public int getCapacity(){
return datas.length;
}
// 判断数组是否为空
public boolean isEmpty(){
return size == 0;
}
// 向数组末尾添加一个元素
public void addLast(E e){
add(size,e);
}
// 向数组开头添加一个元素
public void addFirst(E e){
add(0,e);
}
// 向数组中任意位置添加一个元素
public void add(int index , E e){
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed, Required index >= 0 and index < size");
}
// 时间复杂度震荡, 当数组内容超过数组长度就扩容为原数组容量的2倍
if (size == datas.length)
resize(2 * datas.length);
for (int i = size -1; i >= index; i--)
datas[i + 1] = datas[i];
datas[index] = e;
size++;
}
private void resize(int newCapacity) {
E[] newData = (E[])new Object[newCapacity];
for (int i = 0; i < size; i++){
newData[i] = datas[i];
}
datas = newData;
newData = null;
}
public void swap(int i , int j){
if (i < 0 || i >= size || j < 0 || j >= size)
throw new IllegalArgumentException("index is Illegal");
E temp = datas[i];
datas[i] = datas[j];
datas[j] = temp;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("array.Array : size = %d , capacity = %d\n", size, datas.length));
builder.append("[");
for (int i = 0; i < size ;i++){
builder.append(datas[i]);
if (i < size - 1){
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public E get(int index){
if (index < 0 || index >= size)
throw new IllegalArgumentException("Get failed , Required index > 0 and index < size");
return datas[index];
}
public E getLast(){
return get(size -1);
}
public E getFirst(){
return get(0);
}
public void set(int index , E e){
if (index < 0 || index >= size)
throw new IllegalArgumentException("Set failed, Required index > 0 and index < size");
datas[index] = e;
}
// 是否包含当前元素,包含当期元素返回 true,否则返回 false
public boolean contains(E e){
for (int i = 0; i < size ;i++){
if (datas[i].equals(e))
return true;
}
return false;
}
// 查找元素找到返回当前位置,找不到返回-1
public int find(E e){
for (int i = 0; i < size ;i ++){
if (datas[i].equals(e))
return i;
}
return -1;
}
public E remove(int index){
if (index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed, Required index > 0 and index < size");
E temp = datas[index];
for (int i = index + 1; i < size; i++){
datas[i - 1] = datas[i];
}
datas[size - 1] = null;
size--;
// 时间复杂度震荡, 当缩减大小时,数组长度为容量的1/4,才去缩减数组容量的1/2
if (datas.length != 0 && size == datas.length / 4)
resize(datas.length / 2);
return temp;
}
public E removeLast(){
return remove(size - 1);
}
public E removeFirst(){
return remove(0);
}
public void removeElement(E e){
int index = find(e);
if (index != -1){
remove(index);
}
}
}
|
a9793c7ce697d2e372f330c1020d76199a7856a8
|
[
"Java"
] | 9
|
Java
|
slsan/DataStructures
|
930c14aa9fef881b93681d24090b97725888714c
|
7bf1f0efc1e2027bcb24c5d4817c8e996597c3fe
|
refs/heads/master
|
<file_sep>require './config/environment'
class UserController < ApplicationController
configure do
set :views, 'app/views/user'
end
get '/signup' do
erb :new
end
get '/login' do
if is_logged_in?(session)
redirect to '/tweets'
else
erb :'session/new'
end
end
post '/login' do
user = User.all.detect {|user| user.username == params[:user][:username]}
if user && user.authenticate(params[:user][:password])
session[:user_id] = user.id
redirect to '/tweets'
else
redirect to '/login'
end
end
get '/logout' do
session.clear
redirect to '/login'
end
post '/users' do
if params[:user][:email].empty? || params[:user][:username].empty? || params[:user][:password].empty?
redirect to '/signup'
else
user = User.create(params[:user])
session[:user_id] = user.id
redirect to '/tweets'
end
end
get '/users/:slug' do
@user = User.find_by_slug(params[:slug])
erb :show
end
end
<file_sep>module Helpers
def current_user(session)
User.find(session[:user_id])
end
def is_logged_in?(session)
!!session[:user_id]
end
end
|
dbaaa562e5d5da5afb3b44259f5ec008c2bf5244
|
[
"Ruby"
] | 2
|
Ruby
|
blazeiburgess/sinatra-fwitter-group-project-wdf-000
|
36119e029a0666a61d162b5bbfc8a56446d5922e
|
9d362cd2e18117d6368db7f5ad26bd78361d63ec
|
refs/heads/master
|
<repo_name>albeva/fbide-old-svn<file_sep>/fbide-wx/sdk/include/sdk/Exception.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EXCEPTION_H_INCLUDED
#define EXCEPTION_H_INCLUDED
/**
* Global base Exception object used in FBIde
*
* Other classes in FBIde are encoriged to derive from
* this base class
*/
class DLLIMPORT CException
{
public :
CException (const wxString & message, const wxString & file = _T(""), int line = 0, const wxString & method = _T(""))
: m_message(message), m_file(file), m_line(line), m_method(method)
{}
CException (const char * message, const wxString & file = _T(""), int line = 0, const wxString & method = _T(""))
: m_message(wxString(message, wxConvUTF8)), m_file(file), m_line(line), m_method(method)
{}
const wxString & GetMessage () const
{
return m_message;
}
const wxString & GetFile () const
{
return m_file;
}
int GetLine () const
{
return m_line;
}
const wxString & GetMethod () const
{
return m_method;
}
private :
wxString m_message;
wxString m_file;
int m_line;
wxString m_method;
};
/**
* For creating CException instance.
* This automatically adds file, line and method
* to exception message.
*/
#define EXCEPTION(msg) ::CException((msg), wxString(__FILE__, wxConvUTF8), __LINE__, wxString(__PRETTY_FUNCTION__, wxConvUTF8));
/**
* FBIde specific TRY ... CATCH block that
* traps most exceptions in a consistant
* form
*/
#define FBIDE_TRY try
#define FBIDE_CATCH() \
catch (CException e) \
{ \
::ShowException (e); \
} \
catch (CException * e) \
{ \
::ShowException (*e); \
delete e; \
} \
catch (wxString msg) \
{ \
::ShowException (msg); \
} \
catch (int code) \
{ \
wxString msg = _T("Code : "); \
msg << code; \
::ShowException(msg); \
} \
catch (...) \
{ \
::ShowException(_T("Unknown exception was thrown!")); \
}
/**
* Show exception message window
*/
void DLLIMPORT ShowException (const wxString & msg);
void DLLIMPORT ShowException (const CException & ex);
#endif // EXCEPTION_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Editor/Editor.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "../Manager.h"
#include "../UiManager.h"
#include "../MultiSplitter.h"
#include "Editor.h"
using namespace fbi;
const int ID_SplitVertically = ::wxNewId();
const int ID_SplitHorizontally = ::wxNewId();
class fbi::StcEditor : public wxStyledTextCtrl
{
public:
StcEditor(int index, Editor * owner, wxWindow * parent, int id)
{
Create(parent, id);
UsePopUp(false);
}
// on right mouse button
void OnMouseRight (wxMouseEvent & event)
{
wxMenu menu;
menu.Append(ID_SplitVertically, "Split Vertically");
menu.Append(ID_SplitHorizontally, "Split Horizontally");
PopupMenu(&menu);
}
// destructor
~StcEditor() {}
// receave events
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(StcEditor, wxStyledTextCtrl)
EVT_RIGHT_UP(StcEditor::OnMouseRight)
END_EVENT_TABLE()
/**
* Event table for documents
*/
BEGIN_EVENT_TABLE(Editor, Document)
EVT_MENU(ID_SplitVertically, Editor::OnSplitVertically)
EVT_MENU(ID_SplitHorizontally, Editor::OnSplitHorizontally)
END_EVENT_TABLE()
#define NEW_STC(index, parent) \
m_editors[index] = new StcEditor(index, this, m_splitter, wxID_ANY); \
if (parent != nullptr) \
m_editors[index]->SetDocPointer(parent->GetDocPointer()); \
m_splitter->ShowWindow(index, m_editors[index]);
/**
* Create new editor
*/
Editor::Editor ()
{
// Create the panel
m_panel = new wxPanel(GET_UIMGR()->GetDocumentArea(), wxID_ANY);
SetDocWindow(m_panel);
m_panel->PushEventHandler(this);
// teh main sizer
m_sizer = new wxBoxSizer(wxVERTICAL);
m_panel->SetSizer(m_sizer);
// multisizer to contain the editors
int style = wxSP_3DSASH | wxSP_LIVE_UPDATE | wxCLIP_CHILDREN;
m_splitter = new MultiSplitWindow(m_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, style);
m_sizer->Add(m_splitter, 1, wxGROW, 5);
// clear
memset(m_editors, 0, sizeof(m_editors));
// create default editor
NEW_STC(0, ((StcEditor*)nullptr))
}
// do a vertical split/unsplit
void Editor::OnSplitVertically(wxCommandEvent & event)
{
NEW_STC(1, m_editors[0])
// NEW_STC(2, m_editors[0])
// NEW_STC(3, m_editors[0])
}
// do a horizontal split/unsplit
void Editor::OnSplitHorizontally(wxCommandEvent & event)
{
NEW_STC(2, m_editors[0])
NEW_STC(3, m_editors[0])
}<file_sep>/fbide-wx/Plugins/FBIdePlugin/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/UiManager.h"
#include "sdk/PluginManager.h"
#include "sdk/TypeManager.h"
#include "sdk/Document.h"
#include "sdk/DocManager.h"
#include "sdk/StyleInfo.h"
#include "sdk/Editor.h"
#include "LineStates.h"
#include "LexFreeBasic.hxx"
using namespace fb;
using namespace LEX;
// this is test code...
struct FreeBasicEditor : public CDocument<CEditor, DOCUMENT_MANAGED>
{
FreeBasicEditor (const wxString & file = _T(""))
{
SetDocTitle (::wxFileNameFromPath(file));
CUiManager & ui = *CManager::Get()->GetUiManager();
CRegistry & reg = GET_REG();
m_loaded = false;
// construct the editor
CEditor::Create (
ui.GetDocWindow(),
wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_SIMPLE
);
// Set editor styling
SetLexer (LEX::FREEBASIC);
CStyleParser * parser = GET_MGR()->GetStyleParser(_T("default"));
if (parser) LoadStyles (parser);
// Set m_lineStates
wxString lineStates;
lineStates << (int)&m_lineStates;
SetProperty(_T("lineStates"), lineStates);
// Set vars...
m_lineStates.m_dialect = DIALECT_QB;
m_lineStates.m_drawIndentedBoxes = reg["editor.drawIndentedBoxes"].AsBool(true);
m_lineStates.m_tabWidth = reg["editor.tabWidth"].AsInt(4);
m_lineStates.m_optionEscape = false;
// Load the keywords
SetKeyWords(KEYWORD_ONE, reg["fb.keywords.one"].AsString());
SetKeyWords(KEYWORD_TWO, reg["fb.keywords.two"].AsString());
SetKeyWords(KEYWORD_THREE, reg["fb.keywords.three"].AsString());
SetKeyWords(KEYWORD_FOUR, reg["fb.keywords.four"].AsString());
SetKeyWords(KEYWORD_PP_ONE, reg["fb.keywords.preprocessor.one"].AsString());
SetKeyWords(KEYWORD_PP_TWO, reg["fb.keywords.preprocessor.two"].AsString());
SetKeyWords(KEYWORD_ASM_ONE, reg["fb.keywords.asm.one"].AsString());
SetKeyWords(KEYWORD_ASM_TWO, reg["fb.keywords.asm.two"].AsString());
// define error indicator. (should this be moved to CEditor too?)
IndicatorSetStyle(0, wxSCI_INDIC_SQUIGGLE);
IndicatorSetForeground(0, wxColor(_T("red")));
// Load editor configuration
Setup(parser);
// Load the file
if (file.Len()) LoadFile (file);
// mark editor as ready and fully loaded
MarkReady(true);
}
/**
* Load the styles
*/
void LoadStyles (CStyleParser * parser)
{
// 63 possible LEX states (minus 32-39)
SetStyleBits(6);
// get styles default
CStyleInfo info;
CStyleInfo defInfo = parser->GetStyle(_T(".default"));
CStyleInfo asmInfo = parser->GetStyle(_T(".asm"));
CStyleInfo ppInfo = parser->GetStyle(_T(".preprocessor"));
// normalize default
if (!defInfo.bg.IsOk()) defInfo.bg = wxColor(_T("white"));
// default
SetStyle(FB_DEFAULT, defInfo);
// identifier
info = parser->GetStyle(_T(".identifier"));
bool hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_IDENTIFIER, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_IDENTIFIER, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_IDENTIFIER, info);
// comment
info = parser->GetStyle(_T(".comment"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_COMMENT, info);
// multiline comments should fille the line
StyleSetEOLFilled(FB_COMMENT, true);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_COMMENT, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_COMMENT, info);
// comment url
info = parser->GetStyle(_T(".comment.url"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_COMMENT_URL, info);
StyleSetEOLFilled(FB_COMMENT_URL, true);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_COMMENT_URL, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_COMMENT_URL, info);
// label
info = parser->GetStyle(_T(".label"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_LABEL, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_LABEL, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_LABEL, info);
// string
info = parser->GetStyle(_T(".string"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_STRING, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_STRING, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_STRING, info);
// string edcapes
info = parser->GetStyle(_T(".string.escape"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_STRING_ESCAPE, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_STRING_ESCAPE, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_STRING_ESCAPE, info);
// number
info = parser->GetStyle(_T(".number"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_NUMBER, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_NUMBER, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_NUMBER, info);
// operator
info = parser->GetStyle(_T(".operator"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_OPERATOR, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_OPERATOR, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_OPERATOR, info);
// FB keywords
info = parser->GetStyle(_T(".keyword.one"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_KEYWORD_ONE, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_FB_KEYWORD_ONE, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_FB_KEYWORD_ONE, info);
info = parser->GetStyle(_T(".keyword.two"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_KEYWORD_TWO, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_FB_KEYWORD_TWO, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_FB_KEYWORD_TWO, info);
info = parser->GetStyle(_T(".keyword.three"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_KEYWORD_THREE, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_FB_KEYWORD_THREE, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_FB_KEYWORD_THREE, info);
info = parser->GetStyle(_T(".keyword.four"));
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
SetStyle(FB_KEYWORD_FOUR, info);
if (!hasBg) info.bg = asmInfo.bg;
SetStyle(ASM_FB_KEYWORD_FOUR, info);
if (!hasBg) info.bg = ppInfo.bg;
SetStyle(PP_FB_KEYWORD_FOUR, info);
// ASM block
SetStyle(ASM_DEFAULT, asmInfo);
SetStyle(ASM_KEYWORD_ONE, parser->GetStyle(_T(".asm.keyword.one")));
SetStyle(ASM_KEYWORD_TWO, parser->GetStyle(_T(".asm.keyword.two")));
// make all styles in ASM block fill the line
for (int i = ASM_DEFAULT; i <= ASM_SECTION_LAST; i++)
StyleSetEOLFilled(i, true);
// PP block
SetStyle(PP_DEFAULT, ppInfo);
SetStyle(PP_KEYWORD_ONE, parser->GetStyle(_T(".preprocessor.keyword.one")));
SetStyle(PP_KEYWORD_TWO, parser->GetStyle(_T(".preprocessor.keyword.two")));
// make all pp stataments will the line
for (int i = PP_DEFAULT; i <= PP_SECTION_LAST; i++)
StyleSetEOLFilled(i, true);
}
/**
* Save file
*/
virtual bool SaveDoc (const wxString & file)
{
CEditor::SaveFile(file);
SetDocTitle(::wxFileNameFromPath(file));
}
DECLARE_EVENT_TABLE();
CLineStates m_lineStates;
bool m_loaded;
};
BEGIN_EVENT_TABLE (FreeBasicEditor, CEditor)
// EVT_KEY_DOWN (FreeBasicEditor::OnKeyDown)
// EVT_SCI_MARGINCLICK (-1, FreeBasicEditor::OnMarginClick)
// EVT_SCI_MODIFIED (-1, FreeBasicEditor::OnModified)
END_EVENT_TABLE()
/**
* the plugin class
*/
class FBIdePlugin : public CPluginBase
{
public :
// Attach plugin
bool Attach ()
{
CTypeManager * tm = GET_TYPEMGR();
tm->AddType(_T("text/fb"), _T("Freebasic files"), new CTypeRegistrant<FreeBasicEditor>);
tm->BindExtensions(_T("text/fb"), _T("bas;bi"));
if (!tm->TypeExists(_T("default")))
tm->BindAlias(_T("default"), _T("text/fb"));
return true;
}
// Detach plugin
bool Detach (bool force)
{
return true;
}
};
namespace
{
CPluginProvider<FBIdePlugin, PLUGINTYPE_EDITOR> plugin (_T("FBIdePlugin"));
}
<file_sep>/fbide-vs/Sdk/Editor/Syntax/LexFreeBasic.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
/**
* @todo asm /' ... \n ... '/ should decide is there a single line
* asm block or multiline. Implement methods "ResolveMultiLineComment"
*
* @todo Reseolve line continuation for ASM blocks
* asm _ \n could be either one liner or a multiline
*
* @todo end /' ... \n ... '/ asm should work. as well as
* end _ \n asm
* need to have LINE_STATE_END_PENDING ? that would persist while
* line is continued or a multiline comment comes between ?
* Don't care about that for now...
*
* @todo implement options to disable certain highlighting features
* escape sequences, block highlighting, ...
*/
#include "sdk_pch.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "LineStates.h"
#include "LexFreeBasic.h"
using namespace LEX;
/**
* Allowed URI Schemes inside comments.
* case insensitive.
*/
static const char * const URI_SCHEMES[] = {
"http://",
"https://",
"ftp://",
"www.",
0
};
/**
* Allowed (2 char long) escape codes inside strings
* preceded by \
* case sensitive!
*/
static const char ESCAPE_CODES[] = {
'a', // beep
'b', // backspace
'f', // formfeed
'l', 'n', // new line
'r', // carriage return
't', // tab
'v', // vertical tab
'\\', // backslash
'"', // double quote
'\'', // single quote
0
};
/**
* Integer literal suffixes
* Multi char
*/
static const char * const INTEGER_SUFFIXES_MC[] = {
"ull", "ul", "ll",
0
};
/**
* Integer suffixes single char
*/
static const char INTEGER_SUFFIXES_SC[] = {
'l', '%', '&', 'u',
0
};
// Set bit flags
static inline void SET_FLAG (int & value, int flag) {value |= flag;}
// unset bit flags
static inline void UNSET_FLAG (int & value, int flag) {value &= (~flag);}
// toggle bit flags
static inline void TOGGLE_FLAG (int & value, int flag) {value ^= flag;}
#define USE_LOG
// Logging macros
#ifdef USE_LOG
#define LOG(str, ...) wxLogMessage(str, __VA_ARGS__)
#else
#define LOG(str, ...)
#endif
#define DUMP_INT_VAR(_v) LOG("%s = %d\t\t\t(line: %d)", #_v, (int)_v, (int)__LINE__);
/**
* Highlight fb source code
*/
struct CFbSourceLexer
{
/**
* Construct the lexer object
*/
CFbSourceLexer (StyleContext &sc, Accessor &styler, WordList *keywords[])
: m_sc(sc),
m_styler(styler),
m_keywords(keywords),
m_section(0),
m_visibleChars(0),
m_indent(0),
m_tabWidth(4),
m_skipForward(false),
m_indentedBoxes(false),
m_stateStack(NULL),
m_curNppLevel(0),
m_curNcLevel(0),
m_nLcLevel(0),
m_lineCont(false)
{
// setup the state
m_curLine = styler.GetLine(m_sc.currentPos);
m_stateStack = (CLineStates*) styler.GetPropertyInt("lineStates", NULL);
// can't do anything
if (m_stateStack==0) return;
m_dialect = m_stateStack->m_dialect;
m_indentedBoxes = m_stateStack->m_drawIndentedBoxes;
m_tabWidth = m_stateStack->m_tabWidth;
// clear further state.
m_stateStack->ClearFrom(m_curLine);
// get line state
m_lineState = m_curLine > 0 ? m_styler.GetLineState(m_curLine-1) : 0;
// if there is line state get info...
DUMP_INT_VAR(m_lineState);
if (m_lineState)
{
// nested pp level
m_curNppLevel = m_lineState & 0xFF;
m_nLcLevel = (m_lineState >> 8) & 0xFF;
m_curNcLevel = (m_lineState >> 16) & 0xFF;
m_activeState = m_stateStack->GetActiveState(m_curLine).state;
LOG("m_activeState=%d", m_activeState);
}
else m_activeState = FB_DEFAULT;
// Colorise the document
Parse ();
}
/**
* Parse the syntax
*/
void Parse ()
{
// iterate through the text
while (m_sc.More())
{
// handle line starts
if (m_sc.atLineStart)
{
// get line info
m_curLine = m_styler.GetLine(m_sc.currentPos);
m_section = GetSectionType(m_activeState);
m_sc.SetState(m_activeState);
// zeroe the char count if not in comment
if (!m_curNcLevel) m_visibleChars = 0;
// parse line start
ParseLineStart ();
// detect indent
m_realIndent = 0;
for (int p = m_sc.currentPos; p < m_styler.Length(); p++)
{
char ch = m_styler.SafeGetCharAt(p);
if (ch == ' ') m_realIndent++;
else if (ch == '\t') m_realIndent += m_tabWidth;
else break;
}
DUMP_INT_VAR(m_realIndent);
// if it is a line continuation restore previous style
if (m_lineState & LINESTATE_LINE_CONTINUATION)
{
UNSET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION);
m_lineCont = true;
}
}
// handle non default states (comments, strings, ...)
if (!IsInDefaultSection(m_sc.state))
{
m_section = GetSectionType(m_sc.state);
ParseState ();
}
// handle default states (fb, asm, pp)
if (IsInDefaultSection(m_sc.state))
{
m_section = GetSectionType(m_sc.state);
ParseDefault ();
}
// handle line ends.
if (m_sc.atLineEnd)
{
m_section = GetSectionType(m_sc.state);
ParseLineEnd ();
// pop the multiline state
if (m_lineCont && !(m_lineState & LINESTATE_LINE_CONTINUATION))
{
m_lineCont = false;
while (m_nLcLevel--)
{
m_stateStack->PopState(m_curLine).state;
}
m_activeState = m_stateStack->GetActiveState(m_curLine).state;
LOG("Pop line continuation", 0);
}
}
else
{
if (!IsInComment(m_sc.state) && !IsASpaceOrTab(m_sc.ch))
m_visibleChars++;
}
// skip call to Forward() ?
if (m_skipForward)
{
m_skipForward = false;
continue;
}
Forward();
}
// finalize
m_sc.Complete();
}
/**
* Handle the line beginning
*/
void ParseLineStart ()
{
if (m_indentedBoxes) DrawIndentedBlocks();
}
/**
* Parse the state indicated in m_sc.state
* that is not default
*/
void ParseState ()
{
if (IsInComment(m_sc.state)) ParseComment ();
}
/**
* Parse default state
*/
void ParseDefault ()
{
// multiline comment
if (m_sc.Match('/', '\''))
{
m_activeState = m_section + FB_COMMENT;
m_stateStack->PushState(m_curLine, m_indent, m_activeState);
m_sc.SetState(m_activeState);
m_curNcLevel++;
Forward();
}
// single line comment
else if (m_sc.ch == '\'')
{
m_sc.SetState(m_section + FB_COMMENT);
if (m_visibleChars==0)
{
Forward();
SkipSpacesAndTabs();
ParseSingleLineComment();
}
}
// single line comment using REM keyword. At line start
// can be followed by metacommand
else if (!IsAWordChar(m_sc.GetRelative(3)) && m_sc.MatchIgnoreCase("rem"))
{
m_sc.SetState(m_section + GetFbKeywordStyle("rem", FB_COMMENT));
Forward(3);
m_sc.SetState(m_section + FB_COMMENT);
if (m_visibleChars==0 && IsASpaceOrTab(m_sc.ch))
{
SkipSpacesAndTabs();
ParseSingleLineComment();
}
}
// string literals
else if (m_sc.ch == '"')
{
bool escape = false;
if (m_dialect <= DIALECT_LITE)
{
escape = m_stateStack->m_optionEscape;
}
m_sc.SetState(m_section + FB_STRING);
ParseString(escape);
}
// explicitly NON escaped string literal
else if (m_sc.Match('$', '"'))
{
m_sc.SetState(m_section + FB_STRING);
Forward();
ParseString(false);
}
// explicitly escaped string literal
else if (m_sc.Match('!', '"'))
{
m_sc.SetState(m_section + FB_STRING);
Forward();
ParseString(true);
}
// macro
else if (m_sc.Match('#') && m_visibleChars == 0)
{
m_visibleChars++;
ParsePreprocessor ();
}
// command seperator
else if (m_sc.ch == ':')
{
// set to minus one because it will be incremented
// at next at next iteration anyway
m_visibleChars = -1;
m_sc.SetState(m_section);
}
// decimal or floating point number
else if (IsADigit(m_sc.ch)
|| (m_sc.ch == '.' && IsADigit(m_sc.chNext) && !IsAWordChar(m_sc.chPrev))
) {
m_sc.SetState(m_section + FB_NUMBER);
ParseNumber(10, m_sc.currentPos);
}
// hex number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'h')
{
m_sc.SetState(m_section + FB_NUMBER);
Forward(2);
ParseNumber(16, m_sc.currentPos-2);
}
// octal number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'o')
{
m_sc.SetState(m_section + FB_NUMBER);
Forward(2);
ParseNumber(8, m_sc.currentPos-2);
}
// binary number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'b')
{
m_sc.SetState(m_section + FB_NUMBER);
Forward(2);
ParseNumber(2, m_sc.currentPos-2);
}
// is a asm block start ?
else if (m_section != ASM_DEFAULT
&& !IsAWordChar(m_sc.GetRelative(3))
&& m_sc.Match("asm"))
{
ParseAsmStart ();
}
// is a asm block start ?
else if (m_section == ASM_DEFAULT
&& !IsAWordChar(m_sc.GetRelative(3))
&& m_sc.Match("end"))
{
ParseAsmEnd();
}
// Is a line continuation
else if (m_section != FB_DEFAULT
&& !(m_lineState & LINESTATE_LINE_CONTINUATION)
&& m_sc.ch == '_'
&& !IsAWordChar(m_sc.chNext)
&& !IsAWordChar(m_sc.chPrev))
{
ParseLineContinuation();
}
// a keyword or an identifier
else if (IsAWordChar(m_sc.ch))
{
ParseIdentifier();
}
// is an operator ?
else if (IsOperator(m_sc.ch))
{
m_sc.SetState(m_section + FB_OPERATOR);
while (
IsOperator(m_sc.ch)
&& !m_sc.Match('/', '\'')
&& (m_sc.ch != '.' || !IsADigit(m_sc.chNext, 10))
) {
Forward();
m_skipForward = true;
m_visibleChars++;
}
m_sc.SetState(m_section);
}
}
/**
* Handle the line end
*/
void ParseLineEnd ()
{
// embed pp nest level
m_lineState = (m_lineState & 0xFFFFFF00) | m_curNppLevel;
m_lineState = (m_lineState & 0xFFFF00FF) | (m_nLcLevel<<8);
m_lineState = (m_lineState & 0xFF00FFFF) | (m_curNcLevel<<16);
/// @todo optimize linestate_refresh flag!!!
/// as it is only needed when open/close
/// multiline blocks (pp, asm, ml comments)
// TOGGLE_FLAG(m_lineState, LINESTATE_REFRESH);
// set line state
m_styler.SetLineState(m_curLine, m_lineState);
}
/**
* Parse number
*/
bool ParseNumber (int base, int indStart)
{
int fpCount = 0;
// int indStart = m_sc.currentPos;
// skip the word chars?
while (IsADigit(m_sc.ch, base) || m_sc.ch == '.')
{
if (m_sc.ch == '.')
{
if (base != 10 || fpCount || m_sc.chNext == '.') break;
else fpCount++;
}
MoveForward();
}
// set number state
m_sc.ChangeState(m_section + FB_NUMBER);
m_sc.SetState(m_section + FB_NUMBER);
bool invalid = false;
bool hasSuffix = false;
// exponent. allow only for decimal numbers.
if (base == 10)
{
// check for floating point suffixes
// .fraction[[D|E][[+|-]exponent]][suffix]
char ch = tolower(m_sc.ch);
if (ch == 'e' || ch == 'd')
{
hasSuffix = true;
MoveForward();
ch = m_sc.ch;
if (ch == '+' || ch == '-') MoveForward();
while (IsADigit(m_sc.ch, 10))
MoveForward();
}
// type suffix
ch = tolower(m_sc.ch);
if (ch == '!' || ch == 'f' || ch == '#')
{
hasSuffix = true;
MoveForward();
}
}
// Check for integer literal suffixes
// L, %, &, U, UL, LL, ULL
if (!fpCount && !hasSuffix)
{
// have to look for multichar first
if (int s = FindMatch(INTEGER_SUFFIXES_MC))
{
invalid = IsAWordChar(m_sc.GetRelative(s));
MoveForward(s);
}
// check for single char suffixes
else if (FindMatch(INTEGER_SUFFIXES_SC, true))
{
invalid = IsAWordChar(m_sc.chNext);
MoveForward();
}
}
invalid = IsAWordChar(m_sc.ch);
// indicate invalid number.
m_styler.IndicatorFill(indStart, m_sc.currentPos, 0, invalid ? 1 : 0);
// restore state
m_sc.SetState(m_section);
return true;
}
/**
* Parse string and highlight escape sequences (if escape=true)
* do that in one pass. Assume that first character
* is opening quote. So skip the first one
*/
void ParseString (bool escape)
{
bool skip = false;
while (!m_sc.atLineEnd)
{
if (skip) skip = false;
else Forward();
if (m_sc.Match('"', '"'))
{
m_sc.SetState(m_section+FB_STRING_ESCAPE);
m_sc.Forward(2);
m_sc.SetState(m_section+FB_STRING);
skip = true;
continue;
}
else if (m_sc.Match('"'))
{
m_sc.Forward();
m_sc.SetState(m_section);
m_skipForward = true;
return;
}
// no escapes...
if (!escape || m_sc.ch != '\\') continue;
// not an escape code
int indStart = m_sc.currentPos;
bool matched = false;
m_sc.SetState(m_section+FB_STRING_ESCAPE);
Forward();
// Simple sequences (case sensitive!)
if (FindMatch(ESCAPE_CODES))
{
m_sc.ForwardSetState(m_section+FB_STRING);
matched = true;
}
// unicode char in hex \uFFFF
else if (tolower(m_sc.ch) == 'u' && IsNumberRange(1, 4, 16))
{
m_sc.ForwardSetState(m_section+FB_NUMBER);
Forward(4);
matched = true;
}
// ascii char in decimal \123
else if (IsNumberRange(0, 3, 10))
{
m_sc.SetState(m_section+FB_NUMBER);
Forward(3);
matched = true;
}
// ascii escape sequence in FB style oct, bin or hex
else if (m_sc.ch == '&')
{
m_sc.SetState(m_section+FB_NUMBER);
Forward();
// ascii char in hex \&hFF
if (tolower(m_sc.ch) == 'h' && IsNumberRange(1, 2, 16))
{
Forward(3);
matched = true;
}
// ascii char in octal \&o777
else if (tolower(m_sc.ch) == 'o' && IsNumberRange(1, 3, 8))
{
Forward(4);
matched = true;
}
// ascii char in binary \&b11111111
else if (tolower(m_sc.ch) == 'b' && IsNumberRange(1, 8, 2))
{
Forward(9);
matched = true;
}
else
{
m_sc.ChangeState(m_section+FB_STRING);
}
}
// clear or set error indicator
m_sc.SetState(m_section+FB_STRING);
m_styler.IndicatorFill(indStart, m_sc.currentPos, 0, matched ? 0 : 1);
}
// set back to string
m_sc.SetState(m_section);
m_skipForward = true;
}
/**
* Parse identifier
*/
void ParseIdentifier ()
{
m_sc.SetState(PP_DEFAULT);
int curPos = m_sc.currentPos;
// skip the word chars?
while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch))
MoveForward();
// identifier length
size_t len = m_sc.currentPos-curPos+1;
char * s;
// see if identifier fits into existing buffer
// or allocate a new one
if (len > sizeof(m_buffer)) s = new char[len];
else s = m_buffer;
// get the identifier
GetRange(curPos, m_sc.currentPos-1, s, len);
// style it.
if (m_section == ASM_DEFAULT)
{
m_sc.ChangeState(GetAsmKeywordStyle(s));
}
else
{
if (m_section == PP_DEFAULT && strcmpi(s, "once") == 0)
{
m_sc.ChangeState(GetPpKeywordStyle("once"));
}
else
{
if (strcmpi(s, "end") == 0 || strcmpi(s, "declare") == 0)
{
int defStyle = GetFbKeywordStyle(s);
std::string tmp (s);
bool combined = false;
int p = FindNextWord(m_sc.currentPos, m_buffer, sizeof(m_buffer));
if (p)
{
tmp += '-';
tmp += m_buffer;
if (int style = GetFbKeywordStyle(tmp.c_str(), 0))
{
combined = true;
int move = (p-m_sc.currentPos) + strlen(m_buffer);
MoveForward(move);
m_sc.ChangeState(m_section + style);
}
}
// no combination
if (!combined)
{
m_sc.ChangeState(m_section + defStyle);
}
}
else
{
m_sc.ChangeState(m_section + GetFbKeywordStyle(s));
}
}
}
m_sc.SetState(m_section);
// delete allocated buffer.
if (len > sizeof(m_buffer)) delete s;
}
/**
* Parse asm start block. Multiline or single line
*/
void ParseAsmStart ()
{
int indent = m_indent;
m_skipForward = true;
m_sc.SetState(ASM_DEFAULT + GetFbKeywordStyle("asm"));
Forward(3);
m_sc.SetState(ASM_DEFAULT);
m_visibleChars+=3;
SkipSpacesAndTabs();
if (!m_sc.atLineEnd) m_skipForward = true;
if (!IsAWordChar(m_sc.ch)
&& (!m_sc.MatchIgnoreCase("rem") || !IsAWordChar(m_sc.GetRelative(3))
))
{
if (m_nLcLevel) m_nLcLevel++;
m_activeState = ASM_DEFAULT;
m_stateStack->PushState(m_curLine, indent, m_activeState);
SET_FLAG(m_lineState, LINESTATE_MULTILINE_ASM);
}
}
/**
* Parse ASM end block
*/
void ParseAsmEnd ()
{
// make sure it is a multiline asm block
/// @note ?????????????
/// m_activeState != ASM_DEFAULT
// int state = m_stateStack->GetActiveState(m_curLine).state;
// if (state != ASM_DEFAULT) return;
// check if next keyword is ASM (end asm)
char nw[4];
if (FindNextWord(m_sc.currentPos+4, nw, 4) && (strcmpi(nw, "asm") == 0))
{
int style = GetFbKeywordStyle("end-asm", 0);
m_sc.SetState(m_section + (style ? style : GetFbKeywordStyle("end")));
Forward(3);
m_sc.SetState(m_section);
SkipSpacesAndTabs();
m_sc.SetState(m_section + (style ? style : GetFbKeywordStyle("asm")));
Forward(3);
UNSET_FLAG(m_lineState, LINESTATE_MULTILINE_ASM);
// check if line end then draw asm colours
// to the end. Otherwise end asm block abruptly
m_stateStack->PopState(m_curLine);
m_activeState = m_stateStack->GetActiveState(m_curLine).state;
if (m_sc.ch != '\r' && m_sc.ch != '\n')
{
m_sc.SetState(m_activeState);
m_skipForward = true;
}
else m_sc.SetState(m_section);
}
}
/**
* Parse line continuation _
*
* @todo check if line continuation is really needed ?
*/
void ParseLineContinuation ()
{
m_sc.SetState (m_section);
SET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION);
if (!m_lineCont || m_section != m_activeState)
{
int indent = m_realIndent;
LOG("Push line continuation", 0);
m_nLcLevel++;
m_activeState = m_section;
m_stateStack->PushState(m_curLine, indent, m_section);
}
else
{
LOG("Nested contination", 0);
}
}
/**
* Parse a single line or a multiline comment
* search for urls within
*/
void ParseComment ()
{
//m_skipForward = true;
for ( ; !m_sc.atLineEnd; Forward() )
{
// Handle multiline comment start/close
if (m_curNcLevel)
{
// '/ END
if (m_sc.Match('\'', '/'))
{
if (--m_curNcLevel == 0)
{
int state = m_sc.state;
m_stateStack->PopState(m_curLine);
Forward(2);
m_activeState = m_stateStack->GetActiveState(m_curLine).state;
m_sc.SetState(m_activeState);
if (!IsInComment(m_activeState))
{
if (m_sc.ch == '\r' || m_sc.ch == '\n')
m_sc.ChangeState(state);
else
m_skipForward = true;
}
return;
}
}
// /' START
else if (m_sc.Match('/', '\''))
{
m_activeState = m_sc.state;
//m_stateStack->PushState(m_curLine, 0, m_activeState);
m_curNcLevel++;
Forward(2);
}
}
// needs a non word char infornt
if (IsAWordChar(m_sc.chPrev) || !IsAWordChar(m_sc.ch)) continue;
// match uri schemes. if matched then set state
int len = FindMatch(URI_SCHEMES);
if (len == 0) continue;
m_sc.SetState(m_section + FB_COMMENT_URL);
SkipNonWhiteSpaces();
m_sc.SetState(m_section + FB_COMMENT);
if (m_sc.atLineEnd)
return;
}
}
/**
* Parses single line qomment and checks if contains
* any meta keywords (lang, dynamic, static, ...)
* if yes then set style to PP_DEFAULT, highlight the keyword
* and return true.
*/
void ParseSingleLineComment ()
{
// check if is valid start ?
if (m_sc.atLineEnd || m_sc.ch != '$') goto meta_error;
// mov forth and skip any spaces
Forward();
SkipSpacesAndTabs ();
if (m_sc.atLineEnd) goto meta_error;
// check if this is a valid meta statament
if (HighlightMetaKeyword("lang", 4)) return;
// allowed only in QB and LITE
if (m_dialect > DIALECT_LITE) goto meta_error;
// include
if (HighlightMetaKeyword("include", 7)) return;
// dynamic
if (HighlightMetaKeyword("dynamic", 7)) return;
// static
if (HighlightMetaKeyword("static", 6)) return;
// avoid call to Forward by Parse() since we already
// moved forward.
meta_error:
m_skipForward = true;
return;
}
/**
* Hightlight a QB style metakeyword inside single
* line comments if matches
* return true if matched.
*/
bool HighlightMetaKeyword (const char * kw, int len)
{
// return if not matches or next char is a word char
if (IsAWordChar(m_sc.GetRelative(len)) || !m_sc.MatchIgnoreCase(kw))
return false;
// colorise
m_sc.Forward(len);
m_sc.ChangeState(GetPpKeywordStyle(kw));
m_sc.SetState(PP_DEFAULT);
return true;
}
/**
* Parse preprocessor start #
*/
void ParsePreprocessor ()
{
int indent = m_indent;
m_sc.SetState(PP_DEFAULT);
Forward();
SkipSpacesAndTabs();
if (m_sc.atLineEnd) return;
m_skipForward = true;
// macro's can nest and cover multiple lines
if (m_sc.MatchIgnoreCase("macro") && !IsAWordChar(m_sc.GetRelative(5)))
{
m_sc.ChangeState(GetPpKeywordStyle("macro"));
Forward(5);
m_sc.SetState(PP_DEFAULT);
m_curNppLevel++;
// push state
m_activeState = PP_DEFAULT;
m_stateStack->PushState(m_curLine, indent, PP_DEFAULT);
}
else if (m_sc.MatchIgnoreCase("endmacro") && !IsAWordChar(m_sc.GetRelative(8)))
{
m_sc.ChangeState(GetPpKeywordStyle("endmacro"));
Forward(8);
m_sc.SetState(PP_DEFAULT);
if (m_curNppLevel)
{
m_curNppLevel--;
int state = m_stateStack->PopState(m_curLine).state;
// is it a nested assembly?
if (state == ASM_DEFAULT)
state = m_stateStack->PopState(m_curLine).state;
// check if line end then draw asm colours
// to the end. Otherwise end asm block abruptly
m_activeState = m_stateStack->GetActiveState(m_curLine).state;
if (m_sc.ch != '\r' && m_sc.ch != '\n')
{
m_sc.SetState(m_activeState);
m_skipForward = true;
}
else m_sc.SetState(m_section);
}
}
else if (IsAWordChar(m_sc.ch))
{
// m_sc.SetState(PP_DEFAULT);
int curPos = m_sc.currentPos;
// skip the word chars?
while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch))
{
Forward();
}
char s[25];
// m_sc.GetCurrent(s, sizeof(s));
GetRange(curPos, m_sc.currentPos-1, s, sizeof(s));
m_sc.ChangeState(GetPpKeywordStyle(s));
m_sc.SetState(PP_DEFAULT);
}
}
/**
* Get Section type
*/
int GetSectionType (int style)
{
if (style <= FB_SECTION_LAST)
return FB_DEFAULT;
if (style <= ASM_SECTION_LAST)
return ASM_DEFAULT;
if (style <= PP_SECTION_LAST)
return PP_DEFAULT;
return FB_DEFAULT;
}
/**
* Nested and indented code blocks that have
* a background. Draw those in proper nesting order
*/
void DrawIndentedBlocks ()
{
/// @note ????
if (m_activeState == FB_DEFAULT) return;
int currentState = m_sc.state;
int globalIndent = 0;
CStateRange range = m_stateStack->GetStateRange(m_curLine);
for ( ; range.first != range.second; )
{
// get inner block indent level
int state = (range.first++)->state;
int indent = range.first->indent;
if (indent == 0) continue;
// fix inner indend levels
if (indent > globalIndent) indent-= globalIndent;
else continue;
globalIndent += indent;
// get the state to colour to
m_sc.SetState(state);
// colour the background while there are spaces or tabs
while (indent && IsASpaceOrTab(m_sc.ch))
{
if (m_sc.ch == '\t')
{
if (indent > m_tabWidth) indent-= m_tabWidth;
else indent = 0;
}
else
{
indent--;
}
Forward();
}
}
// restore correct state
m_sc.SetState(currentState);
}
/**
* Skip the tabs and spaces
* but stop at anything else
*/
void SkipSpacesAndTabs ()
{
while (!m_sc.atLineEnd && IsASpaceOrTab(m_sc.ch))
Forward();
}
/**
* Skip non whitespaces. Stop ad line end or
* a space or a tab
*/
void SkipNonWhiteSpaces ()
{
while (!m_sc.atLineEnd && !IsASpaceOrTab(m_sc.ch))
Forward();
}
/**
* Move forward. Update line indent
*/
void Forward (int cnt = 1)
{
while (cnt--)
{
m_sc.Forward();
if (m_sc.atLineStart)
{
m_indent = 0;
}
else
{
if (m_sc.ch == '\t') m_indent += m_tabWidth;
else m_indent++;
}
}
}
/**
* Move forward and set m_skipForward to true
* and increment visible char count
*/
void MoveForward (int amount = 1)
{
Forward(amount);
m_skipForward = true;
m_visibleChars+=amount;
}
/**
* Find the string from an array that matches
* and return it's length
* or 0 if none
*/
int FindMatch (const char * const matches[])
{
for (int i = 0; matches[i]; i++)
if (m_sc.MatchIgnoreCase(matches[i]))
{
LOG("match found %s", matches[i]);
return strlen(matches[i]);
}
return 0;
}
/**
* Check if any of the chars matches ?
* return char that matches or a 0
*/
char FindMatch(const char matches[], bool ignoreCase = false)
{
if (ignoreCase)
{
for (int i = 0; matches[i]; i++)
if (tolower(m_sc.ch) == matches[i])
return matches[i];
}
else
{
for (int i = 0; matches[i]; i++)
if (m_sc.ch == matches[i])
return matches[i];
}
return 0;
}
/**
* Retreave a range of characters into a string
*/
void GetRange(unsigned int start, unsigned int end,
char *s, unsigned int len)
{
unsigned int i = 0;
while ((i < end - start + 1) && (i < len-1))
{
s[i] = static_cast<char>(tolower(m_styler[start + i]));
i++;
}
s[i] = '\0';
}
/**
* Get non whitespace range for the lenght
* skip any spaces or tabs and return when hitting first
* non-printable character (space, tab, newline)
*/
int FindNextWord (unsigned int start, char *s, unsigned int len)
{
// skip any spaces or tabs
for ( ; ; start++)
{
char ch = m_styler[start];
if (IsAWordChar(ch)) break;
if (ch == '\n' || ch == '\r') return 0;
if (!IsASpaceOrTab(ch)) return 0;
}
// GetRange (start, start + len, s, len);
unsigned int i = 0;
while ( i < len )
{
char ch = static_cast<char>(tolower(m_styler[start + i]));
if (IsAWordChar(ch)) s[i] = ch;
else break;
i++;
}
s[i] = '\0';
return start;
}
/**
* Extended to accept accented characters
*/
bool IsAWordChar(int ch)
{
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
/**
* Check if the char is a valid FB operator
*/
bool IsOperator (int ch)
{
return ch == '&'
|| ch == '*'
|| ch == '('
|| ch == ')'
|| ch == '-'
|| ch == '+'
|| ch == '='
|| ch == '{'
|| ch == '}'
|| ch == '['
|| ch == ']'
|| ch == ':'
|| ch == ';'
|| ch == '@'
|| ch == '#'
|| ch == '\\'
|| ch == ','
|| ch == '<'
|| ch == '>'
|| ch == '.'
|| ch == '/'
|| ch == '?'
;
}
/**
* Check if range of characters are numbers of the base
*/
bool IsNumberRange (int startPos, int count, int base)
{
for (--count; count>=0; count--)
{
if (!IsADigit(m_sc.GetRelative(startPos+count), base))
return false;
}
return true;
}
/**
* If the given keyword is a preprocessor keyword then
* highlight it to appropriate PP keyword style
*/
int GetPpKeywordStyle (const char * kw, int defStyle = PP_IDENTIFIER)
{
if (m_keywords[KEYWORD_PP_ONE]->InList(kw))
return PP_KEYWORD_ONE;
else if (m_keywords[KEYWORD_PP_TWO]->InList(kw))
return PP_KEYWORD_TWO;
return defStyle;
}
/**
* Get FB keyword type. If not found FB_IDENTIFIER is returned
*/
int GetFbKeywordStyle (const char * kw, int defStyle = FB_IDENTIFIER)
{
if (m_keywords[KEYWORD_ONE]->InList(kw))
return FB_KEYWORD_ONE;
else if (m_keywords[KEYWORD_TWO]->InList(kw))
return FB_KEYWORD_TWO;
else if (m_keywords[KEYWORD_THREE]->InList(kw))
return FB_KEYWORD_THREE;
else if (m_keywords[KEYWORD_FOUR]->InList(kw))
return FB_KEYWORD_FOUR;
return defStyle;
}
/**
* Get ASM block keyword type
*/
int GetAsmKeywordStyle (const char * kw, int defStyle = ASM_IDENTIFIER)
{
if (m_keywords[KEYWORD_ASM_ONE]->InList(kw))
return ASM_KEYWORD_ONE;
else if (m_keywords[KEYWORD_ASM_TWO]->InList(kw))
return ASM_KEYWORD_TWO;
return defStyle;
}
/**
* Printf compatible function that will output to wxMessageLog
*/
/*
void Log (const char * msg, ...) // __attribute__((format(printf, 2, 3)))
{
// do thr printf
va_list ap;
va_start(ap, msg);
char temp[4096];
vsnprintf (temp, 4096, msg, ap);
va_end(ap);
// output the wxLog
wxString logMsg(temp, wxConvUTF8);
wxLogMessage(logMsg);
}
*/
// style context
StyleContext & m_sc;
// Accessor
Accessor & m_styler;
// keywords
WordList ** m_keywords;
// current section
int m_section;
// current line state
int m_lineState;
// current line
int m_curLine;
// count visible characters
int m_visibleChars;
// line indentation
int m_indent;
// real indent
int m_realIndent;
// current FB dialect
int m_dialect;
// indent amount
int m_tabWidth;
// Force to skip default call to Forward()
bool m_skipForward;
//
bool m_indentedBoxes;
// Line states structure
CLineStates * m_stateStack;
// Active state
int m_activeState;
// nested pp level
int m_curNppLevel;
// nested multiline comments
int m_curNcLevel;
// nested line continuations
int m_nLcLevel;
// line continuation
bool m_lineCont;
// char buffer
char m_buffer[512];
};
/**
* Colorise FB document
*/
static void ColouriseFB (
unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler )
{
// Styler
styler.StartAt(startPos, 63);
StyleContext sc (startPos, length, initStyle, styler, 63);
// Fb source lexer
CFbSourceLexer l (sc, styler, keywordlists);
#ifdef USE_LOG
wxLogMessage(">>>> styled from: %d, length: %d\n"
"---------------------------------------------------------------",
startPos, length);
#endif
}
static bool IsVBComment(Accessor &styler, int pos, int len) {
return len>0 && styler[pos]=='\'';
}
/**
* Should folding use LineStates info? In wich case the parser should
* get states for all possible scope block starts and ends.
*/
static void FoldVBDoc(unsigned int startPos, int length, int,
WordList *[], Accessor &styler) {
int endPos = startPos + length;
// Backtrack to previous line in case need to fix its fold status
int lineCurrent = styler.GetLine(startPos);
if (startPos > 0) {
if (lineCurrent > 0) {
lineCurrent--;
startPos = styler.LineStart(lineCurrent);
}
}
int spaceFlags = 0;
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment);
char chNext = styler[startPos];
for (int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
int lev = indentCurrent;
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
// Line after is blank so check the next - maybe should continue further?
int spaceFlags2 = 0;
int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment);
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
}
indentCurrent = indentNext;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
}
}
}
/**
* Keywords
*/
static const char * const fbWordListDesc[] = {
"FB_kw1",
"FB_kw2",
"FB_kw3",
"FB_kw4",
"FB_pp1",
"FB_pp2",
"FB_asm1",
"FB_asm2",
0
};
// Add the lexer module
LexerModule lmFB(
FREEBASIC, // identifier
ColouriseFB, // colorise proc
"FreeBASIC", // name
FoldVBDoc, // fold proc
fbWordListDesc, // keywords descriptor
6 // number of style bits used
);
<file_sep>/fbide-wx/sdk/include/sdk/Variant.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef VARIANT_H_INCLUDED
#define VARIANT_H_INCLUDED
namespace fb
{
/**
* Very simple variant class for holding
* strings, ints and booleans.
* the reason for not using wxVariant is that
* it tends to throw errors if value not set
* rather than return empty value.
*/
class DLLIMPORT CVariant
{
public :
// default constructor
CVariant () {}
~CVariant () {}
// CVariant
CVariant (const CVariant & value)
: m_value(value.m_value)
{}
void operator = (const CVariant & rhs)
{ m_value = rhs.m_value; }
void operator += (const CVariant & rhs)
{ m_value += rhs.m_value; }
bool operator == (const CVariant & rhs)
{ return m_value == rhs.m_value; }
bool operator != (const CVariant & rhs)
{ return m_value != rhs.m_value; }
// wxString
CVariant (const wxString & value)
: m_value(value)
{}
wxString AsString (const wxString & defValue = _T(""))
{ return m_value.Len() ? m_value : defValue; }
wxString AsString (const char * defValue)
{ return m_value.Len() ? m_value : wxString(defValue, wxConvUTF8); }
void operator = (const wxString & rhs)
{ m_value = rhs; }
void operator += (const wxString & rhs)
{ m_value += rhs; }
bool operator == (const wxString & rhs)
{ return m_value == rhs; }
bool operator != (const wxString & rhs)
{ return m_value != rhs; }
// const char *
explicit CVariant (const char * value)
: m_value(wxString(value, wxConvUTF8))
{}
void operator = (const char * rhs)
{ m_value = wxString(rhs, wxConvUTF8); }
void operator += (const char * rhs)
{ m_value += wxString(rhs, wxConvUTF8); }
bool operator == (const char * rhs)
{ return m_value == wxString(rhs, wxConvUTF8); }
bool operator != (const char * rhs)
{ return m_value != wxString(rhs, wxConvUTF8); }
// const wxChar *
explicit CVariant (const wxChar * value)
: m_value(wxString(value, wxConvUTF8))
{}
void operator = (const wxChar * rhs)
{ m_value = rhs; }
void operator += (const wxChar * rhs)
{ m_value += rhs; }
bool operator == (const wxChar * rhs)
{ return m_value == rhs; }
bool operator != (const wxChar * rhs)
{ return m_value != rhs; }
// const int *
CVariant (int value)
{ *this = value; }
int AsInt (int defValue = 0)
{
if (!m_value.Len()) return defValue;
long v;
if (!m_value.ToLong(&v)) return (int)AsBool();
return v;
}
void operator = (int rhs)
{ m_value.Empty(); m_value << rhs; }
void operator += (int rhs)
{ *this = AsInt() + rhs; }
bool operator == (int rhs)
{ return AsInt() == rhs; }
bool operator != (int rhs)
{ return AsInt() != rhs; }
// As bool
bool AsBool (bool defValue = false)
{
if (!m_value.Len()) return defValue;
if (m_value == _T("0"))
return false;
if (m_value==_T("true")||m_value==_T("yes")||m_value==_T("on"))
return true;
long v;
if (m_value.ToLong(&v)) return true;
return false;
}
void operator = (bool rhs)
{ m_value = rhs ? _T("true") : _T("false"); }
bool operator == (bool rhs)
{ return AsBool() == rhs; }
bool operator != (bool rhs)
{ return AsBool() != rhs; }
private :
wxString m_value;
};
}
#endif // VARIANT_H_INCLUDED
<file_sep>/fbide-wx/sdk/include/sdk/StyleInfo.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EDITORSTYLEINFO_H_INCLUDED
#define EDITORSTYLEINFO_H_INCLUDED
#define STYLE_DEFAULT_FONT_SIZE 10
#define STYLE_DEFAULT_FG _T("black")
#define STYLE_DEFAULT_BG _T("white")
#define STYLE_DEFAULT_FONT _T("Courier New")
namespace fb
{
/**
* Contains info about the styling
*
* @todo add opacity and width
*/
struct DLLIMPORT CStyleInfo
{
bool isOk;
bool bold;
bool italic;
bool underlined;
int size;
int width;
int opacity;
wxString font;
wxColor fg;
wxColor bg;
wxColor outline;
CStyleInfo ()
: isOk(false),
bold(false), italic(false), underlined(false),
size(STYLE_DEFAULT_FONT_SIZE), width(0), opacity(0),
font(STYLE_DEFAULT_FONT)
{}
/**
* Get style info as string
*/
wxString AsString () const
{
wxString tmp;
// font-weight
tmp << _T("font-weight : ");
if (bold) tmp << _T("bold");
else tmp << _T("normal");
tmp << _T(";\n");
// font-style
tmp << _T("font-style : ");
if (italic) tmp << _T("italic");
else tmp << _T("normal");
tmp << _T(";\n");
// text decoration
tmp << _T("text-decoration : ");
if (underlined) tmp << _T("underline");
else tmp << _T("none");
tmp << _T(";\n");
// font size
tmp << _T("font-size : ");
tmp << size << _T("px");
tmp << _T(";\n");
// width
tmp << _T("width : ");
tmp << width << _T("px");
tmp << _T(";\n");
// fg
tmp << _T("color : ");
tmp << fg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
// bg
tmp << _T("background-color : ");
tmp << bg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
// border
tmp << _T("outline-color : ");
tmp << outline.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
// opacity
tmp << _T("opacity : ");
tmp << opacity;
tmp << _T(";");
return tmp;
}
};
/**
* Styles manager
*/
class DLLIMPORT CStyleParser
{
public :
// construct the style info object
CStyleParser (const wxString & filename);
// Parse the file
void LoadFile (const wxString & filename);
// Add CSS rule
void SetCssRule (
const wxString & selector,
const wxString & rule,
const wxArrayString & values,
const wxString & inheritFrom = _T(".default")
);
// Add CSS rule
// Same as above but only one value
void SetCssRule (
const wxString & selector,
const wxString & rule,
const wxString & value,
const wxString & inheritFrom = _T(".default")
);
// check if path exists
bool PathExists (const wxString & selector);
// Get styles for the selector
CStyleInfo GetStyle (const wxString & selector, const wxString & inherit = _T(".default"));
private :
// private data implementation "pimpl"
struct CData;
std::auto_ptr<CData> m_data;
};
};
#endif // EDITORSTYLEINFO_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Document.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "Manager.h"
#include "DocManager.h"
#include "Document.h"
using namespace fbi;
// get new document id
static int GetNewDocId()
{
static int cnt = 0;
return ++cnt;
}
/**
* Create new document
*/
Document::Document () : m_id(GetNewDocId()), m_window(nullptr)
{
SetDocTitle("");
}
/**
* Destroy the document
*/
Document::~Document ()
{
}
/**
* Set document title
*/
void Document::SetDocTitle (const wxString & name)
{
if (!name.Len())
{
m_title = GET_LANG().Get("document.unnamed", "id", wxString() << GetDocId());
}
else
{
m_title = name;
}
}
<file_sep>/fbide-wx/sdk/src/DocManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/DocManager.h"
#include "sdk/UiManager.h"
#include "sdk/TypeManager.h"
#include "sdk/Document.h"
using namespace fb;
extern const int ID_DOCUMENT_NOTEBOOK;
struct CDocManager::CData : wxEvtHandler
{
// event handlers
void OnNew (wxCommandEvent & event);
void OnOpen (wxCommandEvent & event);
void OnDocumentClosed (CDocumentBase * doc, int evt);
/**
* Any command event that shoudl be routed to the
* document
*/
void OnMenuEvent (wxCommandEvent & event)
{
// Find active document
CDocumentBase * doc = GET_UIMGR()->GetActiveDocument();
if (doc == NULL) return;
wxWindow * wnd = dynamic_cast<wxWindow *>(doc);
wxASSERT(wnd != NULL);
wnd->wxEvtHandler::ProcessEvent(event);
}
/**
* Save document
*/
void OnSave (wxCommandEvent & event)
{
CDocumentBase * doc = GET_UIMGR()->GetActiveDocument();
if (doc == NULL) return;
wxString file = doc->GetDocFile();
// if doc has a file then ASSUME that this file BELONGS
// to the doc and just save the file.
if (file.Len())
{
doc->SaveDoc(file);
return;
}
// managers
CUiManager & ui = *GET_UIMGR();
CTypeManager & tm = *GET_TYPEMGR();
CManager & mgr = *GET_MGR();
//
wxFileDialog dlg (
0L, // parent window
mgr.GetLang(_T("save-file")), // title
_T(""), _T(""), // default dir, default file
tm.GetFileFilters(true), // wildcards
wxFD_SAVE |wxFD_OVERWRITE_PROMPT
);
if (dlg.ShowModal() != wxID_OK) return;
// get file. Check if we are over writing it?
file = dlg.GetPath();
doc->SaveDoc(file);
doc->SetDocFile(file);
}
// members
typedef std::vector<CDocumentBase *> docList;
docList m_docList;
CDocManager * m_parent;
// we process events here
DECLARE_EVENT_TABLE();
};
/**
* Event table
*/
BEGIN_EVENT_TABLE(CDocManager::CData, wxEvtHandler)
EVT_MENU(wxID_NEW, CDocManager::CData::OnNew)
EVT_MENU(wxID_OPEN, CDocManager::CData::OnOpen)
EVT_MENU(wxID_UNDO, CDocManager::CData::OnMenuEvent)
EVT_MENU(wxID_REDO, CDocManager::CData::OnMenuEvent)
EVT_MENU(wxID_CUT, CDocManager::CData::OnMenuEvent)
EVT_MENU(wxID_COPY, CDocManager::CData::OnMenuEvent)
EVT_MENU(wxID_PASTE,CDocManager::CData::OnMenuEvent)
EVT_MENU(wxID_SAVE, CDocManager::CData::OnSave)
END_EVENT_TABLE()
/**
* create new default document
*/
void CDocManager::CData::OnNew (wxCommandEvent & event)
{
CUiManager & ui = *GET_UIMGR();
CTypeManager & tm = *GET_TYPEMGR();
CManager & mgr = *GET_MGR();
// Freeze stops updating the window.
// so stop updating until all is properly loaded
mgr.GetFrame()->Freeze();
wxString type = _T("default");
CDocumentBase * doc = tm.NewDocument(type);
if (doc == 0L)
{
mgr.GetFrame()->Thaw();
return; //throw EXCEPTION(_T("Document type '") + type + _T("' is not registered"));
}
m_docList.push_back(doc);
// destruction event (for cleanup)
doc->evt[DocEvent::DESTROY] += MakeDelegate(this, &CDocManager::CData::OnDocumentClosed);
// if it's a content document add to the document area
if (doc->GetDocType() == DOCUMENT_MANAGED)
{
if (doc) ui.AddDocument(doc, true);// doc->GetDocWindow(), doc->GetDocTitle(), true);
}
mgr.GetFrame()->Thaw();
}
/**
* show open dialog
*/
void CDocManager::CData::OnOpen (wxCommandEvent & event)
{
CTypeManager & tm = *GET_TYPEMGR();
CManager & mgr = *GET_MGR();
wxFileDialog dlg (
0L, // parent window
mgr.GetLang(_T("load-file")), // title
_T(""), _T(""), // default dir, default file
tm.GetFileFilters(true), // wildcards
wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE
);
if (dlg.ShowModal() == wxID_OK)
{
wxArrayString paths;
dlg.GetPaths(paths);
m_parent->Open(paths);
}
}
/**
*
*/
void CDocManager::CData::OnDocumentClosed (CDocumentBase * doc, int evt)
{
docList::iterator iter = m_docList.begin();
while (iter != m_docList.end())
{
if (*iter == doc)
{
m_docList.erase(iter);
return;
}
iter++;
}
}
/**
* Create instance
*/
CDocManager::CDocManager () : m_data(new CDocManager::CData)
{
m_data->m_parent = this;
wxFrame * frame = GET_MGR()->GetFrame();
if (frame == 0L) throw EXCEPTION(_T("UiManager must be initalized and have a frame before creating DocManager!"));
// add this manager to frame event handlers list
frame->PushEventHandler(m_data);
}
/**
* Destroy and do cleanup
*/
CDocManager::~CDocManager()
{
// GET_MGR()->GetFrame()->RemoveEventHandler(m_data);
delete m_data;
}
/**
* Find document by a window pointer
*/
CDocumentBase * CDocManager::FindDocument (wxWindow * wnd)
{
//if (wnd == NULL) return NULL;
wxASSERT(wnd != NULL);
CData::docList::iterator iter = m_data->m_docList.begin();
while (iter != m_data->m_docList.end())
{
CDocumentBase * doc = *iter;
if (doc->GetDocWindow() == wnd) return doc;
iter++;
}
// recursive
return FindDocument(wnd->GetParent());
}
/**
* Open a single file
*/
CDocumentBase * CDocManager::Open (const wxString & filename, bool show)
{
CUiManager & ui = *GET_UIMGR();
CTypeManager & tm = *GET_TYPEMGR();
// CManager & mgr = *GET_MGR();
CDocumentBase * doc = tm.LoadFile(filename);
if (doc == 0L) return NULL;
m_data->m_docList.push_back(doc);
// destruction event (for cleanup)
doc->evt[DocEvent::DESTROY] += MakeDelegate(m_data, &CDocManager::CData::OnDocumentClosed);
// if it's a content document add to the document area
if (doc->GetDocType() == DOCUMENT_MANAGED)
{
if (doc) ui.AddDocument(doc, show);
}
return doc;
}
/**
* Open several files
*/
void CDocManager::Open (const wxArrayString & filenames)
{
//CUiManager & ui = *GET_UIMGR();
//CTypeManager & tm = *GET_TYPEMGR();
CManager & mgr = *GET_MGR();
mgr.GetFrame()->Freeze();
for (size_t i = 0; i < filenames.Count(); i++)
{
Open(filenames[i], i == 0);
}
mgr.GetFrame()->Thaw();
}
/**
* Close all opent documents.
* Each doc might ask SAVE
*
* @return success
*/
bool CDocManager::CloseAll ()
{
CUiManager * ui = CManager::Get()->GetUiManager();
CData::docList::iterator iter = m_data->m_docList.begin();
while (iter != m_data->m_docList.end())
{
CDocumentBase * doc = *iter;
iter = m_data->m_docList.erase(iter);
ui->RemoveDocument(doc);
delete doc;
}
return true;
}
<file_sep>/fbide-wx/sdk/src/EditorModMargin.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk/Editor.h"
#include "sdk/EditorEvent.h"
#include "EditorModMargin.h"
#include <algorithm>
using namespace fb;
// Set bit flags
static inline void SET_FLAG (unsigned & value, unsigned flag)
{ value |= flag; }
// unset bit flags
static inline void UNSET_FLAG (unsigned & value, unsigned flag)
{ value &= (~flag); }
// get cell offset
#define GET_OFFSET(_cell) (((_cell) % STATES_IN_CELL) * BITS_PER_STATE)
// get cell index
#define GET_INDEX(_cell) (((_cell) / STATES_IN_CELL) + 1)
// get the state
#define GET_STATE(_val, _offset) (((_val) >> (_offset)) & MARKER_FLAGS)
// Calculate the new state
#define MAKE_STATE(_val, _offset, _marker) \
(((_val) & (~(MARKER_FLAGS << (_offset)))) | ((_marker) & MARKER_FLAGS) << (_offset))
// show logs
#define SHOW_LOG
// wrapper macro
#ifdef SHOW_LOG
# define LOG(_m) _m
#else
# define LOG(_m)
#endif
/**
* Constructor
*/
CEditorModMargin::CEditorModMargin ( CEditor & editor )
: m_editor ( editor )
{
{/*
Push(1, FLAG_NONE);
Push(1, FLAG_EDITED);
Push(1, FLAG_EDITED);
Push(1, FLAG_EDITED);
Push(1, FLAG_SAVED);
Push(1, FLAG_EDITED);
Push(1, FLAG_EDITED);
Push(1, FLAG_SAVED);
Push(1, FLAG_EDITED);
while ( m_lines[1][0] != -1 )
{
int p = Undo( 1 );
if ( p == FLAG_NONE )
{
LOG_MSG("FLAG_NONE");
}
else if ( p == FLAG_SAVED )
{
LOG_MSG("FLAG_SAVED");
}
else if ( p == FLAG_EDITED )
{
LOG_MSG("FLAG_EDITED");
}
else
{
LOG_MSG_INT("Wrong!!!", p);
}
}
*/}
}
/**
* Push line state
*/
void CEditorModMargin::Push(unsigned line, unsigned marker)
{
#ifdef SHOW_LOG
if ( marker == FLAG_SAVED ) { LOG_MSG("Push ( FLAG_SAVED ) {"); }
else if ( marker == FLAG_EDITED ) { LOG_MSG("Push ( FLAG_EDITED ) {"); }
else { LOG_MSG("Push ( FLAG_NONE ) {"); }
LOG_MSG_INT(" ", line);
LOG_MSG_INT(" ", marker);
#endif
// Ensure that vector is big enough
if (line >= m_lines.size())
{
for (size_t s = m_lines.size(); s <= line; s++)
m_lines.push_back(IntVector());
}
// get modification info
IntVector & mod = m_lines[line];
// get the cell or add a new entry
if (mod.size() < (size_t)2)
{
mod.push_back(-1);
mod.push_back(0);
}
// get cell number
int cell = ++mod[0];
LOG(LOG_MSG_INT(" ", cell));
LOG(LOG_MSG_INT(" ", mod[0]));
// get vector index and bit offset
int offset = GET_OFFSET(cell);
int index = GET_INDEX(cell);
LOG(LOG_MSG_INT(" ", offset));
LOG(LOG_MSG_INT(" ", index));
// expand array if needed
if ((int)mod.size() <= index) mod.push_back(0);
// mark the cell
mod[index] = MAKE_STATE(mod[index], offset, marker);
LOG(LOG_MSG("}"));
}
/**
* Get top value ( current )
*/
unsigned CEditorModMargin::Top ( unsigned line )
{
#ifdef SHOW_LOG
LOG_MSG("Top {");
LOG_MSG_INT(" ", line);
#endif
// no state here
if (m_lines.size() <= line)
{
LOG(LOG_MSG("} = FLAG_NONE (m_lines.size() <= line)"));
return FLAG_NONE;
}
// get mod
IntVector & mod = m_lines[line];
// if it's too small?
if (mod.size() < 2)
{
LOG(LOG_MSG("} = FLAG_NONE (mod.size() < 2)"));
return FLAG_NONE;
}
// no states ?
if (mod[0] == (unsigned)-1)
{
LOG(LOG_MSG("} = FLAG_NONE (mod[0] == -1)"));
return FLAG_NONE;
}
// get cell
int cell = mod[0];
LOG(LOG_MSG_INT(" ", cell));
LOG(LOG_MSG_INT(" ", mod[0]));
// get vector index and bit offset
int offset = GET_OFFSET(cell);
int index = GET_INDEX(cell);
LOG(LOG_MSG_INT(" ", offset));
LOG(LOG_MSG_INT(" ", index));
// Get cell state
#ifdef SHOW_LOG
unsigned f = GET_STATE(mod[index], offset);
if (f == FLAG_NONE) { LOG_MSG("} = FLAG_NONE"); }
else if ( f == FLAG_EDITED) { LOG_MSG("} = FLAG_EDITED"); }
else if ( f == FLAG_SAVED) { LOG_MSG("} = FLAG_SAVED"); }
return f;
#else
return GET_STATE(mod[index], offset);
#endif
}
/**
* Pop topmost and check next value
*/
unsigned CEditorModMargin::Undo (unsigned line)
{
#ifdef SHOW_LOG
LOG_MSG("Undo {");
LOG_MSG_INT(" ", line);
#endif
// no state here
if (m_lines.size() <= line)
{
LOG(LOG_MSG("} = FLAG_NONE (m_lines.size() <= line)"));
return FLAG_NONE;
}
// get mod
IntVector & mod = m_lines[line];
// if it's too small?
if (mod.size() < 2)
{
LOG(LOG_MSG("} = FLAG_NONE (mod.size() < 2)"));
return FLAG_NONE;
}
// no states ?
if (mod[0] == (unsigned)-1)
{
LOG(LOG_MSG("} = FLAG_NONE ( (int)mod[0] == -1 )"));
return FLAG_NONE;
}
else if ( mod[0] == 0 )
{
mod[0]--;
LOG(LOG_MSG("} = FLAG_NONE ( (int)mod[0] == 0 )"));
return FLAG_NONE;
}
// get cell
int cell = --mod[0];
LOG(LOG_MSG_INT(" ", cell));
LOG(LOG_MSG_INT(" ", mod[0]));
// get vector index and bit offset
int offset = GET_OFFSET(cell);
int index = GET_INDEX(cell);
LOG(LOG_MSG_INT(" ", offset));
LOG(LOG_MSG_INT(" ", index));
// Get cell state
#ifdef SHOW_LOG
unsigned f = GET_STATE(mod[index], offset);
if (f == FLAG_NONE) { LOG_MSG("} = FLAG_NONE"); }
else if ( f == FLAG_EDITED) { LOG_MSG("} = FLAG_EDITED"); }
else if ( f == FLAG_SAVED) { LOG_MSG("} = FLAG_SAVED"); }
return f;
#else
return GET_STATE(mod[index], offset);
#endif
}
/**
* Redo the line
*/
unsigned CEditorModMargin::Redo ( unsigned line )
{
#ifdef SHOW_LOG
LOG_MSG("Redo {");
LOG_MSG_INT(" ", line);
#endif
// no state here
if (m_lines.size() <= line)
{
LOG(LOG_MSG("} = FLAG_NONE (m_lines.size() <= line)"));
return FLAG_NONE;
}
// get mod
IntVector & mod = m_lines[line];
// if it's too small?
if (mod.size() < 2)
{
LOG(LOG_MSG("} = FLAG_NONE (mod.size() < 2)"));
return FLAG_NONE;
}
// get cell
int cell = ++mod[0];
LOG(LOG_MSG_INT(" ", cell));
// get vector index and bit offset
int offset = GET_OFFSET(cell);
int index = GET_INDEX(cell);
LOG(LOG_MSG_INT(" ", offset));
LOG(LOG_MSG_INT(" ", index));
// Get cell state
#ifdef SHOW_LOG
unsigned f = GET_STATE(mod[index], offset);
if (f == FLAG_NONE) { LOG_MSG("} = FLAG_NONE"); }
else if ( f == FLAG_EDITED) { LOG_MSG("} = FLAG_EDITED"); }
else if ( f == FLAG_SAVED) { LOG_MSG("} = FLAG_SAVED"); }
return f;
#else
return GET_STATE(mod[index], offset);
#endif
}
/**
* Modify line
*/
void CEditorModMargin::Modify ( unsigned int startLine, int modified, int markers )
{
LOG(LOG_MSG("-- Modify:"));
LOG(LOG_MSG_INT(" - ", startLine));
LOG(LOG_MSG_INT(" - ", modified));
// lines added
if ( modified > 0 )
{
unsigned lastLine = m_lines.size();
if ( lastLine > 1 )
{
lastLine--;
for (unsigned line = lastLine; line > startLine; line-- )
{
Push( line + modified, Top( line ) );
}
}
}
// lines removed
else if ( modified < 0 )
{
unsigned deleted = -modified;
int lastLine = m_lines.size();
for (unsigned line = startLine + 1; line < lastLine; line ++ )
{
Push( line, Top( line + deleted ) );
}
}
// current lines
int endLine = startLine + ( modified > 0 ? modified : 0 );
for (int line = startLine; line <= endLine; line++ )
{
if ( m_pending.insert(line).second )
{
// LOG(LOG_MSG_INT("-- Modify:", line));
Push( line, markers );
SetMarker( line, markers );
}
}
}
/**
* Undo the lines
*/
void CEditorModMargin::Undo ( unsigned startLine, int modified )
{
LOG(LOG_MSG("-- Undo:"));
LOG(LOG_MSG_INT(" - ", startLine));
LOG(LOG_MSG_INT(" - ", modified));
// lines added or removed ?
if ( modified != 0 )
{
// Undo lines after the delete / insert block
unsigned touched = modified > 0 ? modified : -modified;
unsigned linesTotal = m_lines.size();
for ( unsigned line = startLine + touched + 1; line < linesTotal; line++ )
{
Undo( line );
}
// undo the lines in place of deleted
if ( modified < 0 )
{
for ( unsigned line = 1; line <= touched; line++ )
{
Undo( line + startLine );
}
}
// lines inserted.
else
{
for ( unsigned line = startLine + 1; line <= startLine + touched; line++ )
{
m_lineMarkers.push_back( LineMarker( line, Undo( line ) ) );
}
}
}
// Undo the line
if ( m_pending.insert( startLine ).second )
{
m_lineMarkers.push_back( LineMarker( startLine, Undo( startLine ) ) );
}
}
/**
* Redo the lines
*/
void CEditorModMargin::Redo ( unsigned startLine, int modified )
{
LOG(LOG_MSG("-- Redo:"));
LOG(LOG_MSG_INT(" - ", startLine));
LOG(LOG_MSG_INT(" - ", modified));
// lines added or removed ?
if ( modified != 0 )
{
// Redo lines after the delete / insert block
unsigned touched = modified > 0 ? modified : -modified;
unsigned linesTotal = m_lines.size();
for ( unsigned line = startLine + touched + 1; line < linesTotal; line++ )
{
Redo( line );
}
// Redo the lines in place of deleted
if ( modified < 0 )
{
for ( unsigned line = 1; line <= touched; line++ )
{
Redo( line + startLine );
}
}
// Redo lines inserted.
else
{
for ( unsigned line = startLine + 1; line <= startLine + touched; line++ )
{
m_lineMarkers.push_back( LineMarker( line, Redo( line ) ) );
}
}
}
// Redo the line
if ( m_pending.insert( startLine ).second )
{
m_lineMarkers.push_back( LineMarker( startLine, Redo( startLine ) ) );
}
}
/**
* Set all modified lines
*/
void CEditorModMargin::SetSavePos ( )
{
LOG(LOG_MSG("SetSavePos:"));
for ( unsigned line = 0; line < m_lines.size(); line++ )
{
LOG(LOG_MSG_INT(" - ", line));
IntVector & mod = m_lines[line];
if ( mod.size() < 2 ) continue;
// only redo
if ( mod[0] == (unsigned)-1 )
{
for ( unsigned i = 1; i < mod.size(); i++ )
mod[i] = FULL_EDITED_FLAG;
continue;
}
// get cell nr
unsigned cell = mod[0];
// index and offset of the cell
unsigned offset = GET_OFFSET(cell);
unsigned index = GET_INDEX(cell);
LOG(LOG_INT(index));
LOG(LOG_INT(offset));
LOG(LOG_MSG_BIN(" - Before:", mod[index]));
// mark all REDO as edited
for ( unsigned i = index + 1; i < mod.size(); i++ )
{
mod[i] = FULL_EDITED_FLAG;
}
if ( offset < ( CELL_SIZE - BITS_PER_STATE ) )
{
unsigned clearMask = ((unsigned)-1) >> ((CELL_SIZE - offset) - 2);
unsigned editMask = ( FULL_EDITED_FLAG << (offset+2) );
mod[index] &= clearMask;
mod[index] |= editMask;
}
// find any previous SAVE position
for ( unsigned i = 1; i < index; i++ )
{
for ( unsigned x = 0; x < CELL_SIZE; x += BITS_PER_STATE )
{
if ( GET_STATE(mod[i], x) == FLAG_SAVED )
{
mod[i] = MAKE_STATE(mod[i], x, FLAG_EDITED);
}
}
}
for ( unsigned x = 0; x < offset; x += BITS_PER_STATE )
{
LOG(LOG_MSG_INT(" - ", x));
if ( GET_STATE(mod[index], x) == FLAG_SAVED )
{
mod[index] = MAKE_STATE(mod[index], x, FLAG_EDITED);
}
}
// mark current state as edited
if ( GET_STATE(mod[index], offset) != FLAG_NONE )
{
mod[index] = MAKE_STATE(mod[index], offset, FLAG_SAVED);
SetMarker ( line, FLAG_SAVED );
}
LOG(LOG_MSG_BIN(" - After:", mod[index]));
}
}
/**
* Apply markers in the linemarkers array
*/
void CEditorModMargin::ApplyMarkers ()
{
MarkerVector::iterator iter = m_lineMarkers.begin();
for ( ; iter != m_lineMarkers.end(); iter++ )
{
SetMarker( iter->first, iter->second );
}
}
/**
* Flush the line cache
*/
void CEditorModMargin::Flush ()
{
LOG(LOG_MSG("-- Flush"));
m_pending.clear();
m_undoredo.clear();
m_lineMarkers.clear();
}
/**
* Set line markers
*/
void CEditorModMargin::SetMarker ( unsigned line, unsigned marker )
{
// update margin
if (marker & FLAG_EDITED)
m_editor.MarkerAdd(line, MARKER_EDITED);
else
m_editor.MarkerDelete(line, MARKER_EDITED);
// set saved
if (marker & FLAG_SAVED)
m_editor.MarkerAdd(line, MARKER_SAVED);
else
m_editor.MarkerDelete(line, MARKER_SAVED);
}
<file_sep>/fbide-vs/Sdk/Sdk.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
// version information
#define SDK_VERSION_MAJOR 0
#define SDK_VERSION_MINOR 5
#define SDK_VERSION_RELEASE 1
#define SDK_VERSION_STRING "0.5.1"
// macro function to check sdk version
#define SDK_CHECK_VERSION(major, minor, release) \
((SDK_VERSION_MAJOR > (major) || \
(SDK_VERSION_MAJOR == (major) && SDK_VERSION_MINOR > (minor)) || \
(SDK_VERSION_MAJOR == (major) && SDK_VERSION_MINOR == (minor) && SDK_VERSION_RELEASE >= (release))))
// macros for DLL import / export clauses
#ifdef __WXMSW__
# ifdef EXPORT_SDK
# define SDK_DLL __declspec (dllexport)
# else
# define SDK_DLL __declspec (dllimport)
# endif
# ifdef EXPORT_PLUGIN
# define PLUGIN_DLL __declspec (dllexport)
# else
# define PLUGIN_DLL __declspec (dllimport)
# endif
#else
# define SDK_DLL
# define PLUGIN_DLL
#endif
<file_sep>/fbide-wx/sdk/include/sdk/EditorManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EDITOR_MANAGER_H_INCLUDED
#define EDITOR_MANAGER_H_INCLUDED
#include "EventMap.h"
namespace fb
{
// forward reference ...
class CEditor;
class CManager;
/**
* Manage editors
*/
class DLLIMPORT CEditorManager
: public CEventMap<int, void(int, CEditor &) >
{
public :
// declare events
enum Event
{
// open new document
EVT_OPEN = 1,
// close document
EVT_CLOSE
};
// Register new editor with the manager
virtual void RegisterEditor ( CEditor * editor ) = 0;
private :
// allow CManager to access ...
friend class CManager;
// get singleton instance
static CEditorManager * Get ();
// free singleton instance
static void Free ();
protected :
virtual ~CEditorManager() {}
};
}
#endif // EDITOR_MANAGER_H_INCLUDED
<file_sep>/fbide-wx/Plugins/TangoTheme/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/PluginArtProvider.h"
#include "sdk/UiManager.h"
#include "sdk/ArtProvider.h"
namespace XPM {
#include "xpm/xpm_tango/newsrc.xpm"
#include "xpm/xpm_tango/opnproj.xpm"
#include "xpm/xpm_tango/save.xpm"
#include "xpm/xpm_tango/close.xpm"
#include "xpm/xpm_tango/undo.xpm"
#include "xpm/xpm_tango/redo.xpm"
#include "xpm/xpm_tango/cut.xpm"
#include "xpm/xpm_tango/copy.xpm"
#include "xpm/xpm_tango/paste.xpm"
#include "xpm/xpm_tango/search.xpm"
#include "xpm/xpm_tango/srchrep.xpm"
#include "xpm/xpm_tango/xpm_goto.xpm"
#include "xpm/xpm_tango/screen.xpm"
#include "xpm/xpm_tango/about.xpm"
#include "xpm/xpm_tango/empty.xpm"
}
using namespace fb;
/**
* Gfx provider
*/
class TangoThemeProvider : public IArtProvider
{
public :
// Create plugin instance
TangoThemeProvider ()
{
// we use only xpm's so...
m_bitmaps[_T("new")] = new wxBitmap (XPM::newsrc);
m_bitmaps[_T("open")] = new wxBitmap (XPM::opnproj);
m_bitmaps[_T("save")] = new wxBitmap (XPM::save);
m_bitmaps[_T("quit")] = new wxBitmap (XPM::close);
m_bitmaps[_T("undo")] = new wxBitmap (XPM::undo);
m_bitmaps[_T("redo")] = new wxBitmap (XPM::redo);
m_bitmaps[_T("cut")] = new wxBitmap (XPM::cut);
m_bitmaps[_T("copy")] = new wxBitmap (XPM::copy);
m_bitmaps[_T("paste")] = new wxBitmap (XPM::paste);
m_bitmaps[_T("find")] = new wxBitmap (XPM::search);
m_bitmaps[_T("replace")] = new wxBitmap (XPM::srchrep);
m_bitmaps[_T("goto")] = new wxBitmap (XPM::xpm_goto);
m_bitmaps[_T("about")] = new wxBitmap (XPM::about);
m_bitmaps[_T("log")] = new wxBitmap (XPM::screen);
m_bitmaps[_T("icon.empty")]= new wxBitmap (XPM::empty);
for (CBitmapMap::iterator iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
iter->second->SetMask(new wxMask(*iter->second, wxColour(191, 191, 191)));
}
}
// clean up
virtual ~TangoThemeProvider ()
{
for (CBitmapMap::iterator iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
delete iter->second;
}
}
virtual wxBitmap GetIcon (const wxString & name, int size = IArtProvider::SMALL)
{
CBitmapMap::iterator iter = m_bitmaps.find(name);
if (iter != m_bitmaps.end())
{
return *iter->second;
}
return *m_bitmaps[_T("icon.empty")];
}
virtual wxSize GetIconSize (int type)
{
return wxSize(16, 16);
}
private :
WX_DECLARE_STRING_HASH_MAP(wxBitmap *, CBitmapMap);
CBitmapMap m_bitmaps;
};
// Register the plugin
CPluginArtProvider<TangoThemeProvider> plugin(_T("TangoTheme"));
<file_sep>/fbide-wx/stuff/fb_lexer_copy.h
/*
* Allowed uri schemes inside the comments
*/
const char * UriSchemes[] = {
"http://",
"https://",
"ftp://",
"www.",
0
};
const char EscapeCodes[] = {
'a', // beep
'b', // backspace
'f', // formfeed
'l', 'n', // new line
'r', // carriage return
't', // tab
'v', // vertical tab
'\\', // backslash
'"', // double quote
'\'', // single quote
0
};
/**
* Is it a comment?
*/
static bool IsComment(Accessor &styler, int pos, int len)
{
return len > 0 && styler[pos] == '\'';
}
/**
* Is it a legal type suffix ?
*/
static inline bool IsTypeCharacter(int ch)
{
return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' ;
}
/**
* Extended to accept accented characters
*/
static inline bool IsAWordChar(int ch)
{
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_' || ch == '$');
}
/**
* Start of teh identifier ?
*/
static inline bool IsAWordStart(int ch)
{
return ch >= 0x80 ||
(isalnum(ch) || ch == '_' || ch == '.');
}
/**
* Skip the tabs and spaces
* but stop at anything else
*/
static inline void SkipSpacesAndTabs (StyleContext & sc)
{
while (!sc.atLineEnd && IsASpaceOrTab(sc.ch))
sc.Forward();
}
/**
* Hightlight a QB style metakeyword inside single
* line comments if matches
* return true if matched.
*/
static bool HighlightMetaKeyword (
StyleContext & sc,
const char * kw,
int len
) {
// return if not matches or next char is printable
if (IsAWordChar(sc.GetRelative(len)) || !sc.MatchIgnoreCase(kw))
return false;
// colorise
sc.ChangeState(PP_KEYWORD_META);
sc.SetState(PP_KEYWORD_META);
sc.Forward(len);
sc.SetState(PP_DEFAULT);
return true;
}
/**
* Parse single line comments
* a comment may appear in:
* - normal code
* - preprocessor
* - asm block
*
* may start with ' or REM keyword
* may be followed by qb compatible
* metacommand in wich case turn it
* into a preprocessor statament
*/
static inline void ParseSingleLineComment (
int dialect,
StyleContext & sc,
Accessor & styler
) {
// skip any spaces or tabs...
SkipSpacesAndTabs (sc);
// return if this line can't be a meta statament
if (sc.atLineEnd || sc.ch != '$') return;
// mov forth and skip any spaces
sc.Forward();
SkipSpacesAndTabs (sc);
if (sc.atLineEnd) return;
// check if this is a valid meta statament
if (HighlightMetaKeyword(sc, "lang", 4))
return;
// allowed only in QB and LITE
if (dialect == DIALECT_QB || dialect == DIALECT_LITE)
{
if (HighlightMetaKeyword(sc, "include", 7))
return;
if (HighlightMetaKeyword(sc, "dynamic", 7))
return;
if (HighlightMetaKeyword(sc, "static", 6))
return;
}
}
/**
* Get the Keyword style
* return FB_IDENTIFIER if not found
*/
static inline int GetFBKeywordStyle (
WordList *keywordlists[],
const char * kw,
int defStyle = FB_IDENTIFIER
) {
if (keywordlists[KEYWORD_ONE]->InList(kw))
return FB_KEYWORD_ONE;
else if (keywordlists[KEYWORD_TWO]->InList(kw))
return FB_KEYWORD_TWO;
else if (keywordlists[KEYWORD_THREE]->InList(kw))
return FB_KEYWORD_THREE;
else if (keywordlists[KEYWORD_FOUR]->InList(kw))
return FB_KEYWORD_FOUR;
return defStyle;
}
/**
* Find the string from an array that matches
* and return it's length
* or 0 if none
*/
static inline int FindMatch (StyleContext & sc, const char * matches[])
{
for (int i = 0; matches[i]; i++)
if (sc.MatchIgnoreCase(matches[i]))
return strlen(matches[i]);
return 0;
}
/**
* Check if any of the chars matches ?
* return char that matches or a 0
*/
static inline char FindMatch(StyleContext & sc, const char matches[])
{
for (int i = 0; matches[i]; i++)
if (sc.ch == matches[i])
return matches[i];
return 0;
}
/**
* If is URL inside the comment
* set the style, move forward and return
* true
*/
static inline bool IsCommentUrl (int section, StyleContext & sc, Accessor &styler)
{
if (!IsAWordChar(styler[sc.currentPos-1]))
{
if (int len = FindMatch(sc, UriSchemes))
{
sc.SetState(section + FB_COMMENT_URL);
sc.Forward(len);
return true;
}
}
return false;
}
/**
* If this is default section
*/
static inline bool IsDefaultSection (int style)
{
return style == FB_DEFAULT
|| style == ASM_DEFAULT
|| style == PP_DEFAULT
;
}
/**
* Get Section type
*/
int GetSectionType (int style)
{
if (style <= FB_SECTION_LAST)
return SECTION_FB;
if (style <= ASM_SECTION_LAST)
return SECTION_ASM;
if (style <= PP_SECTION_LAST)
return SECTION_PP;
return SECTION_FB;
}
/**
* Find previous section type
*/
int GetPrevSectionType (StyleContext & sc, Accessor &styler)
{
int p = sc.currentPos;
if (!p) return SECTION_FB;
int curSection = GetSectionType(sc.state);
while (--p)
{
int prevSection = GetSectionType(styler.StyleAt(p));
if (prevSection != curSection)
return prevSection;
}
return SECTION_FB;
}
/**
* Highlight part of the source code
*/
static void ColouriseFB (
unsigned int startPos,
int length, int initStyle,
WordList *keywordlists[],
Accessor &styler
)
{
// init
styler.StartAt(startPos, 63);
StyleContext sc(startPos, length, initStyle, styler, 63);
// get dialect
int dialect = styler.GetPropertyInt("dialect", LEX::DIALECT_FB);
int charCount = 0;
int curLine = styler.GetLine(startPos);
int lineState = curLine > 0 ? styler.GetLineState(curLine-1): 0;
int curNcLevel = lineState & 0xFF;
// do the highlighting
for ( ; sc.More(); sc.Forward())
{
// get current section
int section = GetSectionType(sc.state);
// section might have changed...
section = GetSectionType(sc.state);
if (sc.atLineStart)
{
/*
// Set previous line state
lineState = (lineState & 0xFFFFFF00) | curNcLevel;
styler.SetLineState(curLine, lineState);
// this line
curLine = styler.GetLine(sc.currentPos);
if (!curNcLevel)
{
if (section != SECTION_FB)
{
sc.SetState(GetPrevSectionType(sc, styler));
}
else sc.SetState(SECTION_FB);
}
else
{
sc.SetState(section + FB_COMMENT_MULTILINE);
}
*/
// no visible chars on a new line
charCount = 0;
}
else if (!IsASpaceOrTab(sc.ch))
{
if (!IsInMultiLineComment(sc.state))
charCount++;
}
// handle single line comments
if (IsInSingleLineComment(sc.state))
{
if (IsCommentUrl(section, sc, styler))
continue;
}
// is URL inside the comment ?
else if (IsInCommentUrl(sc.state))
{
if (sc.atLineEnd || IsASpace(sc.ch))
{
if (curNcLevel)
sc.SetState(section + FB_COMMENT_MULTILINE);
else
sc.SetState(section + FB_COMMENT);
}
}
// is it a multiline ?
else if (IsInMultiLineComment(sc.state))
{
if (sc.Match('\'', '/'))
{
if (curNcLevel > 0) curNcLevel--;
sc.Forward();
if (curNcLevel == 0)
{
sc.ForwardSetState(section);
}
}
else if (sc.Match('/','\'')) {
curNcLevel++;
sc.Forward();
}
else if (IsCommentUrl(section, sc, styler))
continue;
}
// handle string literals
else if (IsInString(sc.state))
{
if (sc.Match('"', '"'))
{
sc.SetState(section+FB_STRING_ESCAPE);
sc.Forward(2);
sc.SetState(section+FB_STRING);
continue;
}
else if (sc.Match('"'))
{
sc.Forward();
sc.SetState(section);
lineState &= (~LINESTATE_ESCAPE_STRING);
curLine = styler.GetLine(sc.currentPos);
styler.SetLineState(curLine, lineState);
}
else if (sc.ch == '\\' && lineState & LINESTATE_ESCAPE_STRING)
{
sc.SetState(section+FB_STRING_ESCAPE);
sc.Forward();
// Simplel sequences
if (FindMatch(sc, EscapeCodes))
{
sc.ForwardSetState(section+FB_STRING);
continue;
}
// unicode char in hex \uFFFF
else if (sc.ch=='u' &&
IsADigit(sc.chNext, 16) &&
IsADigit(sc.GetRelative(2), 16) &&
IsADigit(sc.GetRelative(3), 16) &&
IsADigit(sc.GetRelative(4), 16)
) {
sc.ForwardSetState(section+FB_NUMBER_HEX);
sc.Forward(3);
sc.ForwardSetState(section+FB_STRING);
}
// ascii char in decimal \123
else if (
IsADigit(sc.ch, 10) &&
IsADigit(sc.chNext, 10) &&
IsADigit(sc.GetRelative(2), 10)
) {
sc.SetState(section+FB_NUMBER);
sc.Forward(2);
sc.ForwardSetState(section+FB_STRING);
}
// ascii char in hex \&hFF
else if (sc.ch == '&' && sc.chNext == 'h'
&& IsADigit(sc.GetRelative(2), 16)
&& IsADigit(sc.GetRelative(3), 16)
) {
sc.SetState(section+FB_NUMBER_HEX);
sc.Forward(3);
sc.ForwardSetState(section+FB_STRING);
}
// ascii char in octal \&o777
else if (sc.ch == '&' && sc.chNext == 'o'
&& IsADigit(sc.GetRelative(2), 8)
&& IsADigit(sc.GetRelative(3), 8)
&& IsADigit(sc.GetRelative(4), 8)
) {
sc.SetState(section+FB_NUMBER_OCT);
sc.Forward(4);
sc.ForwardSetState(section+FB_STRING);
}
// ascii char in binary \&b11111111
else if (sc.ch == '&' && sc.chNext == 'b'
&& IsADigit(sc.GetRelative(2), 2)
&& IsADigit(sc.GetRelative(3), 2)
&& IsADigit(sc.GetRelative(4), 2)
&& IsADigit(sc.GetRelative(5), 2)
&& IsADigit(sc.GetRelative(6), 2)
&& IsADigit(sc.GetRelative(7), 2)
&& IsADigit(sc.GetRelative(8), 2)
&& IsADigit(sc.GetRelative(9), 2)
) {
sc.SetState(section+FB_NUMBER_BIN);
sc.Forward(9);
sc.ForwardSetState(section+FB_STRING);
}
// invalid sequence. maybe highlight it properly?
else
{
sc.SetState(section+FB_STRING);
}
}
}
*/
// default mode
if (IsDefaultSection(sc.state))
{
// is it a comment ?
if (sc.Match('\''))
{
/*
sc.SetState(section + FB_COMMENT);
// if is first on the line it might
// be metacommand
if (charCount == 0)
{
ParseSingleLineComment (dialect, sc, styler);
}
*/
}
// REM keyword
else if (
!IsAWordChar(sc.GetRelative(3))
&& sc.MatchIgnoreCase("rem")
) {
// highlight REM as a keyword if it's in the list
sc.SetState(section + GetFBKeywordStyle(
keywordlists, "rem", FB_COMMENT
));
if (IsASpace(sc.GetRelative(3)))
sc.Forward(4);
else
sc.Forward(3);
sc.SetState(section + FB_COMMENT);
if (charCount == 0)
ParseSingleLineComment (dialect, sc, styler);
}
// multiline comment ?
else if (sc.Match('/', '\''))
{
sc.SetState(section + FB_COMMENT_MULTILINE);
curNcLevel++;
sc.Forward();
}
// a string ?
else if (sc.ch == '"')
{
if (dialect == DIALECT_QB || dialect == DIALECT_LITE)
{
if (styler.GetPropertyInt("option.escape", false))
{
curLine = styler.GetLine(sc.currentPos);
lineState |= LINESTATE_ESCAPE_STRING;
styler.SetLineState(curLine, lineState);
}
}
sc.SetState(section + FB_STRING);
}
// explicitly NON escaped string literal
else if (sc.Match('$', '"'))
{
sc.SetState(section + FB_STRING);
sc.Forward();
}
// explicitly escaped string literal
else if (sc.Match('!', '"'))
{
lineState |= LINESTATE_ESCAPE_STRING;
curLine = styler.GetLine(sc.currentPos);
styler.SetLineState(curLine, lineState);
sc.SetState(section + FB_STRING);
sc.Forward();
}
else if (sc.Match('#') && !charCount)
{
sc.SetState(PP_DEFAULT);
}
*/
}
// reached the end of the line...
if (sc.atLineEnd)
{
sc.SetState(GetSectionType(sc.state));
}
}
// end
sc.Complete();
}<file_sep>/fbide-wx/sdk/include/sdk/sdk.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef SDK_H_INCLUDED
#define SDK_H_INCLUDED
#define SDK_VERSION_MAJOR 0
#define SDK_VERSION_MINOR 5
#define SDK_VERSION_RELEASE 0
#define SDK_VERSION_STRING _T("FBIde SDK 0.5.0")
#define SDK_CHECK_VERSION(major, minor, release) \
(SDK_VERSION_MAJOR > (major) || \
(SDK_VERSION_MAJOR == (major) && SDK_VERSION_MINOR > (minor)) || \
(SDK_VERSION_MAJOR == (major) && SDK_VERSION_MINOR == (minor) && SDK_VERSION_RELEASE >= (release)))
#ifdef __WINDOWS__
#if EXPORT_LIB
#define DLLIMPORT __declspec (dllexport)
#else
#define DLLIMPORT __declspec (dllimport)
#endif
#define EXPORT_PLUGIN __declspec (dllexport)
#else
#define DLLIMPORT
#define EXPORT_PLUGIN
#endif
#endif // SDK_H_INCLUDED
<file_sep>/fbide-rw/sdk/manager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
// get manager
#define GET_MGR() fb::Manager::GetInstance()
// get ui manager
#define GET_UIMGR() GET_MGR()->GetUiManager()
// get script manager
#define GET_SCRIPTMGR() GET_MGR()->GetScriptManager()
// get document manager
#define GET_DOCMGR() GET_MGR()->GetDocManager()
// get editor manager
#define GET_EDITORMGR() GET_MGR()->GetEditorManager()
// get plugin manager
#define GET_PLUGINMGR() GET_MGR()->GetPluginManager()
// get type manager
#define GET_TYPEMGR() GET_MGR()->GetTypeManager()
// get global configuration registry
#define GET_REG() GET_MGR()->GetRegistry()
// get translations
#define GET_LANG() GET_MGR()->GetLang()
namespace fb
{
class UiManager;
class ScriptManager;
class DocManager;
class EditorManager;
class PluginManager;
class TypeManager;
/**
* Main manager class. This is aproxy class that holds
* the instances and other bookkeeping of the SDK
* and should be used to access the SDK API
*
* This class is a singleton
*/
struct SDK_DLL Manager : private NonCopyable // : public Singleton<Manager>
{
// get version as an INT
virtual const Version & GetVersion() = 0;
// get global registry object
virtual Registry & GetRegistry() = 0;
// get language
virtual Language & GetLang() = 0;
// Get UiManager
UiManager * GetUiManager();
// get ScriptManager
ScriptManager * GetScriptManager();
// get document manager
DocManager * GetDocManager();
// get editor manager
EditorManager * GetEditorManager();
// get plugin manager
PluginManager * GetPluginManager();
// get type manager
TypeManager * GetTypeManager();
// get manager instance
static Manager * GetInstance();
// release the manager instance ( shut down )
static void Release();
// private methods
protected :
// Release managers
void ReleaseManagers();
// can't create directly
Manager() = default;
// ensure delete to fail. Use Release() instead!
virtual ~Manager() = default;
};
}
// macro to declare a manager class in the header
#define DECLARE_MANAGER(_class) \
protected : \
_class () = default; \
virtual ~_class () = default; \
private : \
friend class Manager; \
static _class * GetInstance (); \
static void Release ();
// Macro to implement Manager class logic in the source
#define IMPLEMENT_MANAGER(_baseClass, _extClass) \
namespace { _extClass * the_instance = NULL; } \
_baseClass * _baseClass::GetInstance () { \
if ( the_instance == NULL ) the_instance = new _extClass; \
return the_instance; \
} \
void _baseClass::Release () { \
if ( the_instance == NULL ) return; \
delete the_instance; \
the_instance = NULL; \
}
<file_sep>/fbide-wx/sdk/include/sdk/TypeManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef TYPEMANAGER_H_INCLUDED
#define TYPEMANAGER_H_INCLUDED
namespace fb
{
/**
* Forward declarations...
*/
class CDocumentBase;
class CManager;
class CTypeManager;
/**
* Base class for type registrants
*/
class DLLIMPORT CTypeRegistrantBase
{
public:
virtual CDocumentBase * Create (const wxString & file = _T("")) = 0;
};
/**
* Template class for registering new document types
* siply use :
* new CTypeRegistrant<classNme>;
*/
template<class T> class CTypeRegistrant : public CTypeRegistrantBase
{
public : virtual CDocumentBase * Create (const wxString & file = _T("")) { return new T(file); }
};
/**
* Manager document types. register new types by name
* then associate file extensions and also generate
* file filter list for open / save dialogs
*
* later this class could also handle registering
* (optionally) said file types with the OS to be
* loaded by FBIde
*/
class DLLIMPORT CTypeManager
{
public :
void AddType (const wxString & name, const wxString & desc, CTypeRegistrantBase * type);
void BindExtensions (const wxString & type, const wxString & types);
void BindAlias (const wxString & alias, const wxString & type);
CDocumentBase * LoadFile (const wxString & file);
CDocumentBase * NewDocument (const wxString & type);
bool TypeExists (const wxString & type);
wxString GetFileFilters (bool allFiles = false);
private :
friend class CManager;
CTypeManager ();
~CTypeManager ();
// private data implementation
struct CData;
std::auto_ptr<CData> m_data;
};
}
#endif // TYPEMANAGER_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Language.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Simple hashmap containing identifier and
* meaning for translations, etc...
*/
class SDK_DLL Language : public NonCopyable
{
public :
/// get translation by key. If doesn't exist return the
/// key.
wxString & operator [] ( const wxString & key );
/// get the translation
wxString Get(const wxString & key) { return (*this)[key]; }
/// get translation by key. If doesn't exist return the
/// key. Replace tags
wxString Get(const wxString & key, const StringHashMap & map);
/// get translation. use std::pair for tag substitution
wxString Get(const wxString & key, const std::pair<wxString, wxString> & tag);
/// get translation and replace tag
wxString Get(const wxString & key, const wxString & tag, const wxString & value);
/// Load the language file
void Load (const wxString & file);
private :
StringHashMap m_map;
};
}
<file_sep>/fbide-wx/sdk/src/StyleInfo.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/StyleInfo.h"
#include <wx/tokenzr.h>
using namespace fb;
// data structure holding style info
struct CssRule
{
wxString inheritFrom;
CStringStringHashMap styles;
};
// private data
struct CStyleParser::CData
{
// Hold the CSS rule blocks
typedef std::map<wxString, CssRule> CCssRuleMap;
// cache styleinfo based on paths
typedef std::map<wxString, CStyleInfo> CStyleInfoMap;
CStyleInfoMap m_styleInfoMap;
CCssRuleMap m_cssRuleMap;
CStyleInfo m_defaultStyle;
CStyleParser * m_owner;
/**
* Find rule value
*/
wxString GetRule (CssRule & info, const wxString & rule, const wxString & selector)
{
// check if this rule has a value
if (info.styles[rule].Len() && info.styles[rule] != _T("inherit"))
return info.styles[rule];
// no inherit or try to inherit from self?
if (!info.inheritFrom.Len() || info.inheritFrom == selector) return _T("");
// check if inherit exists
if (!m_owner->PathExists(info.inheritFrom)) return _T("");
// call recursievly
return GetRule(m_cssRuleMap[info.inheritFrom], rule, info.inheritFrom);
}
// Reset styleinfo's so that changes would reflect in the
// next call to get styles
void resetStyleInfoCache ()
{
CStyleInfoMap::iterator iter = m_styleInfoMap.begin();
for ( ; iter != m_styleInfoMap.end(); iter++)
iter->second.isOk = false;
}
};
/**
* Construct new style info object
*/
CStyleParser::CStyleParser (const wxString & filename)
: m_data(new CStyleParser::CData)
{
// set owner to the pimpl idiom
m_data->m_owner = this;
// this style is returned as default
m_data->m_defaultStyle.isOk = true;
// Load CSS
LoadFile(filename);
}
/**
* Parse the CSS file.
* This is a very simple and primitive CSS
* parser capable only function within FBIDE
* styling needs.
*/
void CStyleParser::LoadFile (const wxString & filename)
{
if (!filename.Len()) return;
if (!::wxFileExists(filename))
{
wxMessageBox(_T("File not found"));
return;
}
// load the file
wxTextFile file;
file.Open(filename);
// parse through the file
wxString buffer;
for (wxString str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
buffer << str << _T("\n");
// parse states
bool inComment = false,
inString = false,
inSection = false,
inDefine = false,
inIdentifier=false;
wxChar cCh = 0;
wxChar pCh = 0;
wxChar nCh = 0;
wxString section, key, value;
wxArrayString values;
int line = 1, col = 0;
#define CSS_ERROR() \
{ \
wxString error; \
error.Printf(_T("Invalid character at %d:%d (%d)"), line, col, __LINE__); \
wxMessageBox(error); \
return; \
}
for (size_t i = 0; i < buffer.Len(); i++)
{
pCh = cCh;
cCh = buffer[i];
nCh = (i < buffer.Len()-1) ? buffer[i+1] : 0;
// count lines and columns
if (cCh == 10) { line++; col=0; }
else col++;
// if inside a comment
if (inComment)
{
if (cCh == '*' && nCh == '/')
{
inComment = false;
col++, i++;
}
continue;
}
// in quoted text ?
else if (inString)
{
if (cCh == '"')
{
inString = false;
values.Add(value);
value = _T("");
}
else value << cCh;
continue;
}
// identifier
else if (inIdentifier)
{
if ((cCh >= 'a' && cCh <= 'z')
|| (cCh >= 'A' && cCh <= 'Z')
|| (cCh >= '0' && cCh <= '9')
|| cCh == '-' || cCh == '.' || cCh == '_')
{
if (inSection)
{
if (inDefine) value << cCh;
else key << cCh;
}
else section << cCh;
continue;
}
else if (inSection && inDefine)
{
values.Add(value);
value = _T("");
}
inIdentifier = false;
}
// a comment ?
if (cCh == '/' && nCh == '*')
{
inComment = true;
col++, i++;
continue;
}
// a whitespace ?
if (cCh == ' ' || cCh == '\t' || cCh == 10 || cCh == 13)
{
continue;
}
// section start ?
if (cCh == '{')
{
if (inSection || !section.Len()) CSS_ERROR();
inSection = true;
continue;
}
// section end ?
if (cCh == '}')
{
if (!inSection || inDefine) CSS_ERROR();
inSection = false;
section = _T("");
continue;
}
// couted text ?
if (cCh == '"')
{
if (!inDefine) CSS_ERROR();
inString = true;
continue;
}
if (cCh == ':')
{
if (!inSection || inDefine || !key.Len())
CSS_ERROR();
inDefine = true;
continue;
}
if (cCh == ';')
{
if (!inSection || !inDefine || !values.Count())
CSS_ERROR();
inDefine = false;
SetCssRule (section, key, values);
key = _T("");
values.Clear();
continue;
}
// identifier ?
if ((cCh >= 'a' && cCh <= 'z')
|| (cCh >= 'A' && cCh <= 'Z')
|| (cCh >= '0' && cCh <= '9')
|| cCh == '-' || cCh == '.'
|| cCh == '_' || cCh == '#')
{
inIdentifier = true;
if (inSection)
{
if (inDefine) value << cCh;
else key << cCh;
}
else section << cCh;
}
}
#undef CSS_ERROR
}
// Add CSS rule
void CStyleParser::SetCssRule (
const wxString & selector,
const wxString & rule,
const wxString & value,
const wxString & inheritFrom
)
{
wxArrayString values;
values.Add(value);
SetCssRule(selector, rule, values, inheritFrom);
}
void CStyleParser::SetCssRule (
const wxString & selector,
const wxString & rule,
const wxArrayString & values,
const wxString & inheritFrom
)
{
if (!selector.Len() || !rule.Len() || !values.Count())
return;
// inherit default values from class...
wxString inherit = inheritFrom;
// reset style cache
m_data->resetStyleInfoCache();
// split classes
wxStringTokenizer tkz(selector, _T("."));
// iterate through the classes
wxString partSelector;
wxString token;
while ( tkz.HasMoreTokens() )
{
// skip if empty
token = tkz.GetNextToken();
if (!token.Len()) continue;
// the path to current class
wxString path = partSelector + _T(".") + token;
// if there are more tokens then it means that current
// selector becomes a parent to the next one
if (tkz.HasMoreTokens())
{
if (!PathExists(path))
{
m_data->m_cssRuleMap[path].inheritFrom = inherit;
}
inherit = path;
partSelector = path;
}
else
{
// need to add inherit info ?
bool addInherit = false;
// get the style info
if (!PathExists(path)) addInherit = true;
CssRule & info = m_data->m_cssRuleMap[path];
if (addInherit) info.inheritFrom = inherit;
// parse CSS rules
wxString value = values[0];
// color
if (rule == _T("color"))
info.styles[rule] = value;
// background
else if (rule == _T("background") || rule == _T("background-color"))
info.styles[_T("background-color")] = value;
// outline
else if (rule == _T("outline-color"))
info.styles[rule] = value;
// font size
else if (rule == _T("font-size"))
{
if (value.Right(2) == _T("px"))
info.styles[rule] = value.Left(value.Len()-2);
}
// font family
else if (rule == _T("font-family"))
info.styles[rule] = value;
// font style
else if (rule == _T("font-style"))
info.styles[rule] = value;
// font weight
else if (rule == _T("font-weight"))
info.styles[rule] = value;
// text decorations
else if (rule == _T("text-decoration"))
info.styles[rule] = value;
else if (rule == _T("opacity"))
info.styles[rule] = value;
else if (rule == _T("width"))
{
if (value.Right(2) == _T("px"))
info.styles[rule] = value.Left(value.Len()-2);
}
}
}
}
/**
* Get styles
* If selector is not defined try to inherit styles from it's base
* or default selector.
*/
CStyleInfo CStyleParser::GetStyle (const wxString & selector, const wxString & inherit)
{
// invalid path?
if (!PathExists(selector))
{
SetCssRule(selector, _T("font-size"), _T("inherit"), inherit.Len() ? inherit : _T(".default"));
}
// get styleinfo from cache. if it exists then return it
CStyleInfo & style = m_data->m_styleInfoMap[selector];
if (style.isOk) return style; // creates a copy
// get data
CssRule & info = m_data->m_cssRuleMap[selector];
wxString value;
// get bold
value = m_data->GetRule(info, _T("font-weight"), selector);
if (value == _T("bold")) style.bold = true;
// get italic
value = m_data->GetRule(info, _T("font-style"), selector);
if (value == _T("italic")) style.italic = true;
// get underlined
value = m_data->GetRule(info, _T("text-decoration"), selector);
if (value == _T("underlined")) style.underlined = true;
// get font size
value = m_data->GetRule(info, _T("font-size"), selector);
if (value.Len())
{
long size = 0;
value.ToLong(&size);
style.size = (int)size;
}
else style.size = STYLE_DEFAULT_FONT_SIZE;
// get font size
value = m_data->GetRule(info, _T("width"), selector);
if (value.Len())
{
long width = 0;
value.ToLong(&width);
style.width = (int)width;
}
// get font size
value = m_data->GetRule(info, _T("opacity"), selector);
if (value.Len())
{
long opacity = 0;
value.ToLong(&opacity);
style.opacity = (int)opacity;
}
// get font family
value = m_data->GetRule(info, _T("font-family"), selector);
if (value.Len()) style.font = value;
else style.font = STYLE_DEFAULT_FONT;
// get color
value = m_data->GetRule(info, _T("color"), selector);
if (value.Len()) style.fg.Set(value);
else style.fg.Set(STYLE_DEFAULT_FG);
// get background color
value = m_data->GetRule(info, _T("background-color"), selector);
if (value.Len())
{
if (value != _T("none") && value != _T("transparent"))
style.bg.Set(value);
}
else style.bg.Set(STYLE_DEFAULT_BG);
// outline color
value = m_data->GetRule(info, _T("outline-color"), selector);
if (value.Len())
{
if (value != _T("none") && value != _T("transparent"))
style.outline.Set(value);
}
else style.outline.Set(STYLE_DEFAULT_BG);
style.isOk = true;
return style; // creates a copy
}
/**
* Check if CSS path exists
*/
bool CStyleParser::PathExists (const wxString & selector)
{
return m_data->m_cssRuleMap.find(selector) != m_data->m_cssRuleMap.end();
}
<file_sep>/fbide-vs/Sdk/MultiSplitter.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include <wx/renderer.h>
#include "MultiSplitter.h"
#include "Manager.h"
#include "UiManager.h"
using namespace fbi;
// implementations
IMPLEMENT_DYNAMIC_CLASS(MultiSplitWindow, wxWindow)
WX_DELEGATE_TO_CONTROL_CONTAINER(MultiSplitWindow, wxWindow)
// the event table
BEGIN_EVENT_TABLE(MultiSplitWindow, wxWindow)
WX_EVENT_TABLE_CONTROL_CONTAINER(MultiSplitWindow)
EVT_SIZE(MultiSplitWindow::OnSize)
EVT_MOUSE_EVENTS(MultiSplitWindow::OnMouseEvent)
EVT_MOUSE_CAPTURE_LOST(MultiSplitWindow::OnMouseCaptureLost)
END_EVENT_TABLE()
/**
* Destructor
*/
MultiSplitWindow::~MultiSplitWindow()
{
}
/**
* Initalize the multisplitter settings
*/
void MultiSplitWindow::Init()
{
WX_INIT_CONTROL_CONTAINER();
// init m_managed array to zeroes
memset(m_managed, 0, sizeof(m_managed));
// init m_visible array to zeroes
memset(m_visible, 0, sizeof(m_visible));
// state flags. set to 0
m_stateFlags = 0;
// default size
m_sashSize = -1;
// sash positions
m_sashVertical = m_sashHorizontal = 0;
// cursors
m_sashCursorWE = wxCursor(wxCURSOR_SIZEWE);
m_sashCursorNS = wxCursor(wxCURSOR_SIZENS);
m_sashCursorBoth = wxCursor(wxCURSOR_SIZING);
// drag mode
m_dragMode = 0;
// no need to update
m_needUpdating = false;
// set minimum sizes
m_minLeft = m_minRight = m_minTop = m_minBottom = 0;
// default gravity
m_vertGravity = 0.5, m_horGravity = 0.5;
// old size
m_oldw = 50, m_oldh = 50;
// temporary!
m_sashVertical = 50;
m_sashHorizontal = 50;
}
/**
* manual construction
*/
bool MultiSplitWindow::Create(wxWindow *parent, wxWindowID id,
const wxPoint& pos,const wxSize& size,
long style, const wxString& name)
{
// allow TABbing from one window to the other
style |= wxTAB_TRAVERSAL;
// we draw our border ourselves to blend the sash with it
style &= ~wxBORDER_MASK;
style |= wxBORDER_NONE;
if ( !wxWindow::Create(parent, id, pos, size, style, name) )
return false;
CalculateSash();
return true;
}
/**
* Show the pabe by index and assign a window pointer to it
* window must not be already assigned!
*/
void MultiSplitWindow::ShowWindow (int index, wxWindow * wnd, bool show)
{
wxWindowUpdateLocker uiLock(this);
// ensure index is correct
wxASSERT_MSG((index >= 0 && index <= 3), "Window index must be from 0 to 3");
// if window pointer is passed make sure its not yet assigned!
if (wnd != NULL)
{
wxASSERT((m_managed[index] == NULL), "Window already assigned to the region");
m_managed[index] = wnd;
}
else
{
wxASSERT((m_managed[index] != NULL), "No window assigned");
wnd = m_managed[index];
}
// get location flag
int locFlag = 0;
switch (index)
{
case PaneTopLeft : locFlag = LayoutTopLeft; break;
case PaneTopRight : locFlag = LayoutTopRight; break;
case PaneBottomLeft : locFlag = LayoutBottomLeft; break;
case PaneBottomRight : locFlag = LayoutBottomRight;break;
}
int flags = m_stateFlags;
if (show)
{
// already visible
if (flags & locFlag) return;
flags |= locFlag;
}
else
{
// not visible anyway
if (!(flags & locFlag)) return;
flags &= ~locFlag;
}
SetVisiblePanes(flags);
wnd->Show(show);
SizeWindows();
}
/**
* Calculate sash positions
*/
void MultiSplitWindow::CalculateSash()
{
int w, h;
GetClientSize(&w, &h);
GET_FRAME()->SetTitle(wxString("w=") << w << ", h=" << h);
int diffw = w - m_oldw;
int diffh = h - m_oldh;
// calculate sashes
if ( m_vertGravity != 0.0 )
{
int new_w = m_sashVertical + (int)(((double)diffw) * m_vertGravity);
if ( new_w >= m_minLeft )
{
if ( new_w >= ( w - m_minRight ) ) m_sashVertical = w - m_minRight;
else m_sashVertical = new_w;
}
else m_sashVertical = m_minLeft;
}
if ( m_horGravity != 0.0 )
{
int new_h = m_sashHorizontal + (int)(((double)diffh) * m_horGravity);
if ( new_h >= m_minTop )
{
if ( new_h >= ( h - m_minBottom ) ) m_sashHorizontal = h - m_minBottom;
m_sashHorizontal = new_h;
}
else m_sashHorizontal = m_minTop;
}
m_oldw = w, m_oldh = h;
}
/**
* Handle size events
*/
void MultiSplitWindow::OnSize(wxSizeEvent & event)
{
// get client size
CalculateSash();
SizeWindows();
}
// Handles mouse events
void MultiSplitWindow::OnMouseEvent(wxMouseEvent& event)
{
int x = (int)event.GetX(),
y = (int)event.GetY(),
w, h;
GetClientSize(&w, &h);
if (event.LeftDown())
{
if (int sash = SashHitTest(x, y))
{
m_dragMode = sash;
CaptureMouse();
SetDragCursor(sash);
}
}
else if (event.LeftUp() && m_dragMode != 0)
{
m_dragMode = 0;
ReleaseMouse();
SetCursor(*wxSTANDARD_CURSOR);
SizeWindows();
}
else if ((event.Moving() || event.Leaving() || event.Entering()) && (m_dragMode == 0))
{
int sash = SashHitTest(x, y);
if ( event.Leaving() || !sash )
{
SetCursor(*wxSTANDARD_CURSOR);
}
else
{
SetDragCursor(sash);
}
}
else if (event.Dragging() && (m_dragMode != 0))
{
bool resize = false;
if (m_dragMode & DragVertical)
{
if ( x >= m_minLeft && (w - x) >= m_minRight )
{
m_sashVertical = x;
resize = true;
}
}
if (m_dragMode & DragHorizontal)
{
if ( y >= m_minTop && (h - y) >= m_minBottom )
{
m_sashHorizontal = y;
resize = true;
}
}
if (resize) SizeWindows();
}
else
{
event.Skip();
}
}
// Aborts dragging mode
void MultiSplitWindow::OnMouseCaptureLost(wxMouseCaptureLostEvent& event)
{
if (!m_dragMode) return;
m_dragMode = 0;
SetCursor(* wxSTANDARD_CURSOR);
}
/**
* Set drag cursor
*/
void MultiSplitWindow::SetDragCursor(int flags)
{
switch (flags)
{
case DragVertical : SetCursor(m_sashCursorWE); break;
case DragHorizontal : SetCursor(m_sashCursorNS); break;
case DragBoth : SetCursor(m_sashCursorBoth); break;
}
}
/**
* Find hash at position
*/
int MultiSplitWindow::SashHitTest(int x, int y, int tolerance)
{
int flags = 0;
int sash_s = GetSashSize();
tolerance += sash_s / 2;
// vertical
if ((m_stateFlags & LayoutVerticalFull) == LayoutVerticalFull || m_visible[1])
{
if ( x >= m_sashVertical - tolerance && x <= m_sashVertical + tolerance )
flags |= DragVertical;
}
else if (m_stateFlags & LayoutVerticalTop)
{
if (y <= (m_sashHorizontal+tolerance))
if (x >= m_sashVertical - tolerance && x <= m_sashVertical + tolerance)
flags |= DragVertical;
}
else if (m_stateFlags & LayoutVerticalBottom)
{
if (y >= (m_sashHorizontal-tolerance))
if (x >= m_sashVertical - tolerance && x <= m_sashVertical + tolerance)
flags |= DragVertical;
}
// horizontal
if ((m_stateFlags & LayoutHorizontalFull) == LayoutHorizontalFull || m_visible[2])
{
if ( y >= m_sashHorizontal - tolerance && y <= m_sashHorizontal + tolerance )
flags |= DragHorizontal;
}
else if (m_stateFlags & LayoutHorizontalLeft)
{
if (x <= (m_sashVertical+tolerance))
if ( y >= m_sashHorizontal - tolerance && y <= m_sashHorizontal + tolerance )
flags |= DragHorizontal;
}
else if (m_stateFlags & LayoutHorizontalRight)
{
if (x >= (m_sashVertical-tolerance))
if ( y >= m_sashHorizontal - tolerance && y <= m_sashHorizontal + tolerance )
flags |= DragHorizontal;
}
return flags;
}
/**
* Position and size subwindows.
* Note that the border size applies to each subwindow, not
* including the edges next to the sash.
*/
void MultiSplitWindow::SizeWindows()
{
wxWindowUpdateLocker uiLock(this);
// no visible windows
if (!m_visible[0]) return;
// get client size
int w, h;
GetClientSize(&w, &h);
// vars
int border_s = GetBorderSize();
int sash_s = GetSashSize();
int size_p = (sash_s/2) + (3*border_s);
int size_m = (sash_s/2) - (2*border_s);
// rects for every corner
wxRect tl, tr, bl, br;
// default
tl.x = border_s, tl.y = border_s;
// top-right
if (m_visible[1])
{
tr.x = m_sashVertical + size_p;
tr.y = border_s;
tl.width = m_sashVertical - size_m;
tr.width = w - tl.width;
}
else tl.width = w - (2*border_s);
// bottom-left
if (m_visible[2])
{
bl.x = border_s;
bl.y = m_sashHorizontal + size_p;
tl.height = m_sashHorizontal - size_m;
bl.height = h - tl.height;
// bottom-right
if (m_visible[3])
{
br.x = m_sashVertical + size_p;
br.y = bl.y;
if (m_visible[1]) bl.width = tl.width, br.width = tr.width;
else
{
bl.width = m_sashVertical - size_m;
br.width = w - bl.width;
}
br.height = bl.height;
}
else bl.width = w - (2*border_s);
}
else tl.height = h - (2*border_s);
tr.height = tl.height;
m_visible[0]->SetSize(tl);
if (m_visible[1]) m_visible[1]->SetSize(tr);
if (m_visible[2]) m_visible[2]->SetSize(bl);
if (m_visible[3]) m_visible[3]->SetSize(br);
SetNeedUpdating(false);
}
/**
* get border size
*/
int MultiSplitWindow::GetBorderSize() const
{
return wxRendererNative::Get().GetSplitterParams(this).border;
}
/**
* Get sash splitter size
*/
int MultiSplitWindow::GetSashSize() const
{
return m_sashSize > -1 ? m_sashSize : wxRendererNative::Get().GetSplitterParams(this).widthSash;
}
/**
* Build m_visible array based on visiblity flags
*/
void MultiSplitWindow::SetVisiblePanes(int flags)
{
// cells in m_visible array
int tl = 0, tr = 0,
bl = 0, br = 0;
// counters
int hCnt = 0, vCnt = 0;
// reset data
memset(m_visible, 0, sizeof(m_visible));
m_stateFlags = 0;
// show top left ?
if (flags & LayoutTopLeft && m_managed[PaneTopLeft] != NULL)
{
m_stateFlags |= LayoutTopLeft;
m_visible[tl] = m_managed[PaneTopLeft];
tr = 1, bl = 2, br = 2;
}
// show top right ?
if (flags & LayoutTopRight && m_managed[PaneTopRight] != NULL)
{
m_stateFlags |= LayoutTopRight;
m_visible[tr] = m_managed[PaneTopRight];
bl = 2, br = 2;
}
// show bottom left ?
if (flags & LayoutBottomLeft && m_managed[PaneBottomLeft] != NULL)
{
m_stateFlags |= LayoutBottomLeft;
m_visible[bl] = m_managed[PaneBottomLeft];
br = 3;
}
// show bottom right ?
if (flags & LayoutBottomRight && m_managed[PaneBottomRight] != NULL)
{
m_stateFlags |= LayoutBottomRight;
m_visible[br] = m_managed[PaneBottomRight];
}
// seperation flags
if (m_visible[1])
{
m_stateFlags |= LayoutVerticalTop;
if (m_visible[2]) m_stateFlags |= LayoutHorizontalRight;
}
else if (m_visible[2]) m_stateFlags |= LayoutHorizontalRight;
if (m_visible[2])
{
m_stateFlags |= LayoutHorizontalLeft;
if (m_visible[3]) m_stateFlags |= LayoutVerticalBottom;
}
}
<file_sep>/fbide-wx/sdk/include/sdk/Registry.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef REGISTRY_H_INCLUDED
#define REGISTRY_H_INCLUDED
#include "sdk/Variant.h"
namespace fb
{
/**
* Hash to hold the registry
*/
WX_DECLARE_STRING_HASH_MAP( CVariant, CRegistryHashMap );
/**
* Simple registry class
*/
class CRegistry : public CRegistryHashMap
{
public :
/*
inline CVariant & operator [] (const char * c_ch)
{
return CRegistryHashMap::operator[](wxString(c_ch, wxConvUTF8));
}
inline CVariant & operator [] (const wxChar * c_wch)
{
return CRegistryHashMap::operator[](c_wch);
}*/
};
}
#endif // REGISTRY_H_INCLUDED
<file_sep>/fbide-rw/sdk/uimanager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fb
{
class Manager;
/**
* Main manager class. This is aproxy class that holds
* the instances and other bookkeeping of the SDK
* and should be used to access the SDK API
*
* This class is a singleton
*/
struct SDK_DLL UiManager : private NonCopyable
{
// Load ui. return false if failed.
virtual bool Load () = 0;
// Get application title
virtual wxString GetTitle () = 0;
// get the main frame
virtual wxFrame * GetFrame () = 0;
// get document area location
virtual wxWindow * GetDocumentArea () = 0;
// declare this class as a manager
DECLARE_MANAGER(UiManager)
};
}
<file_sep>/fbide-wx/sdk/src/TypeManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/Document.h"
#include "sdk/TypeManager.h"
using namespace fb;
struct CTypeManager::CData
{
struct TypeData
{
CTypeRegistrantBase * creator;
wxString description;
wxString name;
};
typedef std::map<wxString, TypeData*> CExtMap;
// typedef std::pair<wxString, TypeData*> CExtPair;
WX_DECLARE_STRING_HASH_MAP(TypeData, CTypeList);
CExtMap m_extMap;
CTypeList m_list;
CStringStringHashMap m_aliasMap;
/**
* Resolve type alias if needed. Return real type
*/
wxString ResolveType (const wxString & base)
{
CTypeList::iterator iter = m_list.find(base);
if (iter != m_list.end()) return base;
CStringStringHashMap::iterator aliasIter = m_aliasMap.find(base);
if (aliasIter != m_aliasMap.end()) return ResolveType (aliasIter->second);
return _T("");
}
};
/**
* PHP like explode function by <NAME>
* from http://wxforum.shadonet.com/viewtopic.php?p=12929#12929
*/
void Explode( const wxString& s, wxArrayString& retArray, const wxChar* cpszExp,
const size_t& crnStart = 0, const size_t& crnCount = (size_t)-1,
const bool& crbCIComp = false)
{
wxASSERT_MSG(cpszExp != NULL, wxT("Invalid value for First Param of wxString::Split (cpszExp)"));
retArray.Clear();
size_t nOldPos = crnStart, nPos = crnStart;
wxString szComp, szExp = cpszExp;
if (crbCIComp)
{
szComp = s.Lower();
szExp.MakeLower();
}
else
szComp = s;
if(crnCount == (size_t)-1)
{
for (; (nPos = szComp.find(szExp, nPos)) != wxString::npos;)
{
retArray.Add(s.Mid(nOldPos, nPos - nOldPos));
nOldPos = nPos += szExp.Length();
}
}
else
{
for (int i = crnCount; (nPos = szComp.find(szExp, nPos)) != wxString::npos && i != 0; --i)
{
retArray.Add(s.Mid(nOldPos, nPos - nOldPos));
nOldPos = nPos += szExp.Length();
}
}
if (nOldPos != s.Length()) retArray.Add(s.Mid(nOldPos) );
}
/**
* construct. Can only be called
* from CManager class
*/
CTypeManager::CTypeManager () : m_data(new CTypeManager::CData())
{
return;
}
/**
* Clean things up
*/
CTypeManager::~CTypeManager ()
{
CData::CTypeList::iterator iter = m_data->m_list.begin();
for (; iter != m_data->m_list.end(); iter++)
{
delete iter->second.creator;
}
return;
}
/**
* register new Document type and associate it with the name
*/
void CTypeManager::AddType (const wxString & name, const wxString & desc, CTypeRegistrantBase * type)
{
if (TypeExists(name)) throw EXCEPTION(_T("Document type '") + name + _T("' already registered!"));
// add
CData::TypeData & data = m_data->m_list[name];
data.creator = type;
data.name = name;
data.description = desc;
}
/**
* Register type alias. Useful for example binding certain
* type identifiers to other types. For example set "default" type
*/
void CTypeManager::BindAlias (const wxString & alias, const wxString & type)
{
if (TypeExists(alias)) throw EXCEPTION(_T("Document type '") + alias + _T("' already registered! Can't register alias."));
if (!TypeExists(type)) throw EXCEPTION(_T("Document type '") + type + _T("' does not exist. Can't register alias."));
m_data->m_aliasMap[alias] = type;
}
/**
* Associate file types with the document types
*
* @todo allow registering multiple documents for the same
* extension later on.
*/
void CTypeManager::BindExtensions (const wxString & type, const wxString & ext)
{
wxString t = m_data->ResolveType(type);
CData::CTypeList::iterator iter = m_data->m_list.find(t);
if (iter == m_data->m_list.end()) throw EXCEPTION(_T("Document type '") + type + _T("' not registered."));
wxArrayString strArr;
Explode (ext, strArr, _T(";"));
for (size_t i = 0; i < strArr.Count(); i++)
{
m_data->m_extMap[strArr[i].Lower()] = &iter->second;
}
}
/**
* Check if given type exists
*/
bool CTypeManager::TypeExists (const wxString & type)
{
CData::CTypeList::iterator iter = m_data->m_list.find(type);
if (iter != m_data->m_list.end()) return true;
CStringStringHashMap::iterator aliasIter = m_data->m_aliasMap.find(type);
return (aliasIter != m_data->m_aliasMap.end());
}
/**
* Create document from file extension
*/
CDocumentBase * CTypeManager::LoadFile (const wxString & file)
{
wxFileName fn(file);
// If file doesn't exist show the error message
// and return NULL
if (!fn.FileExists())
{
wxString msg = GET_MGR()->GetLang(_T("error.file-not-found"));
msg.Replace(_T("{filename}"), fn.GetFullPath());
wxMessageBox(msg);
return NULL;
}
// find Creator
CData::CExtMap::iterator iter = m_data->m_extMap.find(fn.GetExt().Lower());
// if no loader found show error message:
/// @todo In future provide an options for:
/// - open with existing handler (and allow binding the file)
/// - load with external program
if (iter == m_data->m_extMap.end())
{
wxString msg = GET_MGR()->GetLang(_T("error.type-not-supported"));
msg.Replace(_T("{filename}"), fn.GetFullPath());
wxMessageBox(msg);
return NULL;
}
// Create the document and set the file.
CDocumentBase * doc = iter->second->creator->Create(fn.GetFullPath());
doc->SetDocFile (fn.GetFullPath());
return doc;
}
/**
* create document from type name
*/
CDocumentBase * CTypeManager::NewDocument (const wxString & type)
{
wxString t = m_data->ResolveType(type);
CData::CTypeList::iterator iter = m_data->m_list.find(t);
if (iter == m_data->m_list.end()) return 0L;
return iter->second.creator->Create(_T(""));
}
/**
* Get filter string for file open / save dialog
*/
wxString CTypeManager::GetFileFilters (bool allFiles)
{
wxString filter;
for (CData::CTypeList::iterator iter = m_data->m_list.begin(); iter != m_data->m_list.end(); iter++)
{
wxString ext;
for (CData::CExtMap::iterator ext_iter = m_data->m_extMap.begin(); ext_iter != m_data->m_extMap.end(); ext_iter++)
{
if (ext_iter->second == &iter->second)
{
if (ext.Len()) ext << _T(";");
ext << _T("*.") << ext_iter->first;
}
}
if (ext.Len())
{
if (filter.Len()) filter << _T("|");
filter << iter->second.description << _T(" (") << ext << _T(")|") << ext;
}
}
if (allFiles)
{
if (filter.Len()) filter << _T("|");
filter << _T("All files (*.*)|*.*");
}
return filter;
}
<file_sep>/fbide-wx/sdk/src/EditorModMargin.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EDITOR_MOD_MARGIN_H_INCLUDED
#define EDITOR_MOD_MARGIN_H_INCLUDED
#include <set>
namespace fb
{
class CEditor;
/**
* Editor modification margin indicator
*/
struct CEditorModMargin
{
// markers
enum
{
MARKER_SAVED = 0,
MARKER_EDITED = 1,
FLAG_NONE = 0,
FLAG_SAVED = 1 << MARKER_SAVED,
FLAG_EDITED = 1 << MARKER_EDITED,
MARKER_FLAGS = FLAG_SAVED | FLAG_EDITED,
FULL_EDITED_FLAG= 0xAAAAAAAA,
BITS_PER_STATE = 2,
CELL_SIZE = ( sizeof(unsigned) * 8 ),
STATES_IN_CELL = CELL_SIZE / BITS_PER_STATE,
};
// construct
CEditorModMargin ( CEditor & editor );
// Modify line
void Modify ( unsigned startLine, int lines, int markers );
// submit modified
void SubmitModify ();
// Undo action
void Undo ( unsigned int startLine, int lines );
// Redo action
void Redo ( unsigned int startLine, int lines );
// Apply Undo / Redo
void ApplyMarkers ();
// Push this state to all modified lines
void SetSavePos ( );
// Flush the line cache
void Flush ();
private :
// Set line markers
void SetMarker ( unsigned line, unsigned markers );
// Push value to stack
void Push(unsigned line, unsigned flags);
// Set current position to a value
void Set(unsigned line, unsigned flags);
// get current value
unsigned Top ( unsigned line );
// Pop value from stack
unsigned Undo ( unsigned line );
// Redo the line
unsigned Redo ( unsigned line );
// Set to hold the modified lines
typedef std::set<int> IntSet;
// vector of int's
typedef std::vector<unsigned> IntVector;
// the lines vector
typedef std::vector<IntVector> LinesVector;
// The line marker
typedef std::pair<unsigned, unsigned> LineMarker;
// line markers
typedef std::vector< LineMarker > MarkerVector;
CEditor & m_editor;
IntSet m_pending, m_undoredo;
LinesVector m_lines;
MarkerVector m_lineMarkers;
};
}
#endif // EDITOR_MOD_MARGIN_H_INCLUDED
<file_sep>/fbide-wx/sdk/include/sdk/EditorEvent.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EDITOR_EVENT_H_INCLUDED
#define EDITOR_EVENT_H_INCLUDED
namespace fb
{
/**
* Simple class to represent CEditor events
*/
class DLLIMPORT CEditorEvent
{
public :
// Type enums
enum Type
{
// whenever user inserts text
TYPE_TEXT_INSERT,
// when ever user deletes text
TYPE_TEXT_DELETE,
// undo/redo blocks. called at the end of each
TYPE_BLOCK_MODIFY,
// user performed uno
TYPE_BLOCK_UNDO,
// user performed redo
TYPE_BLOCK_REDO,
// Document save
TYPE_SAVE
};
// Constructor
CEditorEvent (
CEditorEvent::Type t,
int start,
int end
) : type(t), startLine(start), endLine(end) {}
// type of event
CEditorEvent::Type type;
// the start line
int startLine;
// the end line
int endLine;
};
}
#endif // EDITOR_EVENT_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Editor/StcEditor.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "../Manager.h"
#include "../Editor.h"
#include "../Document.h"
#include "../EditorManager.h"
#include "StcEditor.h"
#include "StyleInfo.h"
#include "syntax/FreeBasic.h"
using namespace fbi;
//
// For the moment stick these here
// @temporary!
enum
{
MarginLineNumbers = 0,
MarginChangeBar = 1,
MaginFoldBar = 2
};
BEGIN_EVENT_TABLE(StcEditor, wxScintillaCtrl)
EVT_RIGHT_UP ( StcEditor::OnMouseRight)
EVT_STC_PAINTED (-1, StcEditor::OnUpdateUi)
EVT_STC_ZOOM (-1, StcEditor::OnZoom)
END_EVENT_TABLE()
// tyhe constructor
StcEditor::StcEditor ( wxWindow * wnd, Editor * owner, int index, StcEditor * mirror )
: m_owner(owner), m_index(index), m_mirror(mirror)
{
// create the window
Create(wnd, wxID_ANY,
wxDefaultPosition, wxDefaultSize,
0l, "fbi::StcEditor");
// set doc pointer
if ( m_mirror != nullptr )
{
SetDocPointer( m_mirror->GetDocPointer() );
SetSelection( m_mirror->GetSelectionStart(), m_mirror->GetSelectionEnd() );
ScrollToLine( m_mirror->GetFirstVisibleLine() );
EnsureCaretVisible();
}
// disable context menu
UsePopUp(false);
// load styles
Setup(GET_EDITORMGR()->GetStyle());
// highlighter
// m_highlighter = new FreeBasicSyntax(this);
}
// Show the context menu
void StcEditor::OnMouseRight (wxMouseEvent & event)
{
m_owner->ShowContextMenu(m_index);
}
// Setup the editor. Load general config
void StcEditor::Setup (StyleParser * styles)
{
auto & reg = GET_REG();
// set default highlight
SetStyle(wxSCI_STYLE_DEFAULT, styles->GetStyle(".default"));
StyleClearAll();
// Set Tab Width
int tabWidth = reg["editor.tabWidth"].AsInt(4);
SetTabWidth (tabWidth);
// set to use tabs or spaces
SetUseTabs(reg["editor.useTabs"].AsBool(false));
// set if tab key indents or not?
SetTabIndents(reg["editor.tabIndents"].AsBool(true));
SetBackSpaceUnIndents (true); // ???
// Set Indent size
SetIndent(reg["editor.indentSize"].AsInt(tabWidth));
// Set edge column size
SetEdgeColumn(reg["editor.edgeColumnSize"].AsInt(80));
// Set edge column mode
wxString edgeModeType = reg["editor.edgeMode"].AsString("line");
int edgeMode = wxSCI_EDGE_NONE;
if (edgeModeType == "line") edgeMode = wxSCI_EDGE_LINE;
else if (edgeModeType == "background") edgeMode = wxSCI_EDGE_BACKGROUND;
SetEdgeMode (edgeMode);
// Set EOL mode
wxString eolModeType = reg["editor.eolMode"].AsString();
if (eolModeType == "CR") SetEOLMode(wxSCI_EOL_CR);
else if (eolModeType == "LF") SetEOLMode(wxSCI_EOL_LF);
else SetEOLMode(wxSCI_EOL_CRLF);
// view EOL characters ?
SetViewEOL(reg["editor.viewEOL"].AsBool());
// show indent guides ?
SetIndentationGuides(reg["editor.indentationGuides"].AsBool());
// Show whitespaces ?
SetViewWhiteSpace (
reg["editor.viewWhiteSpace"].AsBool()
? wxSCI_WS_VISIBLEALWAYS : wxSCI_WS_INVISIBLE
);
// show line numbers ?
if (reg["editor.showLineNumbers"].AsBool(true))
{
// line numbers
if (styles && styles->PathExists(".line-margin"))
{
SetStyle(wxSCI_STYLE_LINENUMBER, styles->GetStyle(".line-margin"));
}
// calculate line widths
bool dyn = m_dynamicLineNumberWidth = reg["editor.dynamicLineNumberWidth"].AsBool(true);
CalcLineMarginWidth();
// set margin width
SetMarginWidth (MarginLineNumbers,
dyn
? m_dynLNWidths[0]
: m_dynLNWidths[sizeof(m_dynLNWidths) / sizeof(int) - 1]
);
SetMarginType(MarginLineNumbers, wxSCI_MARGIN_NUMBER);
m_showLineNumbers = true;
}
else SetMarginWidth (MarginLineNumbers, 0);
for (int i = 1; i < 10; i++)
SetMarginWidth(i, 0);
// caret
if (styles && styles->PathExists(".caret"))
{
const StyleInfo & info = styles->GetStyle(".caret");
SetCaretForeground(info.fg);
SetCaretWidth(info.width ? info.width : 1);
/**
* @todo figure out why alpha doesn't work
*/
if (reg["editor.highlightCurrentLine"].AsBool(true))
{
if (info.bg.IsOk())
{
SetCaretLineVisible(true);
SetCaretLineBackground(info.bg);
// SetCaretLineBackAlpha(200);
}
}
}
// Auto indent code
/*
if (m_data)
{
m_data->m_indent = reg["editor.autoIndent"].AsBool(false);
}
*/
// Code folding
/*
if (reg["editor.codeFolding"].AsBool(false))
{
// void SetFoldMarginColour(bool useSetting, const wxColour& back);
// void SetFoldMarginHiColour(bool useSetting, const wxColour& fore);
const StyleInfo & info = styles->GetStyle(".fold-margin");
SetMarginWidth (MaginFoldBar, info.width ? info.width : 12);
SetMarginType (MaginFoldBar, wxSCI_MARGIN_SYMBOL);
SetMarginMask (MaginFoldBar, wxSCI_MASK_FOLDERS);
const wxColor & outline = info.fg;
const wxColor & fore = info.bg;
SetFoldFlags(wxSCI_FOLDFLAG_LINEAFTER_CONTRACTED);
MarkerDefine(wxSCI_MARKNUM_FOLDER, wxSCI_MARK_BOXPLUS, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEREND, wxSCI_MARK_BOXPLUSCONNECTED,fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERMIDTAIL, wxSCI_MARK_TCORNER, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEROPEN, wxSCI_MARK_BOXMINUS, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEROPENMID, wxSCI_MARK_BOXMINUSCONNECTED,fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERSUB, wxSCI_MARK_VLINE, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERTAIL, wxSCI_MARK_LCORNER, fore, outline);
SetMarginSensitive (MaginFoldBar, 1);
SetProperty ("fold", "1");
SetProperty ("fold.comment", "1");
SetProperty ("fold.compact", "1");
SetProperty ("fold.preprocessor", "1");
}
*/
/*
// Show modification margin
if (reg["editor.showChangeMargin"].AsBool(true))
{
const StyleInfo & info = styles->GetStyle(_T(".edit-margin"));
m_data->m_changeMargin = true;
SetMarginWidth(MARGIN_CHANGE, 4);
SetMarginType(MARGIN_CHANGE, wxSCI_MARGIN_SYMBOL);
SetMarginWidth(MARGIN_CHANGE, 4);
SetMarginMask(MARGIN_CHANGE, (1 << CEditorModMargin::MARKER_SAVED) | (1 << CEditorModMargin::MARKER_EDITED) );
// edited marker
MarkerDefine(CEditorModMargin::MARKER_EDITED, wxSCI_MARK_FULLRECT);
MarkerSetBackground(CEditorModMargin::MARKER_EDITED, info.bg);
// saved marker
MarkerDefine(CEditorModMargin::MARKER_SAVED, wxSCI_MARK_FULLRECT);
MarkerSetBackground(CEditorModMargin::MARKER_SAVED, info.fg);
}
*/
// process TAB key manually to allow
// adding switching between tabs ????
// CmdKeyClear (wxSCI_KEY_TAB, 0);
}
// Set style
void StcEditor::SetStyle (int nr, const StyleInfo & style)
{
// wxMessageBox(style.AsString());
StyleSetFaceName (nr, style.font);
StyleSetSize (nr, style.size);
StyleSetItalic (nr, style.italic);
StyleSetBold (nr, style.bold);
StyleSetUnderline (nr, style.underlined);
StyleSetForeground (nr, style.fg);
StyleSetBackground (nr, style.bg);
}
// Calculate margin widths for dynamic line margin
void StcEditor::CalcLineMarginWidth ()
{
int w = TextWidth (wxSCI_STYLE_LINENUMBER, "0");
for (int i = 0; i < sizeof(m_dynLNWidths) / sizeof(int); i++)
m_dynLNWidths[i] = w * (i + 3);
}
// Update the editor UI
void StcEditor::OnUpdateUi (wxStyledTextEvent & event)
{
// int line = m_parent->GetCurrentLine();
if (m_showLineNumbers && m_dynamicLineNumberWidth)
{
// get last visible line
int lastLine = GetFirstVisibleLine() + LinesOnScreen();
// detect width
int w = lastLine < 99 ?
m_dynLNWidths[0] : lastLine < 999 ?
m_dynLNWidths[1] : lastLine < 9999 ?
m_dynLNWidths[2] : lastLine < 99999 ?
m_dynLNWidths[3] : m_dynLNWidths[4];
// set width
SetMarginWidth (MarginLineNumbers, w);
}
}
// Zoom in/out
void StcEditor::OnZoom (wxStyledTextEvent & event)
{
CalcLineMarginWidth();
if (m_showLineNumbers && !m_dynamicLineNumberWidth)
{
SetMarginWidth (MarginLineNumbers, m_dynLNWidths[sizeof(m_dynLNWidths) / sizeof(int) - 1]);
}
}
<file_sep>/fbide-wx/sdk/src/EditorManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk/Manager.h"
#include "sdk/Editor.h"
#include "sdk/EditorEvent.h"
#include "sdk/EditorManager.h"
#include "sdk/Singleton.h"
using namespace fb;
struct EdMgr : public CEditorManager, public CSingleton<EdMgr>
{
// Alloc accesses ...
friend class CSingleton<EdMgr>;
friend class CEditorManager;
// Register new editor
void RegisterEditor ( CEditor * editor )
{
GetEventMap(EVT_OPEN)(EVT_OPEN, *editor);
}
};
// Get and Free
CEditorManager * CEditorManager::Get () { return EdMgr::GetInstance(); }
void CEditorManager::Free () { EdMgr::Release (); }
<file_sep>/fbide-wx/sdk/include/sdk/UiToolDescriptor.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef UITOOLDESCRIPTOR_H_INCLUDED
#define UITOOLDESCRIPTOR_H_INCLUDED
namespace fb
{
/**
* For menu and toolbar entries that require special handling
* - like fullscreen that has a checkbox...
*/
class CUiToolDescriptor
{
public :
/**
* Degate method for Toggle tools
* to get is toggled or not.
*/
typedef Delegate0<bool> ToggleCallback;
typedef Delegate<void (bool)> VoidBoolDelegate;
typedef CMultiDelegate<void (bool)> VoidBoolMultiDelegate;
VoidBoolMultiDelegate m_checkEvt;
/**
* Supported tool types
*/
enum
{
TOOL_NORMAL = 0,
TOOL_TOGGLE = 1
};
/**
* Is toggle tool ?
*/
bool IsToggleTool () { return m_type == TOOL_TOGGLE; }
/**
* Get Tool type
*/
int GetType () { return m_type; }
/**
* Is checked? (callback)
*/
bool IsChecked ()
{
if (IsToggleTool()) return m_toggleCallback ();
return false;
}
/**
* Register event receaver
*/
void Connect (VoidBoolDelegate signal)
{
m_checkEvt += signal;
}
/**
* Send event
*/
void Notify (bool checked)
{
m_checkEvt(checked);
}
/**
* Create Toggle tool (2 state checked and unchecked)
*/
static CUiToolDescriptor * CreateToggleTool (ToggleCallback callback)
{
CUiToolDescriptor * tool = new CUiToolDescriptor ();
tool->m_type = TOOL_TOGGLE;
tool->m_toggleCallback = callback;
return tool;
}
private :
int m_type;
ToggleCallback m_toggleCallback;
// use CreateXxx methods
CUiToolDescriptor () : m_type(TOOL_NORMAL) { }
};
}
#endif // UITOOLDESCRIPTOR_H_INCLUDED
<file_sep>/fbide-rw/sdk/manager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "manager.h"
#include "uimanager.h"
#include "scriptmanager.h"
#include "docmanager.h"
#include "editormanager.h"
#include "registry.h"
#include "pluginmanager.h"
#include "typemanager.h"
using namespace fb;
/**
* Manager class implementation
*/
struct TheManager : Manager
{
// create
TheManager() = default;
// destroy
~TheManager()
{
ReleaseManagers();
}
// get version information
virtual const Version & GetVersion()
{
// the static version object
static Version v =
{
SDK_VERSION_MAJOR,
SDK_VERSION_MINOR,
SDK_VERSION_RELEASE,
SDK_VERSION_STRING,
__TIMESTAMP__
};
// return const ref
return v;
}
// get global registry object
virtual Registry & GetRegistry()
{
return m_reg;
}
// get translations
virtual Language & GetLang()
{
return m_lang;
}
// application registry ( configuration )
Registry m_reg;
// language
Language m_lang;
};
// Get Ui manager instance
UiManager * Manager::GetUiManager()
{
return UiManager::GetInstance();
}
// Get Ui manager instance
ScriptManager * Manager::GetScriptManager()
{
return ScriptManager::GetInstance();
}
// get document manager
DocManager * Manager::GetDocManager()
{
return DocManager::GetInstance();
}
// Get editor manager
EditorManager * Manager::GetEditorManager()
{
return EditorManager::GetInstance();
}
// get plugin manager
PluginManager * Manager::GetPluginManager()
{
return PluginManager::GetInstance();
}
// type manager
TypeManager * Manager::GetTypeManager()
{
return TypeManager::GetInstance();
}
/**
* Release all managers. The order is important
* And probably needs some adjustment later on
*
* Logically thinking plugin and scripting should go down
* first, followed by various content managers and lastly
* the ui
*/
void Manager::ReleaseManagers()
{
PluginManager::Release();
ScriptManager::Release();
TypeManager::Release();
EditorManager::Release();
DocManager::Release();
UiManager::Release();
}
// implement manager
IMPLEMENT_MANAGER( Manager, TheManager )
<file_sep>/fbide-vs/Sdk/Editor/Syntax/FreeBasic.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "FreeBasic.h"
#include "LexFreeBasic.h"
#include "LineStates.h"
#include "../StcEditor.h"
#include "../StyleInfo.h"
#include "../Editor.h"
#include "../../Manager.h"
#include "../../EditorManager.h"
#include "../../UiManager.h"
using namespace fbi;
using namespace LEX;
FreeBasicSyntax::FreeBasicSyntax (StcEditor * stc)
: m_stc(stc)
{
// Set editor styling
m_stc->SetLexer (LEX::FREEBASIC);
StyleParser * parser = GET_EDITORMGR()->GetStyle();
// Set m_lineStates
m_lineStates = new CLineStates();
wxString lineStates;
lineStates << (int) m_lineStates;
m_stc->SetProperty("lineStates", lineStates);
// get registry
auto & reg = GET_REG();
// Set vars...
m_lineStates->m_dialect = LEX::DIALECT_QB;
m_lineStates->m_drawIndentedBoxes = reg["editor.drawIndentedBoxes"].AsBool(true);
m_lineStates->m_tabWidth = reg["editor.tabWidth"].AsInt(4);
m_lineStates->m_optionEscape = false;
// Load the keywords
m_stc->SetKeyWords(KEYWORD_ONE, reg["fb.keywords.one"].AsString("asm end"));
m_stc->SetKeyWords(KEYWORD_TWO, reg["fb.keywords.two"].AsString("print"));
m_stc->SetKeyWords(KEYWORD_THREE, reg["fb.keywords.three"].AsString("and or xor not"));
m_stc->SetKeyWords(KEYWORD_FOUR, reg["fb.keywords.four"].AsString("abs rgb rgba"));
m_stc->SetKeyWords(KEYWORD_PP_ONE, reg["fb.keywords.preprocessor.one"].AsString("include ifdef macro endmacro"));
m_stc->SetKeyWords(KEYWORD_PP_TWO, reg["fb.keywords.preprocessor.two"].AsString("define defined"));
m_stc->SetKeyWords(KEYWORD_ASM_ONE, reg["fb.keywords.asm.one"].AsString("mov inc dec add sub"));
m_stc->SetKeyWords(KEYWORD_ASM_TWO, reg["fb.keywords.asm.two"].AsString("eax ebx ecx edx abp esp"));
// define error indicator. (should this be moved to CEditor too?)
m_stc->IndicatorSetStyle(0, wxSCI_INDIC_SQUIGGLE);
m_stc->IndicatorSetForeground(0, wxColor("red"));
// 63 possible LEX states (minus 32-39)
m_stc->SetStyleBits(6);
// get styles default
StyleInfo info;
StyleInfo defInfo = parser->GetStyle(".default");
StyleInfo asmInfo = parser->GetStyle(".asm");
StyleInfo ppInfo = parser->GetStyle(".preprocessor");
// normalize default
if (!defInfo.bg.IsOk()) defInfo.bg = wxColor("white");
// default
m_stc->SetStyle(FB_DEFAULT, defInfo);
// identifier
info = parser->GetStyle(".identifier");
bool hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_IDENTIFIER, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_IDENTIFIER, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_IDENTIFIER, info);
// comment
info = parser->GetStyle(".comment");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_COMMENT, info);
// multiline comments should fille the line
m_stc->StyleSetEOLFilled(FB_COMMENT, true);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_COMMENT, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_COMMENT, info);
// comment url
info = parser->GetStyle(".comment.url");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_COMMENT_URL, info);
m_stc->StyleSetEOLFilled(FB_COMMENT_URL, true);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_COMMENT_URL, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_COMMENT_URL, info);
// label
info = parser->GetStyle(".label");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_LABEL, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_LABEL, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_LABEL, info);
// string
info = parser->GetStyle(".string");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_STRING, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_STRING, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_STRING, info);
// string edcapes
info = parser->GetStyle(".string.escape");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_STRING_ESCAPE, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_STRING_ESCAPE, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_STRING_ESCAPE, info);
// number
info = parser->GetStyle(".number");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_NUMBER, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_NUMBER, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_NUMBER, info);
// operator
info = parser->GetStyle(".operator");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_OPERATOR, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_OPERATOR, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_OPERATOR, info);
// FB keywords
info = parser->GetStyle(".keyword.one");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_KEYWORD_ONE, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_FB_KEYWORD_ONE, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_FB_KEYWORD_ONE, info);
info = parser->GetStyle(".keyword.two");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_KEYWORD_TWO, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_FB_KEYWORD_TWO, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_FB_KEYWORD_TWO, info);
info = parser->GetStyle(".keyword.three");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_KEYWORD_THREE, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_FB_KEYWORD_THREE, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_FB_KEYWORD_THREE, info);
info = parser->GetStyle(".keyword.four");
hasBg = info.bg.IsOk();
if (!hasBg) info.bg = defInfo.bg;
m_stc->SetStyle(FB_KEYWORD_FOUR, info);
if (!hasBg) info.bg = asmInfo.bg;
m_stc->SetStyle(ASM_FB_KEYWORD_FOUR, info);
if (!hasBg) info.bg = ppInfo.bg;
m_stc->SetStyle(PP_FB_KEYWORD_FOUR, info);
// ASM block
m_stc->SetStyle(ASM_DEFAULT, asmInfo);
m_stc->SetStyle(ASM_KEYWORD_ONE, parser->GetStyle(".asm.keyword.one"));
m_stc->SetStyle(ASM_KEYWORD_TWO, parser->GetStyle(".asm.keyword.two"));
// make all styles in ASM block fill the line
for (int i = ASM_DEFAULT; i <= ASM_SECTION_LAST; i++)
m_stc->StyleSetEOLFilled(i, true);
// PP block
m_stc->SetStyle(PP_DEFAULT, ppInfo);
m_stc->SetStyle(PP_KEYWORD_ONE, parser->GetStyle(".preprocessor.keyword.one"));
m_stc->SetStyle(PP_KEYWORD_TWO, parser->GetStyle(".preprocessor.keyword.two"));
// make all pp stataments will the line
for (int i = PP_DEFAULT; i <= PP_SECTION_LAST; i++)
m_stc->StyleSetEOLFilled(i, true);
}
<file_sep>/fbide-wx/Plugins/FBIdePlugin/LexFreeBasic_tmp.cxx
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
/**
* @todo When macro or asm block is closed line is highlighted to the end
* of the line. However ':' character should revert to previous
* section style
*
* @todo asm /' ... \n ... '/ should decide is there a single line
* asm block or multiline. Implement methods "ResolveMultiLineComment"
*
* @todo Reseolve line continuation for ASM blocks
* asm _ \n could be either one liner or a multiline
*
* @todo end (asm|if|while|...) matching. in keyword list have end+asm
* or something
*
* @todo end /' ... \n ... '/ asm should work. as well as
* end _ \n asm
*
* @todo asm and macro block nesting
*
* @todo highlight code blocks that have background based on
* indentation. (looks mich nicer with nested blocks)
*
* @todo implement options to disable certain highlighting features
* escape sequences, block highlighting, ...
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "wx_pch.h"
#include "LexFreeBasic.hxx"
using namespace LEX;
/**
* Allowed URI Schemes inside comments.
* case insensitive.
*/
static const char * URI_SCHEMES[] = {
"http://",
"https://",
"ftp://",
"www.",
0
};
/**
* Allowed (2 char long) escape codes inside strings
* preceded by \
* case sensitive!
*/
const char ESCAPE_CODES[] = {
'a', // beep
'b', // backspace
'f', // formfeed
'l', 'n', // new line
'r', // carriage return
't', // tab
'v', // vertical tab
'\\', // backslash
'"', // double quote
'\'', // single quote
0
};
// Set bit flags
static inline void SET_FLAG (int & value, int flag)
{
value |= flag;
}
// unset bit flags
static inline void UNSET_FLAG (int & value, int flag)
{
value &= (~flag);
}
// toggle bit flags
static inline void TOGGLE_FLAG (int & value, int flag)
{
value ^= flag;
}
/**
* Highlight fb source code
*/
struct CFbSourceLexer
{
/**
* Construct the lexer object
*/
CFbSourceLexer (StyleContext &sc, Accessor &styler, WordList *keywords[])
: m_sc(sc),
m_styler(styler),
m_keywords(keywords),
m_section(0),
m_lineState(0),
m_curNcLevel(0),
m_curNppLevel(0),
m_visibleChars(0),
m_skipForward(false)
{
// setup the state
m_dialect = styler.GetPropertyInt("dialect", LEX::DIALECT_FB);
m_curLine = styler.GetLine(m_sc.currentPos);
// if not the first line then get the state of
// the previous line.
if (m_curLine > 0)
{
m_lineState = m_styler.GetLineState(m_curLine-1);
m_curNcLevel = m_lineState & 0xFF;
m_curNppLevel= (m_lineState >> 8) & 0xFF;
}
// Colorise the document
Parse ();
}
/**
* Parse the syntax
*/
void Parse ()
{
// iterate through the text
while (m_sc.More())
{
// handle line starts
if (m_sc.atLineStart)
{
m_curLine = m_styler.GetLine(m_sc.currentPos);
m_lineState = m_curLine ? m_styler.GetLineState(m_curLine-1) : 0;
m_section = GetSectionType (m_sc.state);
ParseLineStart ();
// do not reset if is a multiline comment
if (m_curNcLevel == 0) m_visibleChars = 0;
}
// handle non default states (comments, strings, ...)
if (!IsInDefaultSection(m_sc.state))
{
m_section = GetSectionType (m_sc.state);
ParseState ();
}
// handle default states (fb, asm, pp)
if (IsInDefaultSection(m_sc.state))
{
m_section = GetSectionType (m_sc.state);
ParseDefault ();
}
// handle line ends.
if (m_sc.atLineEnd)
{
m_section = GetSectionType (m_sc.state);
ParseLineEnd ();
}
else
{
if (!IsInAnyComment(m_sc.state) && !IsASpaceOrTab(m_sc.ch))
m_visibleChars++;
}
// skip call to m_sc.Forward() ?
if (m_skipForward)
{
m_skipForward = false;
continue;
}
m_sc.Forward();
}
// finalize
m_sc.Complete();
}
/**
* Handle the line beginning
*/
void ParseLineStart ()
{
Log("<<< ParseLineStart : m_section=%d", m_section);
Log("<<< ParseLineStart : m_lineState=%d", m_lineState);
if (m_curNcLevel > 0)
{
m_sc.SetState(m_section + FB_COMMENT);
}
else if (IsInComment(m_sc.state))
{
m_sc.SetState(m_section);
}
else if (m_section == PP_DEFAULT)
{
if (m_lineState & LINESTATE_LINE_CONTINUATION)
{
UNSET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION);
m_sc.SetState(PP_DEFAULT);
}
else
{
if (m_curNppLevel==0)
m_sc.SetState(GetPrevSectionType());
}
}
else if (m_lineState & LINESTATE_MULTILINE_ASM)
{
m_sc.SetState(ASM_DEFAULT);
}
else if (m_section == ASM_DEFAULT)
{
if (m_lineState & LINESTATE_LINE_CONTINUATION)
{
UNSET_FLAG(m_lineState, LINESTATE_LINE_CONTINUATION);
m_sc.SetState(ASM_DEFAULT);
}
else
{
m_sc.SetState(GetPrevSectionType());
}
}
else
m_sc.SetState(FB_DEFAULT);
}
/**
* Parse the state indicated in m_sc.state
* that is not default
*/
void ParseState ()
{
// multiline comment
if (IsInAnyComment(m_sc.state))
ParseComment();
else if (IsInString(m_sc.state))
ParseString();
}
/**
* Parse default state
*/
void ParseDefault ()
{
// a single line comment. at line start may be followed
// by QB style metacommand
if (m_sc.ch == '\'')
{
m_sc.SetState(m_section + FB_COMMENT);
if (m_visibleChars==0)
{
m_sc.Forward();
SkipSpacesAndTabs();
ParseSingleLineComment();
}
}
// single line comment using REM keyword. At line start
// can be followed by metacommand
else if (!IsAWordChar(m_sc.GetRelative(3)) && m_sc.Match("rem"))
{
m_sc.SetState(m_section + GetFbKeywordType("rem", FB_COMMENT));
m_sc.Forward(3);
m_sc.SetState(m_section + FB_COMMENT);
if (m_visibleChars==0 && IsASpaceOrTab(m_sc.ch))
{
SkipSpacesAndTabs();
m_sc.SetState(m_section + FB_COMMENT);
ParseSingleLineComment();
}
}
// multiline comment. Can be nested!
else if (m_sc.Match('/', '\''))
{
m_sc.SetState(m_section + FB_COMMENT);
m_curNcLevel++;
m_sc.Forward();
}
// string literals
else if (m_sc.ch == '"')
{
if (m_dialect <= DIALECT_LITE)
{
if (m_styler.GetPropertyInt("option.escape", false))
{
m_lineState |= LINESTATE_ESCAPE_STRING;
}
}
m_sc.SetState(m_section + FB_STRING);
}
// explicitly NON escaped string literal
else if (m_sc.Match('$', '"'))
{
m_sc.SetState(m_section + FB_STRING);
m_sc.Forward();
}
// explicitly escaped string literal
else if (m_sc.Match('!', '"'))
{
m_lineState |= LINESTATE_ESCAPE_STRING;
m_sc.SetState(m_section + FB_STRING);
m_sc.Forward();
}
// macro
else if (m_sc.Match('#') && m_visibleChars == 0)
{
ParsePreprocessor ();
}
// decimal or floating point number
else if (IsADigit(m_sc.ch) ||
(m_sc.ch == '.' && IsADigit(m_sc.chNext) && !IsADigit(m_sc.chPrev))
) {
ParseNumber(10);
}
// hex number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'h')
{
m_sc.Forward(2);
ParseNumber(16);
}
// octal number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'o')
{
m_sc.Forward(2);
ParseNumber(8);
}
// binary number
else if (m_sc.ch == '&' && tolower(m_sc.chNext) == 'b')
{
m_sc.Forward(2);
ParseNumber(2);
}
// is a asm block start ?
else if (m_section != ASM_DEFAULT
&& !IsAWordChar(m_sc.GetRelative(3))
&& m_sc.Match("asm"))
{
m_skipForward = true;
m_sc.SetState(ASM_DEFAULT + GetFbKeywordType("asm"));
m_sc.Forward(3);
m_sc.SetState(ASM_DEFAULT);
m_visibleChars+=3;
SkipSpacesAndTabs();
if (!m_sc.atLineEnd) m_skipForward = true;
if (!IsAWordChar(m_sc.ch)
&& (!m_sc.MatchIgnoreCase("rem") || !IsAWordChar(m_sc.GetRelative(3))
))
{
m_lineState |= LINESTATE_MULTILINE_ASM;
}
}
// is a asm block start ?
else if (m_section == ASM_DEFAULT
&& (m_lineState & LINESTATE_MULTILINE_ASM)
&& !IsAWordChar(m_sc.GetRelative(3))
&& m_sc.Match("end"))
{
char nw[4];
GetNextInput(m_sc.currentPos+4, nw, 4);
if (GetNextInput(m_sc.currentPos+4, nw, 4) && (strcmpi(nw, "asm") == 0))
{
m_sc.SetState(m_section + GetFbKeywordType("end"));
m_sc.Forward(3);
m_sc.SetState(m_section);
SkipSpacesAndTabs();
m_sc.SetState(m_section + GetFbKeywordType("asm"));
m_sc.Forward(3);
m_sc.SetState(m_section);
UNSET_FLAG(m_lineState, LINESTATE_MULTILINE_ASM);
}
}
// Is a line continuation
else if (m_sc.ch == '_' &&
!IsAWordChar(m_sc.chNext) && !IsAWordChar(m_sc.chPrev)
) {
//m_visibleChars = 0;
m_lineState |= LINESTATE_LINE_CONTINUATION;
m_sc.SetState(m_section);
// if (m_section == PP_DEFAULT)
}
// command seperator
else if (m_sc.ch == ':')
{
// set to minus one because it will be incremented
// at next at next iteration anyway
m_visibleChars = -1;
m_sc.SetState(m_section);
}
// a keyword or an identifier
else if (IsAWordChar(m_sc.ch))
{
// m_sc.SetState(PP_DEFAULT);
int curPos = m_sc.currentPos;
// skip the word chars?
while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch))
{
m_sc.Forward();
m_skipForward = true;
m_visibleChars++;
}
char s[25];
getRange(curPos, m_sc.currentPos-1, s, sizeof(s));
if (m_section == ASM_DEFAULT)
{
m_sc.ChangeState(GetAsmKeywordType(s));
}
else
{
if (m_section == PP_DEFAULT && strcmpi(s, "once") == 0)
{
m_sc.ChangeState(GetPpKeywordStyle("once"));
}
else
{
m_sc.ChangeState(m_section + GetFbKeywordType(s));
}
}
m_sc.SetState(m_section);
}
else if (IsOperator(m_sc.ch))
{
m_sc.SetState(m_section + FB_OPERATOR);
while (
IsOperator(m_sc.ch)
&& !m_sc.Match('/', '\'')
&& (m_sc.ch != '.' || !IsADigit(m_sc.chNext, 10))
) {
m_sc.Forward();
m_skipForward = true;
m_visibleChars++;
}
m_sc.SetState(m_section);
}
}
/**
* Handle the line end
*/
void ParseLineEnd ()
{
// set to default section so proper section background
// colour could fill the screen as needed.
// in case of multiline non-default styles they
// will be continued in ParseLineStart
if (!IsInComment(m_sc.state)) m_sc.SetState(m_section);
Log(">>> ParseLineEnd : m_section=%d", m_section);
Log(">>> ParseLineEnd : m_lineState=%d", m_lineState);
// set comment nest level
m_lineState = (m_lineState & 0xFFFFFF00) | m_curNcLevel;
m_lineState = (m_lineState & 0xFFFF00FF) | (m_curNppLevel<<8);
// set current line state
m_styler.SetLineState(m_curLine, m_lineState);
}
/**
* Check if the char is a valid FB operator
*/
bool IsOperator (int ch)
{
return ch == '&'
|| ch == '*'
|| ch == '('
|| ch == ')'
|| ch == '-'
|| ch == '+'
|| ch == '='
|| ch == '{'
|| ch == '}'
|| ch == '['
|| ch == ']'
|| ch == ':'
|| ch == ';'
|| ch == '@'
|| ch == '#'
|| ch == '\\'
|| ch == ','
|| ch == '<'
|| ch == '>'
|| ch == '.'
|| ch == '/'
|| ch == '?'
;
}
/**
* Parse number
*/
bool ParseNumber (int base)
{
// m_sc.SetState(PP_DEFAULT);
int curPos = m_sc.currentPos;
int fpCount = 0;
// skip the word chars?
while (!m_sc.atLineEnd &&
(IsADigit(m_sc.ch, base)
|| (m_sc.ch == '.' && base == 10 && !(fpCount++)))
) {
m_sc.Forward();
m_skipForward = true;
m_visibleChars++;
}
char s[25];
getRange(curPos, m_sc.currentPos-1, s, sizeof(s));
m_sc.ChangeState(m_section + FB_NUMBER);
m_sc.SetState(m_section);
return true;
}
/**
* Retreave a range of characters into a string
*/
void getRange(unsigned int start, unsigned int end,
char *s, unsigned int len)
{
unsigned int i = 0;
while ((i < end - start + 1) && (i < len-1))
{
s[i] = static_cast<char>(tolower(m_styler[start + i]));
i++;
}
s[i] = '\0';
}
/**
* Get non whitespace range for the lenght
* skip any spaces or tabs and return when hitting first
* non-printable character (space, tab, newline)
*/
bool GetNextInput (unsigned int start, char *s, unsigned int len)
{
unsigned int i = 0;
s[i] = '\0';
// skip any spaces or tabs
for ( ; ; start++)
{
char ch = m_styler[start];
if (IsAWordChar(ch)) break;
if (ch == '\n' || ch == '\r') return false;
}
getRange (start, start + len, s, len);
return true;
}
/**
* Parse preprocessor block beginning.
*/
void ParsePreprocessor ()
{
m_sc.SetState(PP_DEFAULT);
m_sc.Forward();
SkipSpacesAndTabs();
if (m_sc.atLineEnd) return;
m_skipForward = true;
// macro's can nest and cover multiple lines
if (m_sc.MatchIgnoreCase("macro"))
{
m_curNppLevel++;
m_sc.ChangeState(GetPpKeywordStyle("macro"));
m_sc.Forward(5);
m_sc.SetState(PP_DEFAULT);
}
else if (m_sc.MatchIgnoreCase("endmacro"))
{
if (m_curNppLevel) m_curNppLevel--;
m_sc.ChangeState(GetPpKeywordStyle("endmacro"));
m_sc.Forward(8);
if (m_curNppLevel)
{
m_sc.SetState(PP_DEFAULT);
// try to style till the end of the line.
// looks better.
}
else
{
/// @todo figure out if it is inside ASM block or not
//m_sc.SetState(FB_DEFAULT);
// try to style till the end of the line.
// looks better.
m_sc.SetState(PP_DEFAULT);
}
m_skipForward = true;
}
else if (IsAWordChar(m_sc.ch))
{
// m_sc.SetState(PP_DEFAULT);
int curPos = m_sc.currentPos;
// skip the word chars?
while (!m_sc.atLineEnd && IsAWordChar(m_sc.ch))
{
m_sc.Forward();
}
char s[25];
// m_sc.GetCurrent(s, sizeof(s));
getRange(curPos, m_sc.currentPos-1, s, sizeof(s));
m_sc.ChangeState(GetPpKeywordStyle(s));
m_sc.SetState(PP_DEFAULT);
}
}
/**
* Parse string literals
*/
void ParseString ()
{
if (m_sc.Match('"', '"'))
{
m_sc.SetState(m_section+FB_STRING_ESCAPE);
m_sc.Forward(2);
m_sc.SetState(m_section+FB_STRING);
}
else if (m_sc.Match('"'))
{
m_sc.Forward();
m_sc.SetState(m_section);
m_lineState &= (~LINESTATE_ESCAPE_STRING);
return;
}
// not an escape code
int indStart = m_sc.currentPos;
bool matched = false;
if (m_sc.ch != '\\' || !(m_lineState & LINESTATE_ESCAPE_STRING))
return;
m_sc.SetState(m_section+FB_STRING_ESCAPE);
m_sc.Forward();
// Simple sequences (case sensitive!)
if (FindMatch(ESCAPE_CODES))
{
m_sc.ForwardSetState(m_section+FB_STRING);
matched = true;
}
// unicode char in hex \uFFFF
else if (tolower(m_sc.ch) == 'u' && IsNumberRange(1, 4, 16))
{
m_sc.ForwardSetState(m_section+FB_NUMBER);
m_sc.Forward(4);
matched = true;
}
// ascii char in decimal \123
else if (IsNumberRange(0, 3, 10))
{
m_sc.SetState(m_section+FB_NUMBER);
m_sc.Forward(3);
matched = true;
}
// ascii escape sequence in FB style oct, bin or hex
else if (m_sc.ch == '&')
{
m_sc.SetState(m_section+FB_NUMBER);
m_sc.Forward();
// ascii char in hex \&hFF
if (tolower(m_sc.ch) == 'h' && IsNumberRange(1, 2, 16))
{
m_sc.Forward(3);
matched = true;
}
// ascii char in octal \&o777
else if (tolower(m_sc.ch) == 'o' && IsNumberRange(1, 3, 8))
{
m_sc.Forward(4);
matched = true;
}
// ascii char in binary \&b11111111
else if (tolower(m_sc.ch) == 'b' && IsNumberRange(1, 8, 2))
{
m_sc.Forward(9);
matched = true;
}
else
{
m_sc.ChangeState(m_section+FB_STRING);
}
}
// clear or set error indicator
m_styler.IndicatorFill(indStart, m_sc.currentPos, 0, matched ? 0 : 1);
// set back to string
m_sc.SetState(m_section+FB_STRING);
m_skipForward = true;
}
/**
* Check if range of characters are numbers of the base
*/
bool IsNumberRange (int startPos, int count, int base)
{
for (--count; count>=0; count--)
{
Log("count=%d", count);
if (!IsADigit(m_sc.GetRelative(startPos+count), base))
return false;
}
return true;
}
/**
* Parses single line qomment and checks if contains
* any meta keywords (lang, dynamic, static, ...)
* if yes then set style to PP_DEFAULT, highlight the keyword
* and return true.
*/
void ParseSingleLineComment ()
{
// check if is valid start ?
if (m_sc.atLineEnd || m_sc.ch != '$') goto meta_error;
// mov forth and skip any spaces
m_sc.Forward();
SkipSpacesAndTabs ();
if (m_sc.atLineEnd) goto meta_error;
// check if this is a valid meta statament
if (HighlightMetaKeyword("lang", 4)) return;
// allowed only in QB and LITE
if (m_dialect > DIALECT_LITE) goto meta_error;
// include
if (HighlightMetaKeyword("include", 7)) return;
// dynamic
if (HighlightMetaKeyword("dynamic", 7)) return;
// static
if (HighlightMetaKeyword("static", 6)) return;
// avoid call to Forward by Parse() since we already
// moved forward.
meta_error:
m_skipForward = true;
return;
}
/**
* Parse the comments and look for urls inside
*/
void ParseComment ()
{
// if this is a nested comment check if it ends ?
if (m_curNcLevel)
{
if (m_sc.Match('\'', '/'))
{
if (m_curNcLevel) m_curNcLevel--;
m_sc.Forward(2);
if (m_curNcLevel == 0)
{
//SkipSpacesAndTabs();
//if (!m_sc.atLineEnd)
//{
m_sc.SetState(m_section);
//}
return;
}
}
else if (m_sc.Match('/', '\''))
{
m_curNcLevel++;
m_sc.Forward(2);
}
}
if (IsInCommentUrl(m_sc.state))
{
if (IsASpaceOrTab(m_sc.ch) || m_sc.atLineEnd)
m_sc.SetState(m_section + FB_COMMENT);
}
else
{
// needs a non word char infornt
if (IsAWordChar(m_sc.chPrev)) return;
// match uri schemes. if matched then set state
if (int len = FindMatch(URI_SCHEMES))
{
m_sc.SetState(m_section + FB_COMMENT_URL);
m_sc.Forward(len);
}
}
}
/**
* Hightlight a QB style metakeyword inside single
* line comments if matches
* return true if matched.
*/
bool HighlightMetaKeyword (const char * kw, int len)
{
// return if not matches or next char is a word char
if (IsAWordChar(m_sc.GetRelative(len)) || !m_sc.MatchIgnoreCase(kw))
return false;
// colorise
m_sc.Forward(len);
m_sc.ChangeState(GetPpKeywordStyle(kw));
m_sc.SetState(PP_DEFAULT);
return true;
}
/**
* If the given keyword is a preprocessor keyword then
* highlight it to appropriate PP keyword style
*/
int GetPpKeywordStyle (const char * kw)
{
if (m_keywords[KEYWORD_PP_ONE]->InList(kw))
return PP_KEYWORD_ONE;
else if (m_keywords[KEYWORD_PP_ONE]->InList(kw))
return PP_KEYWORD_TWO;
return PP_IDENTIFIER;
}
/**
* Get FB keyword type. If not found FB_IDENTIFIER is returned
*/
int GetFbKeywordType (const char * kw, int defStyle = FB_IDENTIFIER)
{
if (m_keywords[KEYWORD_ONE]->InList(kw))
return FB_KEYWORD_ONE;
else if (m_keywords[KEYWORD_TWO]->InList(kw))
return FB_KEYWORD_TWO;
else if (m_keywords[KEYWORD_THREE]->InList(kw))
return FB_KEYWORD_THREE;
else if (m_keywords[KEYWORD_FOUR]->InList(kw))
return FB_KEYWORD_FOUR;
return defStyle;
}
/**
* Get ASM block keyword type
*/
int GetAsmKeywordType (const char * kw, int defStyle = ASM_IDENTIFIER)
{
if (m_keywords[KEYWORD_ASM_ONE]->InList(kw))
return ASM_KEYWORD_ONE;
else if (m_keywords[KEYWORD_ASM_TWO]->InList(kw))
return ASM_KEYWORD_TWO;
return defStyle;
}
/**
* Printf compatible function that will output to wxMessageLog
*/
void Log (const char * msg, ...) __attribute__((format(printf, 2, 3)))
{
// do thr printf
va_list ap;
va_start(ap, msg);
char temp[4096];
vsnprintf (temp, 4096, msg, ap);
va_end(ap);
// output the wxLog
wxString logMsg(temp, wxConvUTF8);
wxLogMessage(logMsg);
}
/**
* Get Section type
*/
int GetSectionType (int style)
{
if (style <= FB_SECTION_LAST)
return SECTION_FB;
if (style <= ASM_SECTION_LAST)
return SECTION_ASM;
if (style <= PP_SECTION_LAST)
return SECTION_PP;
return SECTION_FB;
}
/**
* Find previous section
*/
int GetPrevSectionType ()
{
int p = m_sc.currentPos;
if (!p) return FB_DEFAULT;
while (--p)
{
int prevSection = GetSectionType(m_styler.StyleAt(p));
if (prevSection != m_section)
return prevSection;
}
return SECTION_FB;
}
/**
* Skip the tabs and spaces
* but stop at anything else
*/
void SkipSpacesAndTabs ()
{
while (!m_sc.atLineEnd && IsASpaceOrTab(m_sc.ch))
m_sc.Forward();
}
/**
* Extended to accept accented characters
*/
bool IsAWordChar(int ch)
{
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
/**
* Find the string from an array that matches
* and return it's length
* or 0 if none
*/
int FindMatch (const char * matches[])
{
for (int i = 0; matches[i]; i++)
if (m_sc.MatchIgnoreCase(matches[i]))
return strlen(matches[i]);
return 0;
}
/**
* Check if any of the chars matches ?
* return char that matches or a 0
*/
char FindMatch(const char matches[])
{
for (int i = 0; matches[i]; i++)
if (m_sc.ch == matches[i])
return matches[i];
return 0;
}
// style context
StyleContext & m_sc;
// Accessor
Accessor & m_styler;
// keywords
WordList ** m_keywords;
// current section
int m_section;
// current line
int m_curLine;
// current line state
int m_lineState;
// current nested comment level
int m_curNcLevel;
// nested pp level
int m_curNppLevel;
// count visible characters
int m_visibleChars;
// current FB dialect
int m_dialect;
// Force to skip default call to Forward()
bool m_skipForward;
};
/**
* Colorise FB document
*/
static void ColouriseFB (
unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler )
{
// Styler
styler.StartAt(startPos, 63);
StyleContext sc (startPos, length, initStyle, styler, 63);
// Fb source lexer
CFbSourceLexer l (sc, styler, keywordlists);
l.Log(">>>> styled from: %d, length: %d\n---------------------------------------------------------------", startPos, length);
}
/**
* Keywords
*/
static const char * const fbWordListDesc[] = {
"FB_kw1",
"FB_kw2",
"FB_kw3",
"FB_kw4",
"FB_pp1",
"FB_pp2",
"FB_asm1",
"FB_asm2",
0
};
// Add the lexer module
LexerModule lmFB(
FREEBASIC, // identifier
ColouriseFB, // colorise proc
"FreeBASIC", // name
NULL, // fold proc
fbWordListDesc, // keywords descriptor
6 // number of style bits used
);
<file_sep>/fbide-vs/Sdk/Ui/ToolbarHandler.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Handle menus
*/
struct UiToolbarHandler
{
// constructor
UiToolbarHandler();
// Initalize
void Init (wxAuiManager * aui, bool useMenu = true);
// Uninitalize
void UnInit ();
// Load from XML
void Load (wxXmlNode * node);
// get toolbar by id
wxAuiToolBar * GetToolBar (const wxString & id);
// Add toolbar
void AddToolBar (const wxString & name, wxAuiToolBar * toolbar, bool show = true);
// add item to toolbar
void AddToolBarItem (const wxString & name, wxAuiToolBar * toolbar);
// Catch pane close events (for toolbars)
void OnPaneClose(wxAuiManagerEvent & event);
// catch tbar menu clicks
void OnCommandEvent(wxCommandEvent & event);
// Show / Hide the toolbars
void ToggleToolbars(bool show);
// Flag check items
void OnCmdMgrEvent(wxCommandEvent & event);
private :
wxAuiManager * m_aui; // toolbar owner
wxWindow * m_parent; // parent window
wxMenu * m_menu; // menu where to put toolbar entries
HashMap<wxAuiToolBar *> m_map; // hold id-toolbar associations
std::unordered_map<int, int> m_idbridge; // bridge toolbar id and a menu commands
std::unordered_map<int, bool> m_visibleMap; // visible toolbar map
int m_visibleCnt; // number of visible toolbars
bool m_showTbars; // Show toolbars
};
}
<file_sep>/fbide-vs/App/app_pch.h
/**
* Precompiled headers.
*
* wxWidgets and fbide sdk
*/
#include "Sdk/sdk_pch.h"
<file_sep>/fbide-vs/Sdk/UiManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "Manager.h"
#include "UiManager.h"
#include "CmdManager.h"
#include "Ui/MenuHandler.h"
#include "Ui/ToolbarHandler.h"
#include "Ui/IArtProvider.h"
#include "Ui/ClassicThemeProvider.h"
#include "Ui/DocFrame.h"
#include "Document.h"
using namespace fbi;
// decouple the tab
const int ID_DecoupleTab = ::wxNewId();
/**
* Manager class implementation
*/
struct TheUiManager : UiManager, wxEvtHandler
{
// create
TheUiManager () : m_frame(nullptr), m_artProvider(nullptr)
{
// register UI related IDs
auto cmdMgr = GET_CMDMGR();
cmdMgr->Register("fullscreen", ::wxNewId(), CmdManager::Type_Check, nullptr);
// Load colours
LoadColours();
}
// destroy
~TheUiManager ()
{}
// Load user interface. Return false if failed.
virtual bool Load ()
{
// Create the frame and set events
m_frame = new wxFrame(
NULL, wxID_ANY, GetTitle() ,
wxDefaultPosition, wxSize(400, 300)
);
wxTheApp->SetTopWindow(m_frame);
m_frame->PushEventHandler(this);
// Load default art provider
SetArtProvider(new ClassicThemeProvider());
// Initalize the menubar
auto menuBar = new wxMenuBar();
m_frame->SetMenuBar(menuBar);
m_menuHandler.Init(menuBar);
// Initalize AUI
m_aui.SetFlags(wxAUI_MGR_LIVE_RESIZE | wxAUI_MGR_DEFAULT);
m_aui.SetManagedWindow(m_frame);
m_aui.Update();
// doc styles
int tabStyles = wxAUI_NB_TAB_MOVE | wxAUI_NB_SCROLL_BUTTONS |
wxAUI_NB_WINDOWLIST_BUTTON | wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT;
// Create document area
m_docArea = new wxAuiNotebook (
m_frame,
wxID_ANY,
wxDefaultPosition, wxDefaultSize,
tabStyles | wxAUI_NB_CLOSE_BUTTON | wxAUI_NB_CLOSE_ON_ACTIVE_TAB
);
m_aui.AddPane (
m_docArea,
wxAuiPaneInfo()
.Name("fbUiMgrDocArea")
.CenterPane()
.PaneBorder(false)
);
// Initalize toolbar
m_tbarHandler.Init(&m_aui);
// Success
return true;
}
// Load layout from xml
virtual void LoadLayout (const wxString & file)
{
// the xml object
wxXmlDocument xml;
// Normalize the file path
wxFileName f(file);
f.Normalize();
wxString layoutFile = f.GetFullPath();
// Check for errors ...
if (!f.FileExists() || !xml.Load(layoutFile))
{
wxLogError(_T("Could not load layout file \"%s\""), layoutFile.c_str());
return;
}
if (!xml.IsOk() || xml.GetRoot()->GetName() != _T("fbide"))
{
wxLogError(_T("Malformed layout file \"%s\""), layoutFile.c_str());
return;
}
if (xml.GetRoot()->GetAttribute("type") != "ui-layout")
{
wxLogError(_T("Type is not 'ui-layou' in \"%s\""), layoutFile.c_str());
return;
}
// load layout
wxXmlNode * child = xml.GetRoot()->GetChildren();
for ( ; child; child = child->GetNext())
{
if (child->GetType() == wxXML_COMMENT_NODE) continue;
if (child->GetName() == "menus")
m_menuHandler.Load(child->GetChildren());
else if (child->GetName() == "toolbars")
m_tbarHandler.Load(child->GetChildren());
else
{
wxLogWarning("Invalid entry <%s> in '%s'", child->GetName(), layoutFile.c_str());
}
}
// Refresh ui
m_aui.Update();
}
// Get application title
// - maybe use later a title template
// to allow customing?
virtual wxString GetTitle ()
{
return wxString("FBIde ") + GET_MGR()->GetVersion().string;
}
// get the main frame
virtual wxFrame * GetFrame () { return m_frame; }
// Get document area base window
virtual wxWindow * GetDocumentArea () { return m_docArea; }
// Set art provider
virtual void SetArtProvider (IArtProvider * provider) { m_artProvider = provider; }
// get art provider
virtual IArtProvider * GetArtProvider () { return m_artProvider; }
// add document
virtual void AddDocument(Document * doc)
{
// check doc pointer
wxASSERT(doc != nullptr);
if (doc == nullptr) return;
// get window
wxWindow * wnd = doc->GetDocWindow();
wxASSERT(wnd != nullptr);
if (wnd == nullptr) return;
// add document
m_docMap[wnd->GetId()] = doc;
m_docArea->AddPage(doc->GetDocWindow(), doc->GetDocTitle(), true);
}
// Handle close event
void OnClose (wxCloseEvent & event)
{
// release art provider
if (m_artProvider != nullptr)
{
delete m_artProvider;
m_artProvider = nullptr;
}
// release toolbar handler
m_tbarHandler.UnInit();
// release menu handler
m_menuHandler.UnInit();
// release aui
m_aui.UnInit();
// get rid of the frame
m_frame->RemoveEventHandler(this);
m_frame->Destroy();
}
// handle command events
void OnCommandEvent (wxCommandEvent & event)
{
// sllow others to catch
event.Skip();
// pass events to documents
// ??? shoudl events be sent only to active window/document?
/*
for (auto iter = m_docMap.begin(); iter != m_docMap.end(); iter++)
{
event.StopPropagation();
auto childFrame = dynamic_cast<wxFrame *>(iter->second->GetDocWindow()->GetParent());
if (childFrame)
{
childFrame->GetEventHandler()->ProcessEvent(event);
}
}
*/
// handle toggle events for menus, toolbars, ...
auto cmdMgr = GET_CMDMGR();
auto info = cmdMgr->FindEntry(event.GetId());
if (info != nullptr && info->type == CmdManager::Type_Check)
{
cmdMgr->Check(event.GetId(), event.IsChecked());
}
}
// On tab context menu
void OnTabContextMenu (wxAuiNotebookEvent & event)
{
// ensure tab is visible
m_docArea->SetSelection(event.GetSelection());
wxMenu * menu = new wxMenu();
menu->Append(ID_DecoupleTab, "Decouple", "Decouple this tab");
m_frame->PopupMenu(menu);
}
// on decouple
void OnDecouple (wxCommandEvent & event)
{
// decouple the tab
int index = m_docArea->GetSelection();
wxWindow * wnd = m_docArea->GetPage(index);
Document * doc = m_docMap[wnd->GetId()];
m_docArea->RemovePage(index);
// create new window
DocFrame * docFrame = new DocFrame(doc);
docFrame->Show();
}
// Load some colours by name
void LoadColours ()
{
wxTheColourDatabase->AddColour("AliceBlue", wxColour("#F0F8FF"));
wxTheColourDatabase->AddColour("AntiqueWhite", wxColour("#FAEBD7"));
wxTheColourDatabase->AddColour("Aqua", wxColour("#00FFFF"));
wxTheColourDatabase->AddColour("Aquamarine", wxColour("#7FFFD4"));
wxTheColourDatabase->AddColour("Azure", wxColour("#F0FFFF"));
wxTheColourDatabase->AddColour("Beige", wxColour("#F5F5DC"));
wxTheColourDatabase->AddColour("Bisque", wxColour("#FFE4C4"));
wxTheColourDatabase->AddColour("Black", wxColour("#000000"));
wxTheColourDatabase->AddColour("BlanchedAlmond", wxColour("#FFEBCD"));
wxTheColourDatabase->AddColour("Blue", wxColour("#0000FF"));
wxTheColourDatabase->AddColour("BlueViolet", wxColour("#8A2BE2"));
wxTheColourDatabase->AddColour("Brown", wxColour("#A52A2A"));
wxTheColourDatabase->AddColour("BurlyWood", wxColour("#DEB887"));
wxTheColourDatabase->AddColour("CadetBlue", wxColour("#5F9EA0"));
wxTheColourDatabase->AddColour("Chartreuse", wxColour("#7FFF00"));
wxTheColourDatabase->AddColour("Chocolate", wxColour("#D2691E"));
wxTheColourDatabase->AddColour("Coral", wxColour("#FF7F50"));
wxTheColourDatabase->AddColour("CornflowerBlue", wxColour("#6495ED"));
wxTheColourDatabase->AddColour("Cornsilk", wxColour("#FFF8DC"));
wxTheColourDatabase->AddColour("Crimson", wxColour("#DC143C"));
wxTheColourDatabase->AddColour("Cyan", wxColour("#00FFFF"));
wxTheColourDatabase->AddColour("DarkBlue", wxColour("#00008B"));
wxTheColourDatabase->AddColour("DarkCyan", wxColour("#008B8B"));
wxTheColourDatabase->AddColour("DarkGoldenRod", wxColour("#B8860B"));
wxTheColourDatabase->AddColour("DarkGray", wxColour("#A9A9A9"));
wxTheColourDatabase->AddColour("DarkGreen", wxColour("#006400"));
wxTheColourDatabase->AddColour("DarkKhaki", wxColour("#BDB76B"));
wxTheColourDatabase->AddColour("DarkMagenta", wxColour("#8B008B"));
wxTheColourDatabase->AddColour("DarkOliveGreen", wxColour("#556B2F"));
wxTheColourDatabase->AddColour("Darkorange", wxColour("#FF8C00"));
wxTheColourDatabase->AddColour("DarkOrchid", wxColour("#9932CC"));
wxTheColourDatabase->AddColour("DarkRed", wxColour("#8B0000"));
wxTheColourDatabase->AddColour("DarkSalmon", wxColour("#E9967A"));
wxTheColourDatabase->AddColour("DarkSeaGreen", wxColour("#8FBC8F"));
wxTheColourDatabase->AddColour("DarkSlateBlue", wxColour("#483D8B"));
wxTheColourDatabase->AddColour("DarkSlateGray", wxColour("#2F4F4F"));
wxTheColourDatabase->AddColour("DarkTurquoise", wxColour("#00CED1"));
wxTheColourDatabase->AddColour("DarkViolet", wxColour("#9400D3"));
wxTheColourDatabase->AddColour("DeepPink", wxColour("#FF1493"));
wxTheColourDatabase->AddColour("DeepSkyBlue", wxColour("#00BFFF"));
wxTheColourDatabase->AddColour("DimGray", wxColour("#696969"));
wxTheColourDatabase->AddColour("DodgerBlue", wxColour("#1E90FF"));
wxTheColourDatabase->AddColour("FireBrick", wxColour("#B22222"));
wxTheColourDatabase->AddColour("FloralWhite", wxColour("#FFFAF0"));
wxTheColourDatabase->AddColour("ForestGreen", wxColour("#228B22"));
wxTheColourDatabase->AddColour("Fuchsia", wxColour("#FF00FF"));
wxTheColourDatabase->AddColour("Gainsboro", wxColour("#DCDCDC"));
wxTheColourDatabase->AddColour("GhostWhite", wxColour("#F8F8FF"));
wxTheColourDatabase->AddColour("Gold", wxColour("#FFD700"));
wxTheColourDatabase->AddColour("GoldenRod", wxColour("#DAA520"));
wxTheColourDatabase->AddColour("Gray", wxColour("#808080"));
wxTheColourDatabase->AddColour("Green", wxColour("#008000"));
wxTheColourDatabase->AddColour("GreenYellow", wxColour("#ADFF2F"));
wxTheColourDatabase->AddColour("HoneyDew", wxColour("#F0FFF0"));
wxTheColourDatabase->AddColour("HotPink", wxColour("#FF69B4"));
wxTheColourDatabase->AddColour("IndianRed", wxColour("#CD5C5C"));
wxTheColourDatabase->AddColour("Indigo", wxColour("#4B0082"));
wxTheColourDatabase->AddColour("Ivory", wxColour("#FFFFF0"));
wxTheColourDatabase->AddColour("Khaki", wxColour("#F0E68C"));
wxTheColourDatabase->AddColour("Lavender", wxColour("#E6E6FA"));
wxTheColourDatabase->AddColour("LavenderBlush", wxColour("#FFF0F5"));
wxTheColourDatabase->AddColour("LawnGreen", wxColour("#7CFC00"));
wxTheColourDatabase->AddColour("LemonChiffon", wxColour("#FFFACD"));
wxTheColourDatabase->AddColour("LightBlue", wxColour("#ADD8E6"));
wxTheColourDatabase->AddColour("LightCoral", wxColour("#F08080"));
wxTheColourDatabase->AddColour("LightCyan", wxColour("#E0FFFF"));
wxTheColourDatabase->AddColour("LightGoldenRodYellow", wxColour("#FAFAD2"));
wxTheColourDatabase->AddColour("LightGrey", wxColour("#D3D3D3"));
wxTheColourDatabase->AddColour("LightGreen", wxColour("#90EE90"));
wxTheColourDatabase->AddColour("LightPink", wxColour("#FFB6C1"));
wxTheColourDatabase->AddColour("LightSalmon", wxColour("#FFA07A"));
wxTheColourDatabase->AddColour("LightSeaGreen", wxColour("#20B2AA"));
wxTheColourDatabase->AddColour("LightSkyBlue", wxColour("#87CEFA"));
wxTheColourDatabase->AddColour("LightSlateGray", wxColour("#778899"));
wxTheColourDatabase->AddColour("LightSteelBlue", wxColour("#B0C4DE"));
wxTheColourDatabase->AddColour("LightYellow", wxColour("#FFFFE0"));
wxTheColourDatabase->AddColour("Lime", wxColour("#00FF00"));
wxTheColourDatabase->AddColour("LimeGreen", wxColour("#32CD32"));
wxTheColourDatabase->AddColour("Linen", wxColour("#FAF0E6"));
wxTheColourDatabase->AddColour("Magenta", wxColour("#FF00FF"));
wxTheColourDatabase->AddColour("Maroon", wxColour("#800000"));
wxTheColourDatabase->AddColour("MediumAquaMarine", wxColour("#66CDAA"));
wxTheColourDatabase->AddColour("MediumBlue", wxColour("#0000CD"));
wxTheColourDatabase->AddColour("MediumOrchid", wxColour("#BA55D3"));
wxTheColourDatabase->AddColour("MediumPurple", wxColour("#9370D8"));
wxTheColourDatabase->AddColour("MediumSeaGreen", wxColour("#3CB371"));
wxTheColourDatabase->AddColour("MediumSlateBlue", wxColour("#7B68EE"));
wxTheColourDatabase->AddColour("MediumSpringGreen", wxColour("#00FA9A"));
wxTheColourDatabase->AddColour("MediumTurquoise", wxColour("#48D1CC"));
wxTheColourDatabase->AddColour("MediumVioletRed", wxColour("#C71585"));
wxTheColourDatabase->AddColour("MidnightBlue", wxColour("#191970"));
wxTheColourDatabase->AddColour("MintCream", wxColour("#F5FFFA"));
wxTheColourDatabase->AddColour("MistyRose", wxColour("#FFE4E1"));
wxTheColourDatabase->AddColour("Moccasin", wxColour("#FFE4B5"));
wxTheColourDatabase->AddColour("NavajoWhite", wxColour("#FFDEAD"));
wxTheColourDatabase->AddColour("Navy", wxColour("#000080"));
wxTheColourDatabase->AddColour("OldLace", wxColour("#FDF5E6"));
wxTheColourDatabase->AddColour("Olive", wxColour("#808000"));
wxTheColourDatabase->AddColour("OliveDrab", wxColour("#6B8E23"));
wxTheColourDatabase->AddColour("Orange", wxColour("#FFA500"));
wxTheColourDatabase->AddColour("OrangeRed", wxColour("#FF4500"));
wxTheColourDatabase->AddColour("Orchid", wxColour("#DA70D6"));
wxTheColourDatabase->AddColour("PaleGoldenRod", wxColour("#EEE8AA"));
wxTheColourDatabase->AddColour("PaleGreen", wxColour("#98FB98"));
wxTheColourDatabase->AddColour("PaleTurquoise", wxColour("#AFEEEE"));
wxTheColourDatabase->AddColour("PaleVioletRed", wxColour("#D87093"));
wxTheColourDatabase->AddColour("PapayaWhip", wxColour("#FFEFD5"));
wxTheColourDatabase->AddColour("PeachPuff", wxColour("#FFDAB9"));
wxTheColourDatabase->AddColour("Peru", wxColour("#CD853F"));
wxTheColourDatabase->AddColour("Pink", wxColour("#FFC0CB"));
wxTheColourDatabase->AddColour("Plum", wxColour("#DDA0DD"));
wxTheColourDatabase->AddColour("PowderBlue", wxColour("#B0E0E6"));
wxTheColourDatabase->AddColour("Purple", wxColour("#800080"));
wxTheColourDatabase->AddColour("Red", wxColour("#FF0000"));
wxTheColourDatabase->AddColour("RosyBrown", wxColour("#BC8F8F"));
wxTheColourDatabase->AddColour("RoyalBlue", wxColour("#4169E1"));
wxTheColourDatabase->AddColour("SaddleBrown", wxColour("#8B4513"));
wxTheColourDatabase->AddColour("Salmon", wxColour("#FA8072"));
wxTheColourDatabase->AddColour("SandyBrown", wxColour("#F4A460"));
wxTheColourDatabase->AddColour("SeaGreen", wxColour("#2E8B57"));
wxTheColourDatabase->AddColour("SeaShell", wxColour("#FFF5EE"));
wxTheColourDatabase->AddColour("Sienna", wxColour("#A0522D"));
wxTheColourDatabase->AddColour("Silver", wxColour("#C0C0C0"));
wxTheColourDatabase->AddColour("SkyBlue", wxColour("#87CEEB"));
wxTheColourDatabase->AddColour("SlateBlue", wxColour("#6A5ACD"));
wxTheColourDatabase->AddColour("SlateGray", wxColour("#708090"));
wxTheColourDatabase->AddColour("Snow", wxColour("#FFFAFA"));
wxTheColourDatabase->AddColour("SpringGreen", wxColour("#00FF7F"));
wxTheColourDatabase->AddColour("SteelBlue", wxColour("#4682B4"));
wxTheColourDatabase->AddColour("Tan", wxColour("#D2B48C"));
wxTheColourDatabase->AddColour("Teal", wxColour("#008080"));
wxTheColourDatabase->AddColour("Thistle", wxColour("#D8BFD8"));
wxTheColourDatabase->AddColour("Tomato", wxColour("#FF6347"));
wxTheColourDatabase->AddColour("Turquoise", wxColour("#40E0D0"));
wxTheColourDatabase->AddColour("Violet", wxColour("#EE82EE"));
wxTheColourDatabase->AddColour("Wheat", wxColour("#F5DEB3"));
wxTheColourDatabase->AddColour("White", wxColour("#FFFFFF"));
wxTheColourDatabase->AddColour("WhiteSmoke", wxColour("#F5F5F5"));
wxTheColourDatabase->AddColour("Yellow", wxColour("#FFFF00"));
wxTheColourDatabase->AddColour("YellowGreen", wxColour("#9ACD32"));
}
// vars
wxFrame * m_frame; // the main application frame
wxAuiManager m_aui; // AUI manager instance
UiMenuHandler m_menuHandler; // app menu handler / manager
UiToolbarHandler m_tbarHandler; // app toolbar handler
IArtProvider * m_artProvider; // The art provider object
wxAuiNotebook * m_docArea; // Document area
std::unordered_map<int, Document *> m_docMap; // document map
// route events
DECLARE_EVENT_TABLE();
};
// event dispatching
BEGIN_EVENT_TABLE(TheUiManager, wxEvtHandler)
EVT_CLOSE ( TheUiManager::OnClose)
EVT_MENU (wxID_ANY, TheUiManager::OnCommandEvent)
EVT_MENU (ID_DecoupleTab, TheUiManager::OnDecouple)
EVT_AUINOTEBOOK_TAB_RIGHT_UP( wxID_ANY, TheUiManager::OnTabContextMenu)
END_EVENT_TABLE()
// Implement Manager
IMPLEMENT_MANAGER(UiManager, TheUiManager)
<file_sep>/fbide-wx/sdk/src/Document.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/Document.h"
using namespace fb;
void CDocumentBase::SendDocEvent (int event)
{
DocEvtMap::iterator iter = evt.find(event);
if (iter != evt.end())
iter->second(this, event);
}
void CDocumentBase::SetDocTitle (const wxString & name)
{
if (!name.Len())
{
m_title = _T("Untitled {id}"); //CManager::Get()->GetLang()[_T("document.unnamed")];
wxString id;
id.Printf(_T("%d"), GetDocId());
m_title.Replace(_T("{id}"), id);
}
else
{
m_title = name;
}
SendDocEvent(DocEvent::RENAME);
}
<file_sep>/fbide-vs/Sdk/Ui/DocFrame.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "../Manager.h"
#include "../UiManager.h"
#include "../Document.h"
#include "DocFrame.h"
using namespace fbi;
// events
BEGIN_EVENT_TABLE(DocFrame, wxFrame)
END_EVENT_TABLE()
// create new document
DocFrame::DocFrame(Document * document) : m_document(document)
{
// sanity
wxASSERT(m_document != nullptr);
wxASSERT(m_document->GetDocWindow() != nullptr);
// create the frame
wxFrame::Create(
GET_FRAME(), wxID_ANY, m_document->GetDocTitle(),
wxDefaultPosition, wxDefaultSize,
wxDEFAULT_FRAME_STYLE
);
// use aui to manage the layout
m_aui.SetFlags(wxAUI_MGR_LIVE_RESIZE | wxAUI_MGR_DEFAULT);
m_aui.SetManagedWindow(this);
// bring the document over
wxWindow * docWnd = m_document->GetDocWindow();
docWnd->Reparent(this);
// Add it
m_aui.AddPane (
docWnd,
wxAuiPaneInfo()
.Name("fbDocMgrDocument")
.CenterPane()
.PaneBorder(false)
);
// initalize the toolbar
m_tbarHandler.Init(&m_aui, false);
// load layout
auto & reg = GET_REG();
wxString file = reg["path.ide.data"].AsString() + "docframe.xml";
// the xml object
wxXmlDocument xml;
// Normalize the file path
wxFileName f(file);
f.Normalize();
wxString layoutFile = f.GetFullPath();
// Check for errors ...
if (!f.FileExists() || !xml.Load(layoutFile))
{
wxLogError(_T("Could not load layout file \"%s\""), layoutFile.c_str());
return;
}
if (!xml.IsOk() || xml.GetRoot()->GetName() != _T("fbide"))
{
wxLogError(_T("Malformed layout file \"%s\""), layoutFile.c_str());
return;
}
if (xml.GetRoot()->GetAttribute("type") != "ui-layout")
{
wxLogError(_T("Type is not 'ui-layou' in \"%s\""), layoutFile.c_str());
return;
}
// load layout
wxXmlNode * child = xml.GetRoot()->GetChildren();
for ( ; child; child = child->GetNext())
{
if (child->GetType() == wxXML_COMMENT_NODE) continue;
if (child->GetName() == "menus")
{
wxMessageBox("menus not implemented");
// m_menuHandler.Load(child->GetChildren());
}
else if (child->GetName() == "toolbars")
{
m_tbarHandler.Load(child->GetChildren());
}
else
{
wxLogWarning("Invalid entry <%s> in '%s'", child->GetName(), layoutFile.c_str());
}
}
// Refresh ui
m_aui.Update();
}
/**
* Dock back
*/
void DocFrame::OnDockBack (wxCommandEvent & event)
{
}
<file_sep>/fbide-wx/Plugins/ClassicTheme/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/PluginArtProvider.h"
#include "sdk/UiManager.h"
#include "sdk/ArtProvider.h"
namespace XPM {
#include "xpm/newsrc.xpm"
#include "xpm/opnproj.xpm"
#include "xpm/save.xpm"
#include "xpm/close.xpm"
#include "xpm/undo.xpm"
#include "xpm/redo.xpm"
#include "xpm/cut.xpm"
#include "xpm/copy.xpm"
#include "xpm/paste.xpm"
#include "xpm/search.xpm"
#include "xpm/srchrep.xpm"
#include "xpm/xpm_goto.xpm"
#include "xpm/about.xpm"
#include "xpm/empty.xpm"
}
using namespace fb;
/**
* Gfx provider
*/
class ClassicThemeProvider : public IArtProvider
{
public :
// Create plugin instance
ClassicThemeProvider ()
{
// we use only xpm's so...
m_bitmaps[_T("new")] = new wxBitmap (XPM::newsrc);
m_bitmaps[_T("open")] = new wxBitmap (XPM::opnproj);
m_bitmaps[_T("save")] = new wxBitmap (XPM::save);
m_bitmaps[_T("quit")] = new wxBitmap (XPM::close);
m_bitmaps[_T("undo")] = new wxBitmap (XPM::undo);
m_bitmaps[_T("redo")] = new wxBitmap (XPM::redo);
m_bitmaps[_T("cut")] = new wxBitmap (XPM::cut);
m_bitmaps[_T("copy")] = new wxBitmap (XPM::copy);
m_bitmaps[_T("paste")] = new wxBitmap (XPM::paste);
m_bitmaps[_T("find")] = new wxBitmap (XPM::search);
m_bitmaps[_T("replace")] = new wxBitmap (XPM::srchrep);
m_bitmaps[_T("goto")] = new wxBitmap (XPM::xpm_goto);
m_bitmaps[_T("about")] = new wxBitmap (XPM::about);
m_bitmaps[_T("icon.empty")]= new wxBitmap (XPM::empty);
for (CBitmapMap::iterator iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
iter->second->SetMask(new wxMask(*iter->second, wxColour(191, 191, 191)));
}
}
// clean up
virtual ~ClassicThemeProvider ()
{
for (CBitmapMap::iterator iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
delete iter->second;
}
}
virtual wxBitmap GetIcon (const wxString & name, int size = IArtProvider::SMALL)
{
CBitmapMap::iterator iter = m_bitmaps.find(name);
if (iter != m_bitmaps.end())
{
return *iter->second;
}
return *m_bitmaps[_T("icon.empty")];
}
virtual wxSize GetIconSize (int type)
{
return wxSize(16, 16);
}
private :
WX_DECLARE_STRING_HASH_MAP(wxBitmap *, CBitmapMap);
CBitmapMap m_bitmaps;
};
// Register plugin
CPluginArtProvider<ClassicThemeProvider> plugin(_T("ClassicTheme"));
<file_sep>/fbide-wx/makefile
# Makefile for FBIDE
# we need to know if we're building for linux or win32
ifeq (,$(findstring $(TARGET),linux win32))
$(error need TARGET=linux | win32)
endif
# also should we build release or debug version
ifeq (,$(findstring $(BUILD),debug release))
$(error need BUILD=debug | release)
endif
# set the name of the compiler depending on platform
ifeq ($(TARGET),win32)
CC := gcc.exe
RM := del.exe
else
CC := gcc
RM := rm -f
endif
#compile flags for all modes go here
CPPFLAGS := -Wall -Winvalid-pch -DUSE_PCH -DwxUSE_UNICODE -DWX_PRECOMP -DwxUSE_AUI
ifeq ($(TARGET),win32)
CPPFLAGS += -shared-libgcc -lstdc++_s -D_DLL
endif
#flags specific to building App/ go here
APPCPPFLAGS = -IApp/include -IApp -Isdk/include -include App/wx_pch.h
#flags specific to building the sdk library go here
SDKCPPFLAGS = -Isdk/include -Isdk -include wx_pch.h -fPIC
# debug flags
ifeq ($(BUILD),debug)
CPPFLAGS += -g
endif
# release flags
ifeq ($(BUILD),release)
CPPFLAGS += -O2
endif
# set WX Widgets flags
# on linux and most likely macos wx-config is used for the proper flags
# we'll have to program in the appropriate windows flags at some point
ifeq ($(TARGET),linux)
WXFLAGS := wx-config --cppflags
else
#windows specific wx flags go here
WXFLAGS := wx flags
endif
#these flags get added if we're building the debug version
ifeq ($(BUILD),debug)
ifeq ($(TARGET),linux)
#first linux is easy, wx-config has a option for us to use
WXFLAGS += --debug
else
#windows flags should go here
WXFLAGS += wx flags
endif
endif
APPSRCPATH := App/src
APPHDRSPATH := App/include
SDKSRCPATH := sdk/src
SDKHDRSPATH := sdk/include
APPSRCS := $(wildcard $(APPSRCPATH)/*.cpp)
SDKSRCS := $(wildcard $(SDKSRCPATH)/*.cpp)
APPHDRS := $(wildcard $(APPHDRSPATH)/*.h)
SDKHDRS := $(wildcard $(SDKHDRSPATH)/*.h)
ifndef APPOBJPATH
ifeq ($(BUILD),debug)
APPOBJPATH = App/obj/Debug
else
APPOBJPATH = App/obj/Release
endif
endif
ifndef SDKOBJPATH
ifeq ($(BUILD),debug)
SDKOBJPATH = sdk/obj/Debug
else
SDKOBJPATH = sdk/obj/Release
endif
endif
APPOBJS := $(patsubst $(APPSRCPATH)/%.cpp,$(APPOBJPATH)/%.o,$(APPSRCS))
SDKOBJS := $(patsubst $(SDKSRCPATH)/%.cpp,$(SDKOBJPATH)/%.o,$(SDKSRCS))
ifeq ($(TARGET),win32)
FBIDE := fbide.exe
FBIDEDLL := libfbide.dll
else
FBIDE := fbide
FBIDEDLL := libfbide.so
endif
ifeq ($(BUILD),debug)
OUTDIR := bin/Debug
else
OUTDIR := bin/Release
endif
.SUFFIXES:
.SUFFIXES: .cpp
VPATH = .
ifneq ($(TARGET),win32)
#these tell how to build the object files on linux
$(APPOBJPATH)/%.o : $(APPSRCPATH)/%.cpp $(APPHDRS)
@echo Building $@
@$(CC) $(CPPFLAGS) $(APPCPPFLAGS) `$(WXFLAGS)` -c $< -o $@
$(SDKOBJPATH)/%.o : $(SDKSRCPATH)/%.cpp $(SDKHDRS)
@echo Building $@
@$(CC) $(CPPFLAGS) $(SDKCPPFLAGS) `$(WXFLAGS)` -c $< -o $@
else
#these ones are for windows
$(APPOBJPATH)/%.o : $(APPSRCPATH)/%.cpp $(APPHDRS)
@$(CC) $(CPPFLAGS) $(WXFLAGS) -c $< -o $@
$(SDKOBJPATH)/%.o : $(SDKSRCPATH)/%.cpp $(SDKHDRS)
@$(CC) $(CPPFLAGS) $(SDKCPPFLAGS) $(WXFLAGS) -c $< -o $@
endif
#############
all: $(FBIDE) $(FBIDEDLL)
ifneq ($(TARGET),win32)
#this is the final linking stage of building FBIde on linux
$(FBIDE): $(FBIDEDLL) $(APPOBJS)
@echo Linking $@
@$(CC) $(CPPFLAGS) $(APPCPPFLAGS) `$(WXFLAGS) --libs` -L$(OUTDIR) -lfbide $(APPOBJS) -o $(OUTDIR)/$(FBIDE)
@echo FBIde compiled into: $(OUTDIR)/$(FBIDE)
else
#this is the final linking stage of building FBIde on windows
# needs to have wx libs added to linker list
$(FBIDE): $(FBIDEDLL) $(APPOBJS)
@$(CC) $(CPPFLAGS) $(APPCPPFLAGS) $(WXFLAGS) $(APPOBJS) -o $(OUTDIR)/$(FBIDE)
endif
ifneq ($(TARGET),win32)
#this is the final linking stage of building the FBIde SDK on linux
$(FBIDEDLL): $(SDKOBJS)
@echo Linking $@
@$(CC) -shared $(CPPFLAGS) $(SDKCPPFLAGS) `$(WXFLAGS) --libs` -o $(OUTDIR)/$(FBIDEDLL) $(SDKOBJS)
else
#this is the final linking stage of building the FBIde SDK on windows
$(FBIDEDLL): $(SDKOBJS)
@$(CC) $(CPPFLAGS) $(SDKCPPFLAGS) $(SDKOBJS) -o $(OUTDIR)/$(FBIDEDLL)
endif
.PHONY : clean
clean :
-$(RM) $(APPOBJPATH)/*.o
-$(RM) $(SDKOBJPATH)/*.o
-$(RM) $(OUTDIR)/$(FBIDE)
-$(RM) $(OUTDIR)/$(FBIDEDLL)
<file_sep>/fbide-wx/App/src/App.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "../wx_pch.h"
#include <wx/clipbrd.h>
#include <wx/dir.h>
//#include <wx/windowlist.h>
#include "App.h"
#include "Frame.h"
#include "sdk/Manager.h"
#include "sdk/UiManager.h"
#include "sdk/DocManager.h"
#include "sdk/TypeManager.h"
#include "sdk/ArtProvider.h"
#include "sdk/PluginManager.h"
#include "sdk/StyleInfo.h"
#include "sdk/Document.h"
using namespace fb;
/**
* Register Application class with WX
* and trigger loading
*/
DECLARE_APP(CApp);
IMPLEMENT_APP(CApp);
#include "sdk/Registry.h"
/**
* This is application entry point
*/
bool CApp::OnInit()
{
FBIDE_TRY
{
// create application window
wxFrame * frame = new CFrame(0L, _T("FBIde"));
// Load the base manager and set frame
CManager & mgr = *CManager::Get();
mgr.SetFrame (frame);
// load sub managers
CUiManager & ui = *mgr.GetUiManager();
// registry
CRegistry & reg = mgr.GetReg();
// Set base configuration
reg["dir.base"] = ::wxPathOnly(argv[0]) + _T("/");
reg["dir.data"] = reg["dir.base"].AsString() + _T("ide/");
reg["dir.plugins"] = reg["dir.data"].AsString() + _T("plugins/");
reg["file.config"] = reg["dir.data"].AsString() + _T("config.ini");
// Load config file
mgr.LoadConfig(reg["file.config"].AsString());
// Load colour pallettes
mgr.SetupPalette(_T(""));
// Load language file
mgr.LoadLang(reg["dir.data"].AsString() + reg["file.lang"].AsString());
// Each component will have to register it's
// own ID's to global id map and give each
// unique name. ID's are used also for mapping
// images
mgr.RegisterId(_T("new"), wxID_NEW);
mgr.RegisterId(_T("open"), wxID_OPEN);
mgr.RegisterId(_T("save"), wxID_SAVE);
mgr.RegisterId(_T("quit"), wxID_EXIT);
mgr.RegisterId(_T("undo"), wxID_UNDO);
mgr.RegisterId(_T("redo"), wxID_REDO);
mgr.RegisterId(_T("cut"), wxID_CUT);
mgr.RegisterId(_T("copy"), wxID_COPY);
mgr.RegisterId(_T("paste"), wxID_PASTE);
mgr.RegisterId(_T("find"), wxID_FIND);
mgr.RegisterId(_T("replace"), wxID_REPLACE);
mgr.RegisterId(_T("goto"), wxNewId());
mgr.RegisterId(_T("about"), wxID_ABOUT);
// mgr.RegisterId(_T("log"), wxNewId());
// Initalize docManager. Must be called after wxFrame has been assigned to uiManager
GET_DOCMGR();
// Load plugin manager
CPluginManager * pm = GET_PLUGINMGR();
// experimental plugins
pm->LoadPlugin(_T("FBIdePlugin"));
// Load LogPlugin
pm->LoadPlugin(_T("LogPlugin"));
//
// pm->LoadPlugin(_T("WebBrowser"));
// Load Skin plugin
pm->LoadPlugin(reg["ui.plugin.theme"].AsString("TangoTheme"));
// Load styles
mgr.SetStyleParser(
_T("default"),
new CStyleParser(reg["dir.data"].AsString() + reg["file.ui.style"].AsString())
);
// Load UI
// ui.SetArtProvider(new CArtProvider());
ui.LoadLayout(reg["dir.data"].AsString() + reg["file.ui.layout"].AsString());
// Load up projects
//pm->LoadPlugin(_T("Projects"));
// startup is OK, show window and return
ui.Load();
// open files in sample/ directory
/*
wxDir dir (reg["dir.base"].AsString() + _T("samples/"));
if (dir.IsOpened() && dir.HasFiles(_T("*.bas")))
{
wxArrayString files;
dir.GetAllFiles(dir.GetName(), &files, _T("*.bas"));
GET_DOCMGR()->Open(files);
}
*/
return true;
}
FBIDE_CATCH();
return false;
}
/**
* Make Log window visible
*/
/*
void CApp::ShowLog (wxCommandEvent &)
{
if (wxLogWindow * log = dynamic_cast<wxLogWindow *>(wxLog::GetActiveTarget()))
{
log->Show();
}
}
*/
/**
* Close down the program and do final cleanup
*/
int CApp::OnExit ()
{
FBIDE_TRY
{
// Save the config
CManager & mgr = *CManager::Get();
CRegistry & reg = mgr.GetReg();
wxString file = reg[_T("file.config")].AsString();
reg.erase(_T("dir.base"));
reg.erase(_T("dir.data"));
reg.erase(_T("dir.plugins"));
reg.erase(_T("file.config"));
mgr.SaveConfig(file);
// Release the manager. It will
// internally release all attached
// sub managers
CManager::Free();
// don't let the clipboard data be emptied!
wxTheClipboard->Flush();
// return native OnExit...
return wxApp::OnExit();
}
FBIDE_CATCH();
return EXIT_FAILURE;
}
/**
* Run the system and catch any thrown exceptions from the application
* during it's lifetime
*/
int CApp::OnRun ()
{
FBIDE_TRY
{
return wxApp::OnRun();
}
FBIDE_CATCH();
return EXIT_FAILURE;
}
<file_sep>/fbide-vs/Sdk/Ui/DocFrame.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
#include "ToolbarHandler.h"
namespace fbi
{
// forward reference
class Document;
/**
* Frame into what documents are decoupled
*/
class SDK_DLL DocFrame : public wxFrame
{
public:
// Create new docframe from a Document object
DocFrame(Document * doc);
// dock the frame window back
void OnDockBack (wxCommandEvent & event);
private:
// document managed
Document * m_document;
// aui manager
wxAuiManager m_aui;
// manage toolbars
UiToolbarHandler m_tbarHandler;
// handle events
DECLARE_EVENT_TABLE()
};
}
<file_sep>/fbide-wx/sdk/src/UiManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/Singleton.h"
#include "sdk/UiManager.h"
#include "sdk/UiToolDescriptor.h"
#include "sdk/ArtProvider.h"
#include "sdk/Document.h"
#include "sdk/DocManager.h"
#define AUI_USE_PERSPECTIVES
using namespace fb;
/**
* Ui is private class and implements the CUiManager class
*/
class Ui : public CUiManager, wxEvtHandler, public CSingleton<Ui>
{
friend class CSingleton<Ui>;
friend class CUiManager;
/**
* This small class is used to fix
* a) wxToolBarToolBase::Toggle and wxMenuToolBase::Check are not compatable
* b) wxToolBarToolBase::Toggle does not refresh the UI
* In order to use delegate based fast and nice event dispatching
* this buffer class is required to solve the problem
*
* doesn't seem to work on linux...
*/
struct UiToolbarItemCheckFixer
{
wxAuiToolBar * m_tbar;
wxAuiToolBarItem * m_tool;
void Check (bool check)
{
m_tbar->ToggleTool(m_tool->GetId(), check);
m_tbar->Realize();
}
UiToolbarItemCheckFixer (wxAuiToolBar * tbar, wxAuiToolBarItem * tool) : m_tbar(tbar), m_tool(tool)
{
Ui::GetInstance()->m_toolbarCheckFixs.push_back(this);
}
};
typedef std::map<wxString, CUiToolDescriptor *> UiToolMap;
typedef std::map<wxString, wxMenu *> MenuMap;
typedef std::map<wxString, wxAuiToolBar *> ToolBarMap;
typedef std::vector<UiToolbarItemCheckFixer *> ToolCheckFixVector;
typedef std::map<int, void *> IntVoidMap;
typedef std::map<int, wxAuiToolBarItem*> ToolBarItemsMap;
typedef std::map<int, wxString> IntStringMap;
typedef std::map<wxString, wxAuiNotebook*> NotebookMap;
IntStringMap m_idNameMap;
ToolBarItemsMap m_toolBarItems;
IntVoidMap m_AuiPaneMenuBindMap;
ToolCheckFixVector m_toolbarCheckFixs;
UiToolMap m_uiToolDescMap;
MenuMap m_menuMap;
ToolBarMap m_toolBarMap;
wxAuiManager * m_aui;
IArtProvider * m_artProvider;
wxMenuBar * m_menuBar;
wxMenu * m_toolbarsMenu;
wxStatusBar * m_statusBar;
wxAuiNotebook * m_docArea;
bool m_showToolbars;
NotebookMap m_paneNotebooks;
// Load the toolbars from XML
void LoadToolbars (wxXmlNode * xml);
// new tool to the toolbar
void AddToolBarItem (const wxString & name, wxAuiToolBar * toolbar);
// Load the menus from XML
void LoadMenus (wxXmlNode * xml, wxMenu * parent);
// Create menu entry
void AddMenuItem (const wxString & name, wxMenu * parent);
// Menu Fullscreen selected
void OnFullScreen (wxCommandEvent & event);
// When document tab becomes active
void OnDocumentChanged (wxAuiNotebookEvent & event);
// When document is closed
void OnDocumentClosed (wxAuiNotebookEvent & event);
// About to close document
void OnDocumentClose (wxAuiNotebookEvent & event);
// Aui pane close (toolbar or some panel)
void OnAuiPaneClose (wxAuiManagerEvent & event);
// Toolbar show/hide menu selected
void OnAuiPaneShowHide (wxCommandEvent & event);
// Toggle toolbars on/off
void OnShowToolbars (wxCommandEvent & event);
// Set Application frame title
void SetFrameTitle ();
// Document events
void OnDocumentEvent (CDocumentBase * doc, int evt);
// Are toolbars visible?
bool IsToolbarVisible () { return m_showToolbars; }
// Get number of visible toolbars
int GetVisibleToolbarCount ();
// Find toolbar name
wxString GetToolBarName (wxAuiToolBar * tbar);
// Create UI
Ui ();
// Final clean up
~Ui ();
public :
// Register new tool descriptor
void AddToolDescriptor (const wxString & name, CUiToolDescriptor * toolDesc);
// get doucment "parent" window
wxWindow * GetDocWindow ();
// load layout specified by xml
void LoadLayout (const wxString & file);
// Clean up ui before application close
void Unload ();
// Get menu with given name
wxMenu * GetMenu (const wxString & name);
// Add new menu into system
void AddMenu (const wxString & name, wxMenu * menu, bool show = false);
// Get toolbar by name
wxAuiToolBar * GetToolBar (const wxString & name);
// add new toolbar
void AddToolBar (const wxString & name, wxAuiToolBar * toolbar, bool show = false);
// Add document into Document view
void AddDocument (CDocumentBase * doc, bool show);
// Get Active document
CDocumentBase * GetActiveDocument ();
// Remove document
void RemoveDocument (CDocumentBase * doc);
// Set art provider
void SetArtProvider (IArtProvider * provider);
// Get art provider
IArtProvider * GetArtProvider ();
// Add pane
bool AddPane (const wxString & id, wxWindow * wnd, const wxString & group);
// Get parent for the pane area
wxWindow * GetPaneWindow (const wxString & group);
// Get pane by id
wxWindow * GetPane (const wxString & id);
// remove pane
void RemovePane (const wxString & id);
// Load the UI (finalize loading process)
void Load ();
DECLARE_EVENT_TABLE()
};
// SOME IDs
const int ID_FULLSCREEN = ::wxNewId ();
const int ID_DOC_AREA = ::wxNewId ();
const int ID_SHOW_TOOLBARS = ::wxNewId ();
// Event table for Ui
BEGIN_EVENT_TABLE(Ui, wxEvtHandler)
EVT_AUI_PANE_CLOSE ( Ui::OnAuiPaneClose)
EVT_AUINOTEBOOK_PAGE_CHANGED(ID_DOC_AREA, Ui::OnDocumentChanged)
EVT_AUINOTEBOOK_PAGE_CLOSE (ID_DOC_AREA, Ui::OnDocumentClose)
EVT_AUINOTEBOOK_PAGE_CLOSED (ID_DOC_AREA, Ui::OnDocumentClosed)
EVT_MENU (ID_FULLSCREEN, Ui::OnFullScreen)
EVT_MENU (ID_SHOW_TOOLBARS, Ui::OnShowToolbars)
END_EVENT_TABLE()
// Constructor
Ui::Ui ()
{
// vars
CManager * mgr = GET_MGR();
wxFrame * frame = mgr->GetFrame();
// Register UI specific IDs
mgr->RegisterId(_T("fullscreen"), ID_FULLSCREEN);
AddToolDescriptor (
_T("fullscreen"),
CUiToolDescriptor::CreateToggleTool (MakeDelegate(frame, &wxFrame::IsFullScreen))
);
m_showToolbars = true;
mgr->RegisterId(_T("toolbars"), ID_SHOW_TOOLBARS);
AddToolDescriptor (
_T("toolbars"),
CUiToolDescriptor::CreateToggleTool (MakeDelegate(this, &Ui::IsToolbarVisible))
);
// set event handler
frame->PushEventHandler (this);
// Create Ui stuff
m_aui = new wxAuiManager (
frame,
wxAUI_MGR_LIVE_RESIZE | wxAUI_MGR_DEFAULT
);
m_menuBar = new wxMenuBar ();
m_statusBar = new wxStatusBar (frame);
// Assign status and menu bar to the frame
frame->SetStatusBar(m_statusBar);
frame->SetMenuBar(m_menuBar);
// Toolbars menu
m_toolbarsMenu = new wxMenu ();
AddMenu(_T("group.toolbars"), m_toolbarsMenu);
int tabStyles = wxAUI_NB_TAB_MOVE | wxAUI_NB_SCROLL_BUTTONS |
wxAUI_NB_WINDOWLIST_BUTTON | wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT;
// Create document area
m_docArea = new wxAuiNotebook (
frame,
ID_DOC_AREA,
wxDefaultPosition, wxDefaultSize,
tabStyles | wxAUI_NB_CLOSE_BUTTON | wxAUI_NB_CLOSE_ON_ACTIVE_TAB
);
m_aui->AddPane (
m_docArea,
wxAuiPaneInfo()
.Name(_T("fbUiMgrDocArea"))
.CenterPane()
.PaneBorder(false)
);
// management panes
wxAuiNotebook * nb;
nb = new wxAuiNotebook (
frame,
-1,
wxDefaultPosition, wxSize(150, -1),
tabStyles
);
m_aui->AddPane (
nb,
wxAuiPaneInfo()
.Name(_T("fbUiToolsArea"))
.Left()
.PaneBorder(false)
.Hide()
);
m_paneNotebooks[_T("tools")] = nb;
// log panes
nb = new wxAuiNotebook (
frame,
-1,
wxDefaultPosition, wxDefaultSize,
tabStyles
);
m_aui->AddPane (
nb,
wxAuiPaneInfo()
.Name(_T("fbUiLogsArea"))
.Bottom()
.CaptionVisible(false)
.PaneBorder(false)
.MinSize(100, 50)
.BestSize(200, 300)
.Hide()
);
m_paneNotebooks[_T("logs")] = nb;
// Refresh title
SetFrameTitle ();
}
// Final clean up
Ui::~Ui ()
{
for (UiToolMap::iterator iter = m_uiToolDescMap.begin(); iter != m_uiToolDescMap.end(); iter++)
{
delete iter->second;
}
for ( ToolCheckFixVector::iterator iter = m_toolbarCheckFixs.begin();
iter != m_toolbarCheckFixs.end();)
{
delete *iter;
iter = m_toolbarCheckFixs.erase(iter);
}
// GET_MGR()->GetFrame()->SetNextHandler(NULL);
//
}
/**
* Toggle fullscreen
*/
void Ui::OnFullScreen (wxCommandEvent & event)
{
int style = wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION;
GET_MGR()->GetFrame()->ShowFullScreen(event.IsChecked(), style);
wxMessageBox(event.IsChecked() ? _T("checked") : _T("not"));
// Notify connected items
CUiToolDescriptor * toolDesc = m_uiToolDescMap[_T("fullscreen")];
if (toolDesc) toolDesc->Notify(event.IsChecked());
}
/**
* Show hide all toolbars
*/
void Ui::OnShowToolbars (wxCommandEvent & event)
{
m_showToolbars = event.IsChecked();
for (ToolBarMap::iterator toolbars = m_toolBarMap.begin();
toolbars != m_toolBarMap.end();
toolbars++)
{
wxAuiToolBar * tbar = toolbars->second;
wxAuiPaneInfo & pane = m_aui->GetPane(tbar);
if (m_showToolbars) pane.Show();
else pane.Hide();
wxMenuItem * item = (wxMenuItem *)m_AuiPaneMenuBindMap[tbar->GetId()];
if (item) item->Check(m_showToolbars);
wxString name = _T("toolbar.") + GetToolBarName(tbar);
CUiToolDescriptor * tool = m_uiToolDescMap[name];
if (tool)
{
tool->Notify(m_showToolbars);
}
}
CUiToolDescriptor * tool = m_uiToolDescMap[_T("toolbars")];
if (tool)
{
tool->Notify(m_showToolbars);
}
m_aui->Update();
}
/**
* Get number of toolbars visible
*/
int Ui::GetVisibleToolbarCount ()
{
//IsShown
int count = 0;
ToolBarMap::iterator iter = m_toolBarMap.begin();
for ( ; iter != m_toolBarMap.end(); iter++ )
{
wxAuiToolBar * tbar = iter->second;
if (m_aui->GetPane(tbar).IsShown()) count++;
}
return count;
}
/**
* New tab is active
*/
void Ui::OnDocumentChanged (wxAuiNotebookEvent & event)
{
wxWindow * wnd = m_docArea->GetPage(event.GetSelection());
CDocumentBase * doc = GET_DOCMGR()->FindDocument(wnd);
doc->SendDocEvent(DocEvent::FOCUS);
SetFrameTitle();
}
/**
* Document event
*/
void Ui::OnDocumentEvent (CDocumentBase * doc, int evt)
{
if (evt == DocEvent::RENAME)
{
wxWindow * win = doc->GetDocWindow();
int index = m_docArea->GetPageIndex(win);
if (index == wxNOT_FOUND) return;
m_docArea->SetPageText(index, doc->GetDocTitle());
if (index == m_docArea->GetSelection()) SetFrameTitle();
}
}
/**
* Document closed
*/
void Ui::OnDocumentClosed (wxAuiNotebookEvent & event)
{
if (m_docArea->GetPageCount() == 0) SetFrameTitle();
}
/**
* Close document ?
*/
void Ui::OnDocumentClose (wxAuiNotebookEvent & event)
{
// wxMessageBox(_T("About to close..."));
// event.Skip(true);
}
/**
* On aui pane close (toolbar or some view)
*/
void Ui::OnAuiPaneClose (wxAuiManagerEvent & event)
{
wxAuiPaneInfo * pane = event.GetPane();
if (pane->IsToolbar())
{
int id = pane->window->GetId();
wxMenuItem * item = reinterpret_cast<wxMenuItem *>(m_AuiPaneMenuBindMap[id]);
if (!item) return;
item->Check(false);
if (!(GetVisibleToolbarCount()-1))
{
CUiToolDescriptor * tool = m_uiToolDescMap[_T("toolbars")];
if (tool) tool->Notify(false);
}
wxString name = _T("toolbar.") + GetToolBarName(dynamic_cast<wxAuiToolBar *>(pane->window));
CUiToolDescriptor * tool = m_uiToolDescMap[name];
if (tool)
{
tool->Notify(false);
}
}
}
/**
* Show or Hide the toolbar
*/
void Ui::OnAuiPaneShowHide (wxCommandEvent & event)
{
wxAuiToolBar * toolbar = reinterpret_cast<wxAuiToolBar *>(m_AuiPaneMenuBindMap[event.GetId()]);
if (toolbar)
{
bool show = event.IsChecked();
m_aui->GetPane(toolbar).Show(show);
m_aui->Update();
if (show)
{
if (!m_showToolbars)
{
CUiToolDescriptor * tool = m_uiToolDescMap[_T("toolbars")];
if (tool) tool->Notify(true);
}
}
else if (!GetVisibleToolbarCount())
{
CUiToolDescriptor * tool = m_uiToolDescMap[_T("toolbars")];
if (tool) tool->Notify(false);
}
wxString name = _T("toolbar.") + GetToolBarName(toolbar);
CUiToolDescriptor * tool = m_uiToolDescMap[name];
if (tool)
{
tool->Notify(show);
}
}
}
/**
* Register new Ui tool descriptor
*/
void Ui::AddToolDescriptor (const wxString & name, CUiToolDescriptor * toolDesc)
{
if (m_uiToolDescMap[name] != NULL)
{
wxLogError(_T("Tool descriptor for id '%s' already exists"), name.c_str());
return;
}
m_uiToolDescMap[name] = toolDesc;
}
void Ui::SetFrameTitle ()
{
wxString title(_T("FBIde"));
if (m_docArea->GetPageCount())
{
title << _T(" - ") << m_docArea->GetPageText(m_docArea->GetSelection());
}
GET_MGR()->GetFrame()->SetTitle(title);
}
// Get document parent window (tab area)
wxWindow * Ui::GetDocWindow ()
{
return m_docArea;
}
// Add document into Document view
void Ui::AddDocument (CDocumentBase * doc, bool show)
{
if (doc->GetDocType() != DOCUMENT_MANAGED)
throw EXCEPTION(_T("Invalid document type"));
wxWindow * wnd = dynamic_cast<wxWindow *>(doc);
wxASSERT(wnd != NULL);
m_docArea->AddPage (wnd, doc->GetDocTitle(), show);
doc->evt[DocEvent::RENAME] += MakeDelegate(this, &Ui::OnDocumentEvent);
}
// get currently active document
CDocumentBase * Ui::GetActiveDocument ()
{
if (!m_docArea->GetPageCount()) return NULL;
wxWindow * wnd = m_docArea->GetPage(m_docArea->GetSelection());
return dynamic_cast<CDocumentBase*>(wnd);
}
// Remove document
void Ui::RemoveDocument (CDocumentBase * doc)
{
if (doc->GetDocType() != DOCUMENT_MANAGED) return;
wxWindow * wnd = dynamic_cast<wxWindow *>(doc);
wxASSERT(wnd != NULL);
int page = m_docArea->GetPageIndex(wnd);
if (page == wxNOT_FOUND) return;
// unregister event handler
doc->evt[DocEvent::RENAME] -= MakeDelegate(this, &Ui::OnDocumentEvent);
m_docArea->RemovePage (page);
}
// load layout specified by xml
void Ui::LoadLayout (const wxString & file)
{
// the xml object
wxXmlDocument xml;
// Normalize the file path
wxFileName f(file);
f.Normalize();
wxString layoutFile = f.GetFullPath();
// Check for errors ...
if (!f.FileExists() || !xml.Load(layoutFile))
{
wxLogError(_T("Could not load layout file \"%s\""), layoutFile.c_str());
return;
}
if (!xml.IsOk() || xml.GetRoot()->GetName() != _T("fbide"))
{
wxLogError(_T("Malformed layout file \"%s\""), layoutFile.c_str());
return;
}
// load layout
wxXmlNode * child = xml.GetRoot()->GetChildren();
for ( ; child; child = child->GetNext())
{
if (child->GetName() == _T("menus"))
{
LoadMenus(child->GetChildren(), 0L);
}
else if (child->GetName() == _T("toolbars"))
{
LoadToolbars(child->GetChildren());
}
}
}
// Load the toolbars from XML
void Ui::LoadToolbars (wxXmlNode * xml)
{
// vars
CManager * mgr = GET_MGR();
wxString toolbarId;
wxString itemId;
int style = m_artProvider == NULL
? wxAUI_TB_TEXT | wxAUI_TB_GRIPPER | wxAUI_TB_HORZ_LAYOUT // wxTB_FLAT | wxTB_NODIVIDER | wxTB_NOICONS | wxTB_TEXT
: wxAUI_TB_GRIPPER | wxAUI_TB_HORZ_LAYOUT; // wxTB_FLAT | wxTB_NODIVIDER;
wxXmlNode * child;
// iterate through xml and add entries
for ( ; xml; xml = xml->GetNext())
{
if (xml->GetName() != _T("toolbar")) continue;
if (!xml->GetPropVal(_T("id"), &toolbarId)) continue;
bool addTb = false;
bool show = xml->GetPropVal(_T("show"), _T("yes")) == _T("yes");
wxAuiToolBar * tbar = GetToolBar(toolbarId);
if (tbar == NULL)
{
tbar = new wxAuiToolBar (
mgr->GetFrame(), wxID_ANY,
wxDefaultPosition, wxDefaultSize,
style
);
if (m_artProvider)
{
tbar->SetToolBitmapSize(m_artProvider->GetIconSize());
}
addTb = true;
}
// iterate through children (if any) and add them to the toolbar
for (child = xml->GetChildren(); child; child = child->GetNext())
{
wxString tag = child->GetName();
// seperator
if (tag == _T("separator"))
{
tbar->AddSeparator ();
}
else if (tag == _T("item"))
{
if(!child->GetPropVal(_T("id"), &itemId)) continue;
AddToolBarItem (itemId, tbar);
}
}
// refresh the toolbar
tbar->Realize ();
if (addTb) AddToolBar (toolbarId, tbar, show);
}
}
// Get toolbar by name
wxAuiToolBar * Ui::GetToolBar (const wxString & name)
{
return m_toolBarMap[name];
}
// Get toolbar by name
wxString Ui::GetToolBarName (wxAuiToolBar * tbar)
{
ToolBarMap::iterator iter = m_toolBarMap.begin();
for ( ; iter != m_toolBarMap.end(); iter++)
{
if (iter->second == tbar) return iter->first;
}
return _T("");
}
// add new toolbar
void Ui::AddToolBar (const wxString & name, wxAuiToolBar * toolbar, bool show)
{
if (GetToolBar(name))
{
wxLogWarning(_T("Toolbar with id '%s' already exists"), name.c_str());
return;
}
m_toolBarMap[name] = toolbar;
// vars
CManager * mgr = GET_MGR();
wxString label = mgr->GetLang(_T("toolbar.") + name);
// Add menu entry for toolbar
int menuId = ::wxNewId();
wxMenuItem * item = m_toolbarsMenu->AppendCheckItem(menuId, label);
item->Check(show);
Connect(menuId, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(Ui::OnAuiPaneShowHide));
m_AuiPaneMenuBindMap[menuId] = toolbar;
m_AuiPaneMenuBindMap[toolbar->GetId()] = item;
wxString toolBarEntry = _T("toolbar.");
toolBarEntry += name;
AddToolDescriptor (
toolBarEntry,
CUiToolDescriptor::CreateToggleTool (MakeDelegate(item, &wxMenuItemBase::IsChecked))
);
mgr->RegisterId(toolBarEntry, menuId);
m_uiToolDescMap[toolBarEntry]->Connect(
CUiToolDescriptor::VoidBoolDelegate(item, &wxMenuItemBase::Check)
);
// Add to aui
m_aui->AddPane(
toolbar,
wxAuiPaneInfo().Name(name).Caption(label)
.ToolbarPane().Top().Dockable(true).Show(show)
);
}
/**
* Add an item to the toolbar
*/
void Ui::AddToolBarItem (const wxString & name, wxAuiToolBar * toolbar)
{
// vars
CManager * mgr = GET_MGR();
wxItemKind style= wxITEM_NORMAL;
bool checked = false;
int id = mgr->GetId(name);
wxString label = mgr->GetLang(name);
wxString help = mgr->GetLang(name + _T(".help"));
wxAuiToolBarItem * tool = NULL;
CUiToolDescriptor * toolDesc;
// check if is a special tool
toolDesc = m_uiToolDescMap[name];
if (toolDesc != NULL)
{
if (toolDesc->GetType() == CUiToolDescriptor::TOOL_TOGGLE)
{
checked = toolDesc->IsChecked();
style = wxITEM_CHECK;
}
}
wxBitmap bmp = m_artProvider ? m_artProvider->GetIcon(name) : wxNullBitmap;
toolbar->AddTool(id, label, bmp, help, style);
tool = toolbar->FindTool(id);
m_toolBarItems[id] = tool;
m_idNameMap[id] = name;
if (style == wxITEM_CHECK)
{
tool->SetKind(wxITEM_CHECK);
UiToolbarItemCheckFixer * t = new UiToolbarItemCheckFixer (toolbar, tool);
toolDesc->Connect (
CUiToolDescriptor::VoidBoolDelegate(t, &UiToolbarItemCheckFixer::Check)
);
toolbar->ToggleTool(tool->GetId(), checked);
}
tool->SetLongHelp(help);
toolbar->Realize();
}
/**
* Load the menus from XML
*/
void Ui::LoadMenus (wxXmlNode * xml, wxMenu * parent)
{
wxString idName;
CManager & mgr = *GET_MGR();
for ( ; xml; xml = xml->GetNext())
{
if (xml->GetName() == _T("menu"))
{
if(!xml->GetPropVal(_T("id"), &idName)) continue;
idName = _T("group.") + idName;
wxMenu * menu = GetMenu(idName);
if (menu == NULL)
{
menu = new wxMenu();
AddMenu(idName, menu, parent == 0L);
}
if (parent != 0L)
{
parent->AppendSubMenu(menu, mgr.GetLang(idName));
}
else if(m_menuBar->FindMenu(mgr.GetLang(idName)) == wxNOT_FOUND)
{
m_menuBar->Append(menu, mgr.GetLang(idName));
}
if (wxXmlNode * children = xml->GetChildren())
{
LoadMenus(children, menu);
}
}
else if (xml->GetName() == _T("item"))
{
if(parent && xml->GetPropVal(_T("id"), &idName)) AddMenuItem (idName, parent);
}
else if (xml->GetName() == _T("separator"))
{
if (parent != 0L) parent->AppendSeparator();
}
}
}
// Get menu with given name
wxMenu * Ui::GetMenu (const wxString & name)
{
return m_menuMap[name];
}
// Add new menu into system
void Ui::AddMenu (const wxString & name, wxMenu * menu, bool show)
{
if (GetMenu(name) != NULL)
{
wxLogError (_T("Menu with id '%s' already registered"), name.c_str());
return;
}
m_menuMap[name] = menu;
if (show) m_menuBar->Append(menu, GET_MGR()->GetLang(name));
}
// Add menu item
void Ui::AddMenuItem (const wxString & name, wxMenu * parent)
{
// vars
CManager * mgr = GET_MGR();
wxItemKind style= wxITEM_NORMAL;
bool checked = false;
int id = mgr->GetId(name);
wxString label = mgr->GetLang(name);
wxString help = mgr->GetLang(name + _T(".help"));
wxMenuItem * item = NULL;
CUiToolDescriptor * toolDesc;
// check if is a special tool
toolDesc = m_uiToolDescMap[name];
if (toolDesc != NULL)
{
if (toolDesc->GetType() == CUiToolDescriptor::TOOL_TOGGLE)
{
checked = toolDesc->IsChecked();
style = wxITEM_CHECK;
}
}
// Create menu item
item = new wxMenuItem (parent, id, label, help, style);
if (style == wxITEM_NORMAL)
{
if (m_artProvider) item->SetBitmap(m_artProvider->GetIcon(name));
parent->Append(item);
}
else if (style == wxITEM_CHECK)
{
parent->Append(item);
item->Check(checked);
toolDesc->Connect(
CUiToolDescriptor::VoidBoolDelegate(item, &wxMenuItemBase::Check)
);
}
}
// Load the UI (finalize loading process)
void Ui::Load ()
{
CRegistry & reg = GET_REG();
wxFrame & frame = *GET_MGR()->GetFrame();
// Load previous window size and position
frame.SetSize(
reg["ui.window.rect.x"].AsInt(wxDefaultCoord),
reg["ui.window.rect.y"].AsInt(wxDefaultCoord),
reg["ui.window.rect.width"].AsInt(300),
reg["ui.window.rect.height"].AsInt(200)
);
// Set minimum size
frame.SetMinSize(wxSize(
reg["ui.window.min.width"].AsInt(300),
reg["ui.window.min.height"].AsInt(200)
));
// load AUI perspective
#ifdef AUI_USE_PERSPECTIVES
if (m_aui != 0L)
{
m_aui->LoadPerspective(reg["ui.perspective"].AsString());
}
#endif
// update aui layout
m_aui->Update();
// show the main window
frame.Show();
}
// to be removed
void Ui::Unload ()
{
wxFrame & frame = *GET_MGR()->GetFrame();
frame.RemoveEventHandler (this);
CRegistry & reg = GET_REG();
CManager::Get()->GetDocManager()->CloseAll();
#ifdef AUI_USE_PERSPECTIVES
if (m_aui != 0L) reg["ui.perspective"] = m_aui->SavePerspective();
#endif
// save window size and position
wxRect r = frame.GetScreenRect();
reg["ui.window.rect.x"] = r.x;
reg["ui.window.rect.y"] = r.y;
reg["ui.window.rect.width"] = r.width;
reg["ui.window.rect.height"] = r.height;
}
/**
* Set art provider. Takes ownership?? maybe no... (might be a plugin class
* that directly implements the interface. Should send an event...)
*
* @todo if provider is changed then should refresh the UI
*/
void Ui::SetArtProvider (IArtProvider * provider)
{
// if setting self no reason to linger here...
if (provider == m_artProvider) return;
// vars
CManager * mgr = GET_MGR();
// check if we are killing ourselves
if (mgr->IsShuttingDown()) return;
m_artProvider = provider;
onArtProvderChange (provider);
int style = m_artProvider == NULL
? wxTB_FLAT | wxTB_NODIVIDER | wxTB_NOICONS | wxTB_TEXT
: wxTB_FLAT | wxTB_NODIVIDER;
// Update toolbars
for (ToolBarMap::iterator toolbars = m_toolBarMap.begin();
toolbars != m_toolBarMap.end();
toolbars++)
{
// get the toolbar and name
wxAuiToolBar * toolbar = toolbars->second;
wxString name = toolbars->first;
m_aui->DetachPane(toolbar);
// if we have art provider change bitmaps
if (m_artProvider)
{
toolbar->SetToolBitmapSize(m_artProvider->GetIconSize());
// iterate through items
for (ToolBarItemsMap::iterator items = m_toolBarItems.begin();
items != m_toolBarItems.end(); items++)
{
wxAuiToolBarItem * tool = items->second;
tool->SetBitmap(m_artProvider->GetIcon(m_idNameMap[items->first]));
//toolbar->SetToolNormalBitmap (items->first, m_artProvider->GetIcon(m_idNameMap[items->first]));
}
}
toolbar->SetWindowStyle(style);
toolbar->Realize();
m_aui->AddPane(
toolbar,
wxAuiPaneInfo().Name(name).Caption(mgr->GetLang(_T("toolbar.") + name))
.ToolbarPane().Top().LeftDockable(false).RightDockable(false)
.Show(true)
);
}
m_aui->Update();
}
// Get art provider
IArtProvider * Ui::GetArtProvider ()
{
return m_artProvider;
}
// Add pane
bool Ui::AddPane (const wxString & id, wxWindow * wnd, const wxString & group)
{
wxAuiNotebook * nb = m_paneNotebooks[group];
if (NULL == nb)
{
wxLogMessage(_T("Pane group '%s' does not exist!"), group.c_str());
return false;
}
nb->AddPage(wnd, id, true);
m_aui->GetPane(nb).Show();
return true;
}
// Get parent for the pane area
wxWindow * Ui::GetPaneWindow (const wxString & group)
{
return m_paneNotebooks[group];
}
// Get pane by id
wxWindow * Ui::GetPane (const wxString & id)
{
return 0;
}
// remove pane
void Ui::RemovePane (const wxString & id)
{
}
// Get and Free
CUiManager * CUiManager::Get () { return Ui::GetInstance(); }
void CUiManager::Free () { Ui::Release (); }
<file_sep>/fbide-vs/Sdk/Editor/StcEditor.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
#include "../wxScintillaCtrl/stc.h"
namespace fbi
{
// forward declarations
class Editor;
class StyleParser;
class StyleInfo;
class FreeBasicSyntax;
/**
* The editor
*/
class SDK_DLL StcEditor : public ::wxScintillaCtrl
{
public:
// constructor
StcEditor ( wxWindow * wnd, Editor * owner, int index, StcEditor * mirror );
// on mouse right up ( show context menu for the editor )
void OnMouseRight (wxMouseEvent & event);
// update the ui
void OnUpdateUi (wxStyledTextEvent & event);
// zoom
void OnZoom (wxStyledTextEvent & event);
// Setup the editor. Load general config
void Setup (StyleParser * styles);
// Set style
void SetStyle (int nr, const StyleInfo & styleInfo);
private:
// precalculate the line-number margin width
void CalcLineMarginWidth();
// precalculated number margin widths
int m_dynLNWidths[5];
// show line numbers
bool m_showLineNumbers;
// dynamically size the line-number margin
int m_dynamicLineNumberWidth;
// the owner of this editor
Editor * m_owner;
// editor index ( in MultiSplitWindow )
int m_index;
// mirror the editor (for main null)
StcEditor * m_mirror;
// highlighter
FreeBasicSyntax * m_highlighter;
DECLARE_EVENT_TABLE()
};
}
<file_sep>/fbide-wx/sdk/src/PluginManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
using namespace fb;
/**
* Create new plugin object
*/
CPluginBase::CPluginBase ()
: m_provider(NULL), m_isAttached(false)
{
}
/**
* Is plugin attached ?
*/
bool CPluginBase::IsAttached ()
{
return m_isAttached;
}
/**
* Set "attached" state
*/
void CPluginBase::SetAttached (bool attached)
{
m_isAttached = attached;
}
/**
* Get plugin type
*/
PluginType CPluginBase::GetType ()
{
return m_provider->GetType();
}
/**
* Get plugin id name
*/
wxString CPluginBase::GetName()
{
return m_provider->GetName();
}
/**
* Unload the plugin
*
* This has to be postponed till execution
* leaved the plugin. Otherwise crash will happen.
* utilize IDLE event?
*/
void CPluginBase::Unload()
{
if (!IsAttached()) return;
GET_PLUGINMGR()->Unload (this, true);
}
/**
* Set the registrant
*/
void CPluginBase::SetProvider (CPluginProviderBase * provider)
{
m_provider = provider;
}
/**
* Get the registrant
*/
CPluginProviderBase * CPluginBase::GetProvider ()
{
return m_provider;
}
class CPluginManager::CData
{
public:
typedef std::map<wxString, CPluginProviderBase*> CPluginRegistry;
CPluginRegistry m_providers;
};
/**
* Create the instance
*/
CPluginManager::CPluginManager () : m_data(new CData())
{
}
/**
* release the instance
*/
CPluginManager::~CPluginManager ()
{
UnloadAll ();
}
/**
* Unload all plugins
*/
void CPluginManager::UnloadAll ()
{
typedef CData::CPluginRegistry::iterator Iterator;
for (Iterator iter = m_data->m_providers.begin();
iter != m_data->m_providers.end();
iter = m_data->m_providers.begin())
{
CPluginProviderBase * provider = iter->second;
Unload(provider->GetName(), true);
}
}
/**
* Notify all plugins about pending shutdown
*
* NB! This shoudl be called:
* - when fbide closes ( doen )
* - when plugin is about to be unloaded at runtime
* ensure that this is called only once!
*/
void CPluginManager::NotifyUnload ()
{
CData::CPluginRegistry::iterator iter = m_data->m_providers.begin();
for ( ; iter != m_data->m_providers.end(); iter++ )
{
iter->second->GetPlugin()->NotifyExit();
}
}
/**
* Register a new plugin
*/
void CPluginManager::AddProvider (const wxString & name, CPluginProviderBase * provider)
{
m_data->m_providers[name] = provider;
}
/**
* Load plugin file only. Will not instantiate
*/
bool CPluginManager::LoadPluginFile (const wxString & name)
{
// vars
CPluginProviderBase * provider;
// check if already loaded ?
if (m_data->m_providers[name]) return true;
// normalize filename
wxFileName file = wxDynamicLibrary::CanonicalizeName(GET_REG()[_T("dir.plugins")].AsString() + name, wxDL_MODULE);
file.Normalize();
// check file exists
if (!file.FileExists())
{
wxLogError(_T("Plugin file '%s' not found"), file.GetFullPath().c_str());
return false;
}
// load dll
wxDynamicLibrary * dll = new wxDynamicLibrary(file.GetFullPath());
if (!dll->IsLoaded())
{
wxLogError(_T("Could no load plugin '%s'"), name.c_str());
delete dll;
return false;
}
// check registrant
provider = m_data->m_providers[name];
if (!provider)
{
wxLogError(_T("No plugin provider for '%s' found"), name.c_str());
delete dll;
return false;
}
// register dll to registrant
provider->SetDll(dll);
// everything ok...
return true;
}
/**
* Get plugin instance by id
*/
CPluginBase * CPluginManager::GetPlugin (const wxString & name)
{
CPluginProviderBase * provider = m_data->m_providers[name];
if (!provider) return NULL;
return provider->GetPlugin();
}
/**
* Load plugin by name.
*/
CPluginBase * CPluginManager::LoadPlugin (const wxString & name)
{
CPluginBase * plugin;
CPluginProviderBase * provider;
// check id file is loaded ?
if (!LoadPluginFile(name)) return NULL;
provider = m_data->m_providers[name];
// Chech if plugin is already instantiated?
if (provider->IsLoaded()) return provider->GetPlugin();
// Get plugin instance
plugin = provider->Create();
if (!plugin)
{
// Some very wierd failure... ?
wxLogError(_T("Failed to create plugin instance '%s'"), name.c_str());
Unload(name, true);
return NULL;
}
// set provider to the plugin
plugin->SetProvider (provider);
// Attach plugin
if (!plugin->Attach())
{
Unload(name, true);
return NULL;
}
// Final setup
plugin->SetAttached(true);
// and done
return plugin;
}
/**
* Unload the plugin
*/
bool CPluginManager::Unload (CPluginBase * plugin, bool force)
{
return Unload(plugin->GetName(), force);
}
/**
* Unload by plugin id
*/
bool CPluginManager::Unload (const wxString & name, bool force)
{
CPluginProviderBase * provider = m_data->m_providers[name];
if (!provider) return true;
// release the plugin
if (provider->IsLoaded())
{
CPluginBase * plugin = provider->GetPlugin();
if (!plugin->Detach(force) && !force) return false;
provider->Release();
}
// delete dll
wxDynamicLibrary * dll = provider->GetDll();
if (dll) delete dll;
// remove provider
m_data->m_providers.erase(m_data->m_providers.find(name));
// plugin should use static object ??? delete provider;
return true;
}
<file_sep>/fbide-vs/Sdk/Editor/Editor.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
#include "../Document.h"
namespace fbi
{
// splitter
class MultiSplitWindow;
class StcEditor;
/**
* Editor panel
*/
class SDK_DLL Editor : public Document
{
public :
// default constructor
Editor ();
// Split / Unsplit vertically
void OnSplitVertically(wxCommandEvent & event);
// Split / Unsplit horizontally
void OnSplitHorizontally(wxCommandEvent & event);
private:
// the panel that contains the controls
wxPanel * m_panel;
// main sizer
wxSizer * m_sizer;
// splitter containint the editor(s)
MultiSplitWindow * m_splitter;
// main stc editor
StcEditor * m_stc;
// additional editors visible when split
StcEditor * m_editors[4];
// has an event table
DECLARE_EVENT_TABLE()
};
}<file_sep>/fbide-rw/sdk/variant.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "variant.h"
#include <wx/regex.h>
using namespace fb;
namespace
{
wxRegEx reSizePoint("^\\{([0-9]+)[ ]*,[ ]*([0-9]+)\\}$");
}
//------------------------------------------------------------------------------
// Variant
//------------------------------------------------------------------------------
Variant::Variant (const Variant & value)
: m_value(value.m_value) {}
void Variant::operator = (const Variant & rhs)
{ m_value = rhs.m_value; }
bool Variant::operator == (const Variant & rhs) const
{ return m_value == rhs.m_value; }
bool Variant::operator != (const Variant & rhs) const
{ return m_value != rhs.m_value; }
//------------------------------------------------------------------------------
// wxString
//------------------------------------------------------------------------------
Variant::Variant (const wxString & value)
: m_value(value) {}
void Variant::operator = (const wxString & rhs)
{ m_value = rhs; }
bool Variant::operator == (const wxString & rhs) const
{ return m_value == rhs; }
bool Variant::operator != (const wxString & rhs) const
{ return m_value != rhs; }
wxString Variant::AsString (const wxString & def) const
{ return m_value.Len() ? m_value : def; }
//------------------------------------------------------------------------------
// const char *
//------------------------------------------------------------------------------
Variant::Variant (const char * value)
: m_value(value) {}
void Variant::operator = (const char * rhs)
{ m_value = rhs; }
bool Variant::operator == (const char * rhs) const
{ return m_value == rhs; }
bool Variant::operator != (const char * rhs) const
{ return m_value != rhs; }
//------------------------------------------------------------------------------
// const wxChar *
//------------------------------------------------------------------------------
Variant::Variant (const wxChar * value)
: m_value(value) {}
void Variant::operator = (const wxChar * rhs)
{ m_value = rhs; }
bool Variant::operator == (const wxChar * rhs) const
{ return m_value == rhs; }
bool Variant::operator != (const wxChar * rhs) const
{ return m_value != rhs; }
//------------------------------------------------------------------------------
// int
//------------------------------------------------------------------------------
Variant::Variant (int value)
{ *this = value; }
void Variant::operator = (int rhs)
{ m_value.Empty(); m_value << rhs; }
bool Variant::operator == (int rhs) const
{ return AsInt() == rhs; }
bool Variant::operator != (int rhs) const
{ return AsInt() != rhs; }
int Variant::AsInt (int def) const
{
if (!m_value.Len()) return def;
long v; if (m_value.ToLong(&v)) return v;
if (m_value == "true" || m_value == "yes" || m_value== "on")
return (int)true;
return def;
}
//------------------------------------------------------------------------------
// bool
//------------------------------------------------------------------------------
bool Variant::AsBool (bool def) const
{
if (!m_value.Len()) return def;
if (m_value == "0") return false;
if (m_value == "true" || m_value == "yes" || m_value== "on")
return true;
long v; if (m_value.ToLong(&v)) return (bool)v;
return def;
}
//------------------------------------------------------------------------------
// double
//------------------------------------------------------------------------------
Variant::Variant (double value)
{ *this = value; }
void Variant::operator = (double rhs)
{ m_value.Empty(); m_value << rhs; }
bool Variant::operator == (double rhs) const
{ return AsDouble() == rhs; }
bool Variant::operator != (double rhs) const
{ return AsDouble() != rhs; }
double Variant::AsDouble (double def) const
{
if (!m_value.Len()) return def;
double v; if (m_value.ToDouble(&v)) return v;
return def;
}
//------------------------------------------------------------------------------
// wxSize {w, h}
//------------------------------------------------------------------------------
Variant::Variant (const wxSize & value)
{ *this = value; }
void Variant::operator = (const wxSize & rhs)
{
m_value.Empty();
m_value = MakeString(rhs);
}
bool Variant::operator == (const wxSize & rhs) const
{ return m_value == MakeString(rhs); }
bool Variant::operator != (const wxSize & rhs) const
{ return m_value != MakeString(rhs); }
wxSize Variant::AsSize (const wxSize & def) const
{
if (!m_value.Len()) return def;
if (reSizePoint.Matches(m_value))
{
auto w_str = reSizePoint.GetMatch(m_value, 1);
auto h_str = reSizePoint.GetMatch(m_value, 2);
long w = 0, h = 0;
w_str.ToLong(&w);
h_str.ToLong(&h);
return wxSize(w, h);
}
return def;
}
wxString Variant::MakeString (const wxSize & size)
{
wxString tmp;
tmp << "{" << size.GetWidth()
<< ", " << size.GetHeight() << "}"
;
return tmp;
}
//------------------------------------------------------------------------------
// wxPoint {w, h}
//------------------------------------------------------------------------------
Variant::Variant (const wxPoint & value)
{ *this = value; }
void Variant::operator = (const wxPoint & rhs)
{
m_value.Empty();
m_value = MakeString(rhs);
}
bool Variant::operator == (const wxPoint & rhs) const
{ return m_value == MakeString(rhs); }
bool Variant::operator != (const wxPoint & rhs) const
{ return m_value != MakeString(rhs); }
wxPoint Variant::AsPoint (const wxPoint & def) const
{
if (!m_value.Len()) return def;
if (reSizePoint.Matches(m_value))
{
auto x_str = reSizePoint.GetMatch(m_value, 1);
auto y_str = reSizePoint.GetMatch(m_value, 2);
long x = 0, y = 0;
x_str.ToLong(&x);
y_str.ToLong(&y);
return wxPoint(x, y);
}
return def;
}
wxString Variant::MakeString (const wxPoint & point)
{
wxString tmp;
tmp << "{" << point.x
<< ", " << point.y << "}"
;
return tmp;
}
//------------------------------------------------------------------------------
// wxColour css notation
//------------------------------------------------------------------------------
Variant::Variant (const wxColour & value)
{ *this = value; }
void Variant::operator = (const wxColour & rhs)
{
m_value.Empty();
m_value = MakeString(rhs);
}
bool Variant::operator == (const wxColour & rhs) const
{ return m_value == MakeString(rhs); }
bool Variant::operator != (const wxColour & rhs) const
{ return m_value != MakeString(rhs); }
wxColour Variant::AsColour (const wxColour & def) const
{
if (!m_value.Len()) return def;
auto c = wxColour(m_value);
if (c.IsOk ()) return c;
return def;
}
wxString Variant::MakeString (const wxColour & colour)
{
return colour.GetAsString(wxC2S_HTML_SYNTAX);
}
<file_sep>/fbide-wx/sdk/include/sdk/UiManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef UIMANAGER_H_INCLUDED
#define UIMANAGER_H_INCLUDED
namespace fb
{
/**
* forward references
*/
class IArtProvider;
class CManager;
class CDocumentBase;
class CUiToolDescriptor;
/**
* User interface manager handles menus, toolbars
* floatable / dockable panels and document views
* in abstract way. It generates some UI interaction
* specific logic and event handling
*
* Can be created only via CManager class.
*/
class DLLIMPORT CUiManager
{
public :
enum
{
PANE_TARGET_MANAGEMENT = 1,
PANE_TARGET_UTILS
};
// Register new tool descriptor
virtual void AddToolDescriptor (const wxString & name, CUiToolDescriptor * toolDesc) = 0;
// get doucment "parent" window
virtual wxWindow * GetDocWindow () = 0;
// load layout specified by xml
virtual void LoadLayout (const wxString & file) = 0;
// Clean up ui before application close
virtual void Unload () = 0;
// Get menu with given name
virtual wxMenu * GetMenu (const wxString & name) = 0;
// Add new menu into system
virtual void AddMenu (const wxString & name, wxMenu * menu, bool show = false) = 0;
// Get toolbar by name
virtual wxAuiToolBar * GetToolBar (const wxString & name) = 0;
// add new toolbar
virtual void AddToolBar (const wxString & name, wxAuiToolBar * toolbar, bool show = false) = 0;
// Add document into Document view
virtual void AddDocument (CDocumentBase * doc, bool show) = 0;
// Get currently active document or return NULL if noen
virtual CDocumentBase * GetActiveDocument () = 0;
// Add pane
virtual bool AddPane (const wxString & id, wxWindow * wnd, const wxString & group) = 0;
// Get parent for the pane area
virtual wxWindow * GetPaneWindow (const wxString & group) = 0;
// Get pane by id
virtual wxWindow * GetPane (const wxString & id) = 0;
// remove pane
virtual void RemovePane (const wxString & id) = 0;
// Remove document
virtual void RemoveDocument (CDocumentBase * doc) = 0;
// Set art provider
virtual void SetArtProvider (IArtProvider * provider) = 0;
// Get art provider
virtual IArtProvider * GetArtProvider () = 0;
// Load the UI (finalize loading process)
virtual void Load () = 0;
// Registerable callback for ArtProviderChange event
CMultiDelegate<void(IArtProvider *)> onArtProvderChange;
private :
friend class CManager;
static CUiManager * Get ();
static void Free ();
protected :
virtual ~CUiManager() {}
};
}
#endif // UIMANAGER_H_INCLUDED
<file_sep>/fbide-wx/sdk/include/sdk/EventMap.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EVENT_MAP_H_INCLUDED
#define EVENT_MAP_H_INCLUDED
#include "sdk/MultiDelegate.h"
#include <map>
namespace fb
{
/**
* Provide simple EVENT_ID -> multidelegate map
* for event broadcasting classes to implement
*/
template<typename KEY, class MULTI_DLG>
class CEventMapBase
{
public :
// the method
typedef typename MULTI_DLG::Signature Signature;
// Add event to the EventMap
void Bind (KEY event, Signature delegate)
{
m_evt[event] += delegate;
}
// Remove event from the EventMap
void UnBind (KEY event, Signature delegate)
{
m_evt[event] -= delegate;
}
// get reference to the MULTI_DLG
inline MULTI_DLG & GetEventMap (KEY event)
{
return m_evt[event];
}
private :
typedef std::map<KEY, MULTI_DLG> EventMap;
EventMap m_evt;
};
// Specialise CEventMap template for nice api
template<typename KEY, typename T>
class CEventMap;
// R()
template<typename KEY, typename R>
class CEventMap < KEY, R ( ) >
: public CEventMapBase<KEY, CMultiDelegate<R> >
{};
// R(p1)
template<typename KEY, typename R, typename P1>
class CEventMap < KEY, R ( P1 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1)> >
{};
// R(p1, p2)
template<typename KEY, typename R, typename P1, typename P2>
class CEventMap < KEY, R ( P1, P2 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1, P2)> >
{};
// R(p1, p2, p3)
template<typename KEY, typename R, typename P1, typename P2, typename P3>
class CEventMap < KEY, R ( P1, P2, P3 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1, P2, P3)> >
{};
// R(p1, p2, p3, p4)
template<typename KEY, typename R, typename P1, typename P2, typename P3, typename P4>
class CEventMap < KEY, R ( P1, P2, P3, P4 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1, P2, P3, P4)> >
{};
// R(p1, p2, p3, p4, p5)
template<typename KEY, typename R, typename P1, typename P2, typename P3, typename P4, typename P5>
class CEventMap < KEY, R ( P1, P2, P3, P4, P5 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1, P2, P3, P4, P5)> >
{};
// R(p1, p2, p3, p4, p5, p6)
template<typename KEY, typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6>
class CEventMap < KEY, R ( P1, P2, P3, P4, P5, P6 ) >
: public CEventMapBase<KEY, CMultiDelegate<R(P1, P2, P3, P4, P5, P6)> >
{};
} // namespace fb
#endif // EVENT_MAP_H_INCLUDED
<file_sep>/fbide-wx/App/src/Frame.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "Frame.h"
#include "sdk/Manager.h"
#include "sdk/UiManager.h"
#include "sdk/TypeManager.h"
#include "sdk/PluginManager.h"
using namespace fb;
/**
* Main application event table
*/
BEGIN_EVENT_TABLE(CFrame, wxFrame)
EVT_MENU (wxID_EXIT, CFrame::OnExit)
EVT_CLOSE (CFrame::OnClose)
END_EVENT_TABLE()
/**
* Construct the main FBIde frame window
*/
CFrame::CFrame(wxFrame *frame, const wxString& title)
: wxFrame(
frame, -1, title, wxDefaultPosition,
wxSize(640, 480)
)
{
}
/**
* Do cleanup here
*/
CFrame::~CFrame()
{
}
/**
* Close window
*/
void CFrame::OnClose(wxCloseEvent &event)
{
/*
int answer = wxMessageBox (_T("Quit FBIde?"), _T("Exit FBIde"), wxYES_NO | wxICON_QUESTION);
if (answer != wxYES) return;
*/
GET_PLUGINMGR()->NotifyUnload();
GET_UIMGR()->Unload();
Destroy();
}
/**
*
*/
void CFrame::OnExit (wxCommandEvent & event)
{
Close(true);
}
<file_sep>/fbide-vs/Sdk/TypeManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "Manager.h"
#include "UiManager.h"
#include "TypeManager.h"
#include "Document.h"
using namespace fbi;
/**
* Manager class implementation
*/
struct TheTypeManager : TypeManager
{
// forward ref
struct TypeInfo;
// Hold a list of typeinfos
typedef std::vector<TypeInfo*> TypeInfoVector;
// Register new type
virtual void Register (const wxString & type,
const wxString & desc,
DocCreatorFn creator )
{
// type already registered?
if (IsRegistered(type))
{
wxLogError("Type '%s' already registered with TypeManager", type);
return;
}
// create type and set info
auto & info = m_typeMap[type];
info.isAlias = false;
info.type = type;
info.desc = desc;
info.creator = creator;
}
// Bind file extensions to the type
virtual void BindExtensions (const wxString & type,
const wxString & extensions)
{
// find one level only
auto info = FindType(type, false);
if (info == nullptr)
{
wxLogError("Type '%s' is not registered with TypeManager", type);
return;
}
// explode extensions into an array
wxArrayString arr;
ExplodeString(extensions, arr, ";");
// add the extensions
for (size_t i = 0; i < arr.Count(); i++)
{
// Get the extension anc clean it
wxString ext = arr[i].Lower().Trim();
//if (!ext.Len()) continue;
// avoid duplicates
if (info->exts.Index(ext) != wxNOT_FOUND) continue;
// Bind the extenions
info->exts.Add(ext);
m_extMap[ext].push_back(info);
}
}
// Bind type alias to an existing type
virtual void BindAlias (const wxString & alias,
const wxString & target,
bool overwrite)
{
// Get target type. However One alias may point to another
// and later alias might change the target. So resolve one level only
auto targetInfo = FindType(target, false);
if (targetInfo == nullptr)
{
wxLogError("Target '%s' is not registered with TypeManager", target);
return;
}
// Get alias type
auto aliasInfo = FindType(alias, false);
if (aliasInfo != nullptr)
{
// type exists ...
if (!overwrite || !aliasInfo->isAlias)
{
wxLogError("Cannot convert '%s' into an alias in TypeManager", alias);
return;
}
// overwrite the alias
auto oldTarget = aliasInfo->alias;
aliasInfo->alias = targetInfo;
// check for circular references
auto check = aliasInfo;
while (check->isAlias)
{
// circular reference
if (check->alias = aliasInfo)
{
wxLogError("Alias '%s' creates a circular reference with '%s' in TypeManager", alias, target);
aliasInfo->alias = oldTarget;
return;
}
check = check->alias;
}
return;
}
// add new
auto & entry = m_typeMap[alias];
entry.isAlias = true;
entry.alias = targetInfo;
}
// Create new document. Deduct type from extension
// if failed show a dialog with an option to open the file
// with any other registered loaders or use OS to open it
// return nullptr if not opened in the editor
virtual Document * CreateFromFile (const wxString & file)
{
// get the extension and clean it
wxString ext = wxFileName(file).GetExt().Lower().Trim();
// if extension is already registered ?
auto extIter = m_extMap.find(ext);
if (extIter != m_extMap.end())
{
auto doc =_createFromExt( extIter->second, true );;
if (doc != nullptr) _loadFile( doc, file );
return doc;
}
// Get different loaders and ignore aliases
TypeInfoVector list;
for (auto iter = m_typeMap.begin(); iter != m_typeMap.end(); iter++)
{
TypeInfo * info = &iter->second;
while (info->isAlias) info = info->alias;
if (std::find(list.begin(), list.end(), info) == list.end()) list.push_back(info);
}
// choises.
wxArrayString choices;
for (size_t i = 0; i < list.size(); i++) choices.Add(list[i]->desc);
// Allow user to select the document type to create
// todo - add option to open with external program
// todo - add option to use shell to open
auto & lang = GET_LANG();
wxSingleChoiceDialog select(
GET_FRAME(),
lang.Get("open.document.type.message", "file", file),
lang.Get("open.document.type.title", "file", file),
choices
);
if (select.ShowModal() == wxID_CANCEL) return nullptr;
// create the document and load file
auto doc = list[select.GetSelection()]->creator();
if (doc != nullptr) _loadFile( doc, file );
return doc;
}
// Load file
void _loadFile ( Document * doc, const wxString & file )
{
auto & lang = GET_LANG();
wxFileName f(file);
if (!f.FileExists())
{
wxMessageBox(lang.Get("error.file-not-found", "filename", file));
return;
}
if (doc->LoadDocFile(file))
{
doc->SetDocFilename(file);
doc->SetDocTitle(f.GetFullName());
}
}
// Create new document using type name. If not registred
// return nullptr and log a warning.
virtual Document * CreateFromType (const wxString & type)
{
auto info = FindType(type, true);
if (info == nullptr)
{
wxLogError("Type '%s' is not registered with TypeManager", type);
return nullptr;
}
return info->creator();
}
// Create new document by registered extenions.
// if multiple creators are registered show a dialog allowing
// to select the proper type.
// return nullptr and log a warning if no extension is registered
// with the type
virtual Document * CreateFromExtension (const wxString & ext)
{
auto extIter = m_extMap.find(ext);
if (extIter == m_extMap.end())
{
wxLogError("File extension '%s' is not registered with TypeManager", ext);
return nullptr;
}
// create
return _createFromExt( extIter->second, false );
}
// Create from extension
// internal implementation
Document * _createFromExt (TypeInfoVector & types, bool fromFile)
{
// there is only one registered type then return it
if (types.size() == 1) return types[0]->creator();
// get the types and elimiate duplicates
TypeInfoVector list;
for (auto iter = types.begin(); iter != types.end(); iter++)
{
auto info = *iter;
while (info->isAlias) info = info->alias;
if (std::find(list.begin(), list.end(), info) == list.end()) list.push_back(info);
}
// is only one type left ?
if (list.size() == 1) return list[0]->creator();
// choises.
// NB! don't sort this. order is important as
// index is used to match
wxArrayString choices;
for (size_t i = 0; i < list.size(); i++) choices.Add(list[i]->desc);
// Allow user to select the document type to create
auto & lang = GET_LANG();
wxSingleChoiceDialog select(
GET_FRAME(),
lang["select.document.type.message"],
lang["select.document.type.title"],
choices
);
if (select.ShowModal() == wxID_CANCEL) return nullptr;
// and create the document
return list[select.GetSelection()]->creator();
}
// check if type is registered. Will resolve aliases to the
// actual type
virtual bool IsRegistered ( const wxString & type )
{
return m_typeMap.find(type) != m_typeMap.end();
}
// Get file filters to be used with file load / save dialogs
virtual wxString GetFileFilters ( bool incAllFiles )
{
// Collect all information needed into a map
std::map<TypeInfo *, wxString> map;
// iterate through the extensions
for (auto extIter = m_extMap.begin(); extIter != m_extMap.end(); extIter++)
{
// get list where the extension can possibly belong
auto & list = extIter->second;
for (auto typeIter = list.begin(); typeIter != list.end(); typeIter++)
{
// resolve aliases
TypeInfo * info = *typeIter;
while (info->isAlias) info = info->alias;
// add extension to the map
wxString & exts = map[info];
if (exts.Len()) exts << ";";
exts << "*." << extIter->first;
}
}
// generate the string
wxString result;
for (auto iter = map.begin(); iter != map.end(); iter++)
{
if (result.Len()) result << "|";
result << iter->first->desc << " (" << iter->second << ")|" << iter->second;
}
// add All files
if (incAllFiles)
{
if (result.Len()) result << "|";
result << GET_LANG()["all-files"] << " (*.*)|*.*";
}
return result;
}
// find type by name and return TypeInfo * or nullptr
// if not found.
TypeInfo * FindType ( const wxString & type, bool resolveAlias )
{
// find
auto iter = m_typeMap.find(type);
if (iter == m_typeMap.end()) return nullptr;
// don't care about aliases
if (!resolveAlias) return &iter->second;
// resolve alias
TypeInfo * info = &iter->second;
while (info->isAlias) info = info->alias;
return info;
}
/**
* PHP like explode function by <NAME>
* from http://wxforum.shadonet.com/viewtopic.php?p=12929#12929
*/
void ExplodeString( const wxString& s,
wxArrayString& retArray,
const char * cpszExp,
const size_t& crnStart = 0,
const size_t& crnCount = (size_t)-1,
const bool& crbCIComp = false)
{
wxASSERT_MSG(cpszExp != NULL, wxT("Invalid value for First Param of wxString::Split (cpszExp)"));
retArray.Clear();
size_t nOldPos = crnStart, nPos = crnStart;
wxString szComp, szExp = cpszExp;
if (crbCIComp)
{
szComp = s.Lower();
szExp.MakeLower();
}
else
szComp = s;
if(crnCount == (size_t)-1)
{
for (; (nPos = szComp.find(szExp, nPos)) != wxString::npos;)
{
retArray.Add(s.Mid(nOldPos, nPos - nOldPos));
nOldPos = nPos += szExp.Length();
}
}
else
{
for (int i = crnCount; (nPos = szComp.find(szExp, nPos)) != wxString::npos && i != 0; --i)
{
retArray.Add(s.Mid(nOldPos, nPos - nOldPos));
nOldPos = nPos += szExp.Length();
}
}
if (nOldPos != s.Length()) retArray.Add(s.Mid(nOldPos) );
}
// hold type information
struct TypeInfo
{
// is this an alias to another type ?
bool isAlias;
// type name
wxString type;
// type description
wxString desc;
// type extensions
wxArrayString exts;
// if is alias then a pointer to typeinfo it points to
// otherwise document creaor function pointer
union
{
TypeInfo * alias;
DocCreatorFn creator;
};
};
// hold types
HashMap<TypeInfo> m_typeMap;
// hold extension to typeinfo
HashMap<TypeInfoVector> m_extMap;
};
// Implement Manager
IMPLEMENT_MANAGER(TypeManager, TheTypeManager)
<file_sep>/fbide-wx/Plugins/Log/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/UiManager.h"
using namespace fb;
#include <wx/thread.h>
#include <queue>
/**
* Run the logging inside the thread
* so that large amount of log wouldn't get
* in teh way of responsivness of the main UI
*
* works on Win32. how about linux ?
*/
struct LogThread
: public wxThread,
public wxLog
{
LogThread ( wxTextCtrl * tctrl, wxButton * logStopBtn )
: m_tctrl( tctrl ), m_logStopBtn( logStopBtn )
{
}
// ...
virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t)
{
wxMutexLocker lock(m_inputLock);
m_text.push(szString);
if (NULL != m_logStopBtn)
m_logStopBtn->Enable(true);
}
/**
* the thread function
*/
virtual ExitCode Entry()
{
// hold the message
wxString msg;
// run the thread
while ( !TestDestroy() )
{
// check if there are any messages ?
{
wxMutexLocker lock1(m_inputLock);
if ( m_text.empty() )
{
if (NULL != m_logStopBtn)
m_logStopBtn->Disable();
continue;
}
msg = m_text.front();
m_text.pop();
}
// log the message
{
wxMutexLocker lock(m_tctrlLock);
if (NULL != m_tctrl)
{
m_tctrl->AppendText ( msg );
m_tctrl->AppendText ( _T("\n") );
}
}
}
return NULL;
}
// clear the log window
void Clear ()
{
wxMutexLocker lock(m_tctrlLock);
if (NULL != m_tctrl) m_tctrl->Clear();
}
// Stop the log input
void Stop ()
{
wxMutexLocker lock(m_inputLock);
while ( !m_text.empty() ) m_text.pop();
if (NULL != m_logStopBtn) m_logStopBtn->Disable();
}
// NotifyExit
void NotifyExit ()
{
LogThread::Stop();
wxMutexLocker lock1(m_inputLock);
m_logStopBtn = NULL;
}
wxTextCtrl * m_tctrl;
wxButton * m_logStopBtn;
wxMutex m_inputLock, m_tctrlLock;
std::queue<wxString> m_text;
};
struct LogPlugin
: public CPluginBase,
public wxEvtHandler
{
// Attach plugin
bool Attach ()
{
CManager &mgr = *GET_MGR();
CUiManager &ui= *mgr.GetUiManager();
// get parent pointer
wxWindow * p = ui.GetPaneWindow(_T("logs"));
wxASSERT( p != NULL );
if ( p == NULL ) return false;
// panel
wxPanel * panel = new wxPanel(p);
// sizer
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
panel->SetSizer(sizer);
ID_LOG_CLEAR = wxNewId();
ID_LOG_STOP = wxNewId();
// the toolbar
wxToolBar* toolbar = new wxToolBar( panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_FLAT|wxTB_HORIZONTAL );
// log button
wxButton* logClearBtn = new wxButton( toolbar, ID_LOG_CLEAR, _("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
logClearBtn->SetName(_T("Clear"));
toolbar->AddControl(logClearBtn);
// stop button
wxButton* logStopBtn = new wxButton( toolbar, ID_LOG_STOP, _("Stop"), wxDefaultPosition, wxDefaultSize, 0 );
logStopBtn->SetName(_T("Clear"));
toolbar->AddControl(logStopBtn);
toolbar->Realize();
sizer->Add(toolbar, 0, wxGROW|wxLEFT|wxRIGHT|wxTOP, 5);
// create control
tctrl = new wxTextCtrl (
panel, wxID_ANY,
_T(""),
wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxTE_READONLY | wxTE_BESTWRAP
);
tctrl->SetFont(wxFont(
12,
wxFONTFAMILY_MODERN,
wxFONTSTYLE_NORMAL,
wxFONTWEIGHT_NORMAL,
false,
_T("Courier New")
));
sizer->Add(tctrl, 1, wxGROW|wxLEFT|wxRIGHT|wxBOTTOM, 5);
// Add to the UI
ui.AddPane(_T("Log"), panel, _T("logs"));
// connect clear event
panel->wxEvtHandler::SetNextHandler(dynamic_cast<wxEvtHandler *>(this));
Connect(
ID_LOG_CLEAR,
wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(LogPlugin::OnCommand)
);
Connect(
ID_LOG_STOP,
wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(LogPlugin::OnCommand)
);
// the thread
m_logThread = new LogThread (tctrl, logStopBtn);
m_logThread->Create();
m_logThread->Run();
// Set log target
wxLog::SetLogLevel(wxLOG_Info);
wxLog::SetActiveTarget(m_logThread);
// success
return true;
}
// show the log window
void OnCommand (wxCommandEvent & e)
{
int id = e.GetId();
if ( id == ID_LOG_CLEAR ) m_logThread->Clear();
else if ( id == ID_LOG_STOP ) m_logThread->Stop();
}
// void
bool Detach (bool force)
{
wxLog::SetActiveTarget(NULL);
m_logThread->Delete();
}
// about to close ?
void NotifyExit ()
{
wxLog::SetActiveTarget(NULL);
m_logThread->NotifyExit();
}
// the text control to send the log to
wxTextCtrl * tctrl;
LogThread * m_logThread;
// IDs
int ID_LOG_CLEAR;
int ID_LOG_STOP;
};
namespace
{
CPluginProvider<LogPlugin, PLUGINTYPE_TOOL> plugin (_T("LogPlugin"));
}
<file_sep>/fbide-wx/sdk/include/sdk/PluginManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef PLUGINMANAGER_H_INCLUDED
#define PLUGINMANAGER_H_INCLUDED
namespace fb
{
// fwd ref
class CPluginProviderBase;
class CPluginManager;
/**
* To ease differentation between plugins...
*/
enum PluginType
{
PLUGINTYPE_ARTPROVIDER,
PLUGINTYPE_EDITOR,
PLUGINTYPE_TOOL,
PLUGINTYPE_WIZARD
};
/**
* Base class for plugins
*/
class DLLIMPORT CPluginBase
{
// allow PluginManager to access private bits
friend class CPluginManager;
// Get provider
CPluginProviderBase * GetProvider ();
// Set provider
void SetProvider (CPluginProviderBase *);
// Set this plugin to be "attached"
void SetAttached (bool attached);
public :
// Create new plugin instance (should be a template?)
CPluginBase ();
// destroy
virtual ~CPluginBase() {}
// Get type
PluginType GetType ();
// Get plugin name
wxString GetName ();
// Is attached
bool IsAttached ();
// Unload this plugin (should be used with care)
void Unload ();
// Call on attach
virtual bool Attach () = 0;
// notify unload
virtual void NotifyExit () {}
// And when detached
virtual bool Detach (bool force) { return true; };
private :
CPluginProviderBase * m_provider;
bool m_isAttached;
};
/**
* Base class for plugin registrants
*/
class DLLIMPORT CPluginProviderBase
{
public :
// Get plugin instance (if loaded)
CPluginBase * GetPlugin () { return m_plugin; }
// get plugin type
PluginType GetType () { return m_type; }
// get sdk version
virtual int GetSDKVersion() = 0;
// Get plugin name (registration name)
wxString GetName () { return m_name; }
// Is loaded ?
bool IsLoaded () { return m_plugin != NULL; };
protected :
// Allow plugin manager to access private bits
friend class CPluginManager;
PluginType m_type;
wxString m_name;
CPluginBase * m_plugin;
wxDynamicLibrary * m_dll;
// Create plugin registrant object
CPluginProviderBase (PluginType type, const wxString & name)
: m_type(type), m_name(name), m_plugin(NULL), m_dll(NULL)
{}
// clean up...
virtual ~CPluginProviderBase () {}
// Get plugin instance (if loaded)
virtual CPluginBase * Create () = 0;
// Destroy plugin
void Release ()
{
if (m_plugin == NULL) return;
delete m_plugin;
m_plugin = NULL;
}
// Set the DLL handle
void SetDll (wxDynamicLibrary * dll)
{
m_dll = dll;
}
// Get Dll
wxDynamicLibrary * GetDll ()
{
return m_dll;
}
};
/**
* This class manages the plugins
*
* Can be accessed via CManager
*/
class DLLIMPORT CPluginManager
{
public :
// Register new plugin provider
void AddProvider (const wxString & name, CPluginProviderBase * registrant);
// Load plugin by ID. (fbide/ide/plugins is default folder)
CPluginBase * LoadPlugin (const wxString & name);
// Will only load dll but not instantiate the plugin
bool LoadPluginFile (const wxString & file);
// Get plugin instance (if loaded)
CPluginBase * GetPlugin (const wxString & name);
// Unload the plugin.
bool Unload (CPluginBase * plugin, bool force);
bool Unload (const wxString & name, bool force);
// Unload all plugins
void UnloadAll ();
// send unload notification
void NotifyUnload ();
private :
friend class CManager;
CPluginManager ();
~CPluginManager ();
struct CData ;
std::auto_ptr<CData> m_data;
};
/**
* Template used for registaring ny plugins easily and hasslefree.
* namespace
* {
* CPluginProvider<PluginClass, PLUGINTYPE> plugin(_T("PluginName"));
* }
*/
template<class T, PluginType type> class CPluginProvider : public CPluginProviderBase
{
public:
CPluginProvider(const wxString& name) : CPluginProviderBase(type, name)
{
CManager::Get()->GetPluginManager()->AddProvider(name, this);
}
/**
* Destroy
*/
virtual ~CPluginProvider() {}
/**
* Get plugin instance
*/
virtual CPluginBase * Create ()
{
if (m_plugin == NULL) m_plugin = new T ();
return m_plugin;
}
/**
* Get version
*/
virtual int GetSDKVersion()
{
return (SDK_VERSION_MAJOR * 1000) + (SDK_VERSION_MINOR * 100) + SDK_VERSION_RELEASE;
}
};
}
#endif // PLUGINMANAGER_H_INCLUDED
<file_sep>/fbide-rw/sdk/singleton.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fb
{
/**
* Template to declare singleton classes
*/
template <class T> class Singleton
{
private :
static T * m_instance;
// disable any copy constructions...
explicit Singleton (const Singleton<T>&) = delete;
Singleton<T>& operator = (Singleton<T> const&) = delete;
protected :
// private constructor
Singleton()
{
assert(Singleton<T>::m_instance == 0L);
}
// private destructor
virtual ~Singleton()
{
Singleton<T>::m_instance = NULL;
}
public:
/**
* Return true if Singleton instance exists
*/
static inline bool IsCreated () { return m_instance != 0L; }
/**
* Get singleton class instance. Create if doesn't exist
*/
static inline T * GetInstance()
{
if(m_instance == 0L) m_instance = new T();
return m_instance;
}
/**
* Release existing singleton instance
*/
static inline void Release()
{
if (!Singleton::IsCreated()) return;
delete m_instance;
m_instance = 0L;
}
};
template<class T>T * Singleton<T>::m_instance = 0L;
}
<file_sep>/fbide-vs/Sdk/Language.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
using namespace fbi;
/**
* Get translation for ID or return ID itself
*/
wxString & Language::operator [] ( const wxString & key ) {
auto iter = m_map.find(key);
if (iter != m_map.end()) return iter->second;
return m_map[key] = key;
}
/**
* Get translation and replace tags
*/
wxString Language::Get (const wxString & key, const StringHashMap & map)
{
wxString str = (*this)[key]; // create a copy
for (auto iter = map.begin(); iter != map.end(); iter++) {
str.Replace("{" + iter->first + "}", iter->second, true);
}
return str;
}
/**
* Get translation and replace a tag
*/
wxString Language::Get(const wxString & key, const std::pair<wxString, wxString> & tag)
{
wxString str = (*this)[key]; // create a copy
str.Replace("{" + tag.first + "}", tag.second, true);
return str;
}
/**
* Get translation and replace a tag
*/
wxString Language::Get(const wxString & key, const wxString & tag, const wxString & value)
{
wxString str = (*this)[key]; // create a copy
str.Replace("{" + tag + "}", value, true);
return str;
}
/**
* Load language
*/
void Language::Load (const wxString & file)
{
if (!wxFileExists(file)) {
wxLogError("Language file '%s' not found", file);
return;
}
wxFileInputStream is (file);
wxFileConfig ini(is);
long index = 0;
wxString entry;
if (!ini.GetFirstEntry (entry, index)) return;
do
{
(*this)[entry] = ini.Read(entry, "");
} while (ini.GetNextEntry(entry, index));
}<file_sep>/fbide-vs/Sdk/Editor/Syntax/LexFreeBasic.hxx
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*
* This file is based on VB lexer for Scintilla by
* <NAME> <<EMAIL>>
*/
#ifndef LEXFREEBASIC_HXX_INCLUDED
#define LEXFREEBASIC_HXX_INCLUDED
namespace LEX
{
// the lexer ID
const int FREEBASIC = 100;
// lexer states
enum
{
// Lexical states for FB code
FB_DEFAULT = 0,
FB_IDENTIFIER = 1,
FB_COMMENT = 2,
FB_COMMENT_URL = 3,
FB_LABEL = 4,
FB_STRING = 5,
FB_STRING_ESCAPE = 6,
FB_NUMBER = 7,
FB_OPERATOR = 8,
FB_KEYWORD_ONE = 9,
FB_KEYWORD_TWO = 10,
FB_KEYWORD_THREE = 11,
FB_KEYWORD_FOUR = 12,
FB_SECTION_LAST = FB_KEYWORD_FOUR,
// the lexical states for ASM code
ASM_DEFAULT = 17,
ASM_IDENTIFIER = 18,
ASM_COMMENT = 19,
ASM_COMMENT_URL = 20,
ASM_LABEL = 21,
ASM_STRING = 22,
ASM_STRING_ESCAPE = 23,
ASM_NUMBER = 24,
ASM_OPERATOR = 25,
ASM_FB_KEYWORD_ONE = 26,
ASM_FB_KEYWORD_TWO = 27,
ASM_FB_KEYWORD_THREE = 28,
ASM_FB_KEYWORD_FOUR = 29,
ASM_KEYWORD_ONE = 30,
ASM_KEYWORD_TWO = 31,
ASM_SECTION_LAST = ASM_KEYWORD_TWO,
// Lexical states for preprocessor blocks
PP_DEFAULT = 40,
PP_IDENTIFIER = 41,
PP_COMMENT = 42,
PP_COMMENT_URL = 43,
PP_LABEL = 44,
PP_STRING = 45,
PP_STRING_ESCAPE = 46,
PP_NUMBER = 47,
PP_OPERATOR = 48,
PP_FB_KEYWORD_ONE = 49,
PP_FB_KEYWORD_TWO = 50,
PP_FB_KEYWORD_THREE = 51,
PP_FB_KEYWORD_FOUR = 52,
PP_KEYWORD_ONE = 53,
PP_KEYWORD_TWO = 54,
PP_SECTION_LAST = 55
};
/**
* Test if style is a single line comment
*/
static inline bool IsInComment (int style)
{
return style == FB_COMMENT
|| style == ASM_COMMENT
|| style == PP_COMMENT
;
}
/**
* returns true if this style is a comment of any kind
*/
static inline bool IsInAnyComment (int style)
{
return style == FB_COMMENT
|| style == FB_COMMENT_URL
|| style == ASM_COMMENT
|| style == ASM_COMMENT_URL
|| style == PP_COMMENT
|| style == PP_COMMENT_URL
;
}
/**
* Test if style is comment url
*/
static inline bool IsInCommentUrl (int style)
{
return style == FB_COMMENT_URL
|| style == ASM_COMMENT_URL
|| style == PP_COMMENT_URL
;
}
/**
* Test if style is a string literal
*/
static inline bool IsInString (int style)
{
return style == FB_STRING
|| style == ASM_STRING
|| style == PP_STRING
;
}
/**
* Check if is inside default section
*/
static inline bool IsInDefaultSection (int style)
{
return style == FB_DEFAULT
|| style == ASM_DEFAULT
|| style == PP_DEFAULT
;
}
// Keyword types
enum
{
KEYWORD_ONE = 0,
KEYWORD_TWO = 1,
KEYWORD_THREE = 2,
KEYWORD_FOUR = 3,
KEYWORD_PP_ONE = 4,
KEYWORD_PP_TWO = 5,
KEYWORD_ASM_ONE = 6,
KEYWORD_ASM_TWO = 7
};
// FB DIALECT TYPE
enum
{
DIALECT_QB,
DIALECT_LITE,
DIALECT_DEPRECATED,
DIALECT_FB
};
// Line state bits
enum
{
/* bits 0 to 23 reserved */
LINESTATE_MULTILINE_ASM = 1 << 29,
LINESTATE_LINE_CONTINUATION = 1 << 30,
LINESTATE_REFRESH = 1 << 31, // force editor refresh
};
}
#endif // LEXFREEBASIC_HXX_INCLUDED
<file_sep>/fbide-vs/App/FBIde.cpp
/**
* FBIde main application
*/
#include "app_pch.h"
#include "Sdk/Manager.h"
#include "Sdk/UiManager.h"
#include "Sdk/ScriptManager.h"
#include "Sdk/CmdManager.h"
using namespace fbi;
/**
* Main application class
*/
class FBIdeApp : public wxApp
{
// Entry point
virtual bool OnInit () {
// base init
if (!wxApp::OnInit()) return false;
// app base
wxStandardPathsBase & sp = this->GetTraits()->GetStandardPaths();
auto path = ::wxPathOnly(sp.GetExecutablePath());
// Load Language
Language & lang = GET_LANG();
lang.Load(path + "/ide/en.ini");
// set registry
auto & reg = GET_REG();
reg["path.ide.data"] = path + "/ide/";
auto ui = GET_UIMGR();
if (!ui->Load()) return false;
// ensure all managers are loaded
GET_CMDMGR();
GET_DOCMGR();
GET_TYPEMGR();
GET_EDITORMGR();
GET_PLUGINMGR();
GET_SCRIPTMGR();//->Execute(path + "/test.js");
// GET_SCRIPTMGR()->Execute(path + "/test.js");
ui->LoadLayout(path + "/ide/layout.xml");
auto frame = ui->GetFrame();
frame->Show();
// set logger
auto * logger = new wxLogWindow(frame, "logs");
//logger->SetLogLevel(wxLOG_Info);
logger->Resume();
wxLog::SetActiveTarget ( logger );
// success
return true;
}
};
IMPLEMENT_APP(FBIdeApp);
<file_sep>/fbide-vs/Sdk/sdk_pch.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
// wxWidget headers
#include <wx/wxprec.h>
#include <wx/stdpaths.h>
#include <wx/apptrait.h>
#include <wx/regex.h>
#include <wx/filename.h>
#include <wx/xml/xml.h>
#include <wx/aui/aui.h>
#include <wx/gdicmn.h>
#include <wx/fileconf.h>
#include <wx/wfstream.h>
#include <wx/dynlib.h>
#include <wx/log.h>
#include <wx/textfile.h>
#include <wx/splitter.h>
// #include <wx/stc/stc.h>
#include <wx/wupdlock.h>
#include <wx/tokenzr.h>
#include <wx/textctrl.h>
// c++ stl headers
#include <unordered_map>
#include <map>
#include <memory>
// delegates
#include "Delegate.h"
#include "MultiDelegate.h"
// FBIde SDK headers
#include "Sdk.h"
#include "Variant.h"
#include "Utilities.h"
#include "Version.h"
#include "Registry.h"
#include "Language.h"
<file_sep>/fbide-wx/sdk/include/sdk/Manager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef MANAGER_H_INCLUDED
#define MANAGER_H_INCLUDED
#define GET_MGR() fb::CManager::Get()
#define GET_UIMGR() fb::CManager::Get()->GetUiManager()
#define GET_TYPEMGR() fb::CManager::Get()->GetTypeManager()
#define GET_DOCMGR() fb::CManager::Get()->GetDocManager()
#define GET_PLUGINMGR() fb::CManager::Get()->GetPluginManager()
#define GET_LANG() fb::CManager::Get()->GetLang()
#define GET_REG() fb::CManager::Get()->GetReg()
#define GET_EDITORMGR() fb::CManager::Get()->GetEditorManager()
#include "sdk/Registry.h"
namespace fb
{
/**
* Forward declarations
*/
class CUiManager;
class CTypeManager;
class CDocManager;
class CPluginManager;
class CStyleParser;
class CEditorManager;
/**
* Manager is entry to FBIde SDK
*/
class DLLIMPORT CManager
{
public :
// Get and release the instance
static CManager * Get ();
// Release (and clean up) managers
static void Free ();
// language and registry are managed by
// CManager as well.
CRegistry & GetReg ();
// Language
const wxString & GetLang (const wxString & name);
// ID - name relation
void RegisterId (const wxString & name, int id);
int GetId (const wxString & name);
// wxFrame handling
void SetFrame (wxFrame * frame);
wxFrame * GetFrame ();
// managers
CUiManager * GetUiManager();
CTypeManager * GetTypeManager ();
CDocManager * GetDocManager ();
CPluginManager * GetPluginManager ();
CStyleParser * GetStyleParser (const wxString & name);
CEditorManager * GetEditorManager ();
void SetStyleParser (const wxString & name, CStyleParser * parser);
// config and lang related
void LoadConfig (const wxString & file);
void SaveConfig (const wxString & file);
void LoadLang (const wxString & file);
void SetupPalette (const wxString & filename);
bool IsShuttingDown () { return m_shutdown; }
private :
CManager ();
~CManager ();
// disable copying
void operator = (CManager &) {};
// private data implementation "pimpl"
struct CData;
std::auto_ptr<CData> m_data;
bool m_shutdown;
};
}
#endif // MANAGER_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Editor/StyleInfo.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Default values
*/
static const int StyleDefaultFontSize = 10;
static const char * StyleDefaultForeColor = "black";
static const char * StyleDefaultBackColor = "white";
static const char * StyleDefaultFont = "Courier New";
/**
* Contain styling information for
* a single rule
*/
struct SDK_DLL StyleInfo
{
bool isOk;
bool bold;
bool italic;
bool underlined;
int size;
int width;
int opacity;
wxString font;
wxColor fg;
wxColor bg;
wxColor outline;
// default constructor
StyleInfo ();
// get styleinfo as a string
wxString AsString () const;
};
/**
* Styl parser.
*/
class SDK_DLL StyleParser
{
public :
// construct the style info object
StyleParser (const wxString & filename = "");
// Parse the file
void LoadFile (const wxString & filename);
// Add CSS rule
void SetCssRule (
const wxString & selector,
const wxString & rule,
const wxArrayString & values,
const wxString & inheritFrom = ".default"
);
// Add CSS rule
// Same as above but only one value
void SetCssRule (
const wxString & selector,
const wxString & rule,
const wxString & value,
const wxString & inheritFrom = ".default"
);
// check if path exists
bool PathExists (const wxString & selector);
// Get styles for the selector
const StyleInfo & GetStyle (const wxString & selector, const wxString & inherit = ".default");
private :
// data structure holding style info
struct CssRule
{
wxString inheritFrom;
StringHashMap styles;
};
// get rule
wxString GetRule (CssRule & info, const wxString & rule, const wxString & selector);
// as name says
void ResetStyleInfoCache ();
// Hold the CSS rule blocks
typedef HashMap<CssRule> CssRuleMap;
// cache styleinfo based on paths
typedef HashMap<StyleInfo> StyleInfoMap;
// data
StyleInfoMap m_styleInfoMap;
CssRuleMap m_cssRuleMap;
StyleInfo m_defaultStyle;
};
}
<file_sep>/fbide-wx/sdk/src/Manager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/UiManager.h"
#include "sdk/TypeManager.h"
#include "sdk/DocManager.h"
#include "sdk/PluginManager.h"
#include "sdk/EditorManager.h"
#include "sdk/StyleInfo.h"
#include <wx/gdicmn.h>
using namespace fb;
/**
* Private data of CManager class
*/
struct CManager::CData
{
CData () : /*m_uiManager(0L), */m_typeManager(0L),
m_docManager(0L), m_pluginManager(0L),
m_frame(0L)
{}
// common typedefs
typedef std::map<wxString, int> IdMap;
typedef std::map<wxString, wxString> StrMap;
typedef std::map<wxString, CStyleParser *> CStyleMap;
// public properties
// CUiManager * m_uiManager;
CTypeManager * m_typeManager;
CDocManager * m_docManager;
CPluginManager * m_pluginManager;
wxFrame * m_frame;
CStyleMap m_stylesMap;
CRegistry m_registry;
IdMap m_idMap;
StrMap m_langMap;
};
/**
* Manager Constructor
*/
CManager::CManager () : m_data(new CManager::CData), m_shutdown(false)
{
return;
}
/**
* Manager Destructor
*
* @todo Clean up all active sub managers...
*/
CManager::~CManager ()
{
m_shutdown = true;
if (m_data->m_pluginManager != 0L) delete m_data->m_pluginManager;
if (m_data->m_docManager != 0L) delete m_data->m_docManager;
CUiManager::Free();
if (m_data->m_typeManager != 0L) delete m_data->m_typeManager;
CEditorManager::Free();
}
/**
* return CManager instance
*/
CManager * CManager::Get ()
{
static CManager * m_instance = 0L;
if (m_instance == 0L) m_instance = new CManager;
return m_instance;
}
/**
* release CManager instance
*/
void CManager::Free ()
{
delete CManager::Get();
}
/**
* Get style info
*/
CStyleParser * CManager::GetStyleParser (const wxString & name)
{
return m_data->m_stylesMap[name];
}
/**
* Add style info
*/
void CManager::SetStyleParser (const wxString & name, CStyleParser * parser)
{
m_data->m_stylesMap[name] = parser;
}
/**
* return registry object
*/
CRegistry & CManager::GetReg ()
{
return m_data->m_registry;
}
/**
* return text for value name.
*/
const wxString & CManager::GetLang (const wxString & name)
{
CData::StrMap::iterator iter = m_data->m_langMap.find(name);
if (iter == m_data->m_langMap.end()) return name;
return iter->second;
}
/**
* Register ID by name
*/
void CManager::RegisterId (const wxString & name, int id)
{
m_data->m_idMap[name] = id;
}
/**
* Get ID by name
*/
int CManager::GetId (const wxString & name)
{
CData::IdMap::iterator iter = m_data->m_idMap.find(name);
if (iter == m_data->m_idMap.end()) return wxID_ANY;
return iter->second;
}
/**
* Set application frame
*/
void CManager::SetFrame (wxFrame * frame)
{
if (0L == m_data->m_frame) m_data->m_frame = frame;
else throw EXCEPTION(_T("Frame already set"));
}
/**
* return application frame
*/
wxFrame * CManager::GetFrame ()
{
return m_data->m_frame;
}
/**
* Return instance of CUiManager
*/
CUiManager * CManager::GetUiManager()
{
return CUiManager::Get();
}
/**
* return instance of CTypeManager
*/
CTypeManager * CManager::GetTypeManager ()
{
if (m_data->m_typeManager == 0L) m_data->m_typeManager = new CTypeManager;
return m_data->m_typeManager;
}
/**
* Return instance of CDocManager
*/
CDocManager * CManager::GetDocManager ()
{
if (m_data->m_docManager == 0L) m_data->m_docManager = new CDocManager;
return m_data->m_docManager;
}
/**
* Return instance of CPluginMmanager
*/
CPluginManager * CManager::GetPluginManager ()
{
if (m_data->m_pluginManager == 0L) m_data->m_pluginManager = new CPluginManager;
return m_data->m_pluginManager;
}
/**
* Return editor manager
*/
CEditorManager * CManager::GetEditorManager ()
{
return CEditorManager::Get();
}
/**
* Load language file
*/
void CManager::LoadLang (const wxString & file)
{
if (!wxFileExists(file)) throw EXCEPTION(_T("Language file '") + file + _T("' not found!"));
wxFileInputStream is (file);
wxFileConfig ini(is);
long index = 0;
wxString entry;
if (!ini.GetFirstEntry (entry, index)) return;
do
{
m_data->m_langMap[entry] = ini.Read(entry, _T(""));
} while (ini.GetNextEntry(entry, index));
}
/**
* Load config file
*/
void CManager::LoadConfig (const wxString & file)
{
if (!wxFileExists(file)) throw EXCEPTION(_T("Config file '") + file + _T("' not found!"));
wxFileInputStream is (file);
wxFileConfig ini(is);
long index = 0;
wxString entry;
if (!ini.GetFirstEntry (entry, index)) return;
do
{
wxString value = ini.Read(entry, _T(""));
m_data->m_registry[entry] = value;
} while (ini.GetNextEntry(entry, index));
}
/**
*
*/
void CManager::SaveConfig (const wxString & file)
{
wxFileInputStream is (file);
wxFileConfig ini(is);
CRegistry::iterator iter = m_data->m_registry.begin();
while (iter != m_data->m_registry.end())
{
ini.Write(iter->first, iter->second.AsString());
iter++;
}
wxFileOutputStream os(file);
ini.Save(os);
}
/**
* Load color palette. Extend the wxColourDatabase
* to include CSS style colour names.
* @todo in the future palette should be loaded from file!
*/
void CManager::SetupPalette (const wxString & filename)
{
wxTheColourDatabase->AddColour(_T("AliceBlue"), wxColour(_T("#F0F8FF")));
wxTheColourDatabase->AddColour(_T("AntiqueWhite"), wxColour(_T("#FAEBD7")));
wxTheColourDatabase->AddColour(_T("Aqua"), wxColour(_T("#00FFFF")));
wxTheColourDatabase->AddColour(_T("Aquamarine"), wxColour(_T("#7FFFD4")));
wxTheColourDatabase->AddColour(_T("Azure"), wxColour(_T("#F0FFFF")));
wxTheColourDatabase->AddColour(_T("Beige"), wxColour(_T("#F5F5DC")));
wxTheColourDatabase->AddColour(_T("Bisque"), wxColour(_T("#FFE4C4")));
wxTheColourDatabase->AddColour(_T("Black"), wxColour(_T("#000000")));
wxTheColourDatabase->AddColour(_T("BlanchedAlmond"), wxColour(_T("#FFEBCD")));
wxTheColourDatabase->AddColour(_T("Blue"), wxColour(_T("#0000FF")));
wxTheColourDatabase->AddColour(_T("BlueViolet"), wxColour(_T("#8A2BE2")));
wxTheColourDatabase->AddColour(_T("Brown"), wxColour(_T("#A52A2A")));
wxTheColourDatabase->AddColour(_T("BurlyWood"), wxColour(_T("#DEB887")));
wxTheColourDatabase->AddColour(_T("CadetBlue"), wxColour(_T("#5F9EA0")));
wxTheColourDatabase->AddColour(_T("Chartreuse"), wxColour(_T("#7FFF00")));
wxTheColourDatabase->AddColour(_T("Chocolate"), wxColour(_T("#D2691E")));
wxTheColourDatabase->AddColour(_T("Coral"), wxColour(_T("#FF7F50")));
wxTheColourDatabase->AddColour(_T("CornflowerBlue"), wxColour(_T("#6495ED")));
wxTheColourDatabase->AddColour(_T("Cornsilk"), wxColour(_T("#FFF8DC")));
wxTheColourDatabase->AddColour(_T("Crimson"), wxColour(_T("#DC143C")));
wxTheColourDatabase->AddColour(_T("Cyan"), wxColour(_T("#00FFFF")));
wxTheColourDatabase->AddColour(_T("DarkBlue"), wxColour(_T("#00008B")));
wxTheColourDatabase->AddColour(_T("DarkCyan"), wxColour(_T("#008B8B")));
wxTheColourDatabase->AddColour(_T("DarkGoldenRod"), wxColour(_T("#B8860B")));
wxTheColourDatabase->AddColour(_T("DarkGray"), wxColour(_T("#A9A9A9")));
wxTheColourDatabase->AddColour(_T("DarkGreen"), wxColour(_T("#006400")));
wxTheColourDatabase->AddColour(_T("DarkKhaki"), wxColour(_T("#BDB76B")));
wxTheColourDatabase->AddColour(_T("DarkMagenta"), wxColour(_T("#8B008B")));
wxTheColourDatabase->AddColour(_T("DarkOliveGreen"), wxColour(_T("#556B2F")));
wxTheColourDatabase->AddColour(_T("Darkorange"), wxColour(_T("#FF8C00")));
wxTheColourDatabase->AddColour(_T("DarkOrchid"), wxColour(_T("#9932CC")));
wxTheColourDatabase->AddColour(_T("DarkRed"), wxColour(_T("#8B0000")));
wxTheColourDatabase->AddColour(_T("DarkSalmon"), wxColour(_T("#E9967A")));
wxTheColourDatabase->AddColour(_T("DarkSeaGreen"), wxColour(_T("#8FBC8F")));
wxTheColourDatabase->AddColour(_T("DarkSlateBlue"), wxColour(_T("#483D8B")));
wxTheColourDatabase->AddColour(_T("DarkSlateGray"), wxColour(_T("#2F4F4F")));
wxTheColourDatabase->AddColour(_T("DarkTurquoise"), wxColour(_T("#00CED1")));
wxTheColourDatabase->AddColour(_T("DarkViolet"), wxColour(_T("#9400D3")));
wxTheColourDatabase->AddColour(_T("DeepPink"), wxColour(_T("#FF1493")));
wxTheColourDatabase->AddColour(_T("DeepSkyBlue"), wxColour(_T("#00BFFF")));
wxTheColourDatabase->AddColour(_T("DimGray"), wxColour(_T("#696969")));
wxTheColourDatabase->AddColour(_T("DodgerBlue"), wxColour(_T("#1E90FF")));
wxTheColourDatabase->AddColour(_T("FireBrick"), wxColour(_T("#B22222")));
wxTheColourDatabase->AddColour(_T("FloralWhite"), wxColour(_T("#FFFAF0")));
wxTheColourDatabase->AddColour(_T("ForestGreen"), wxColour(_T("#228B22")));
wxTheColourDatabase->AddColour(_T("Fuchsia"), wxColour(_T("#FF00FF")));
wxTheColourDatabase->AddColour(_T("Gainsboro"), wxColour(_T("#DCDCDC")));
wxTheColourDatabase->AddColour(_T("GhostWhite"), wxColour(_T("#F8F8FF")));
wxTheColourDatabase->AddColour(_T("Gold"), wxColour(_T("#FFD700")));
wxTheColourDatabase->AddColour(_T("GoldenRod"), wxColour(_T("#DAA520")));
wxTheColourDatabase->AddColour(_T("Gray"), wxColour(_T("#808080")));
wxTheColourDatabase->AddColour(_T("Green"), wxColour(_T("#008000")));
wxTheColourDatabase->AddColour(_T("GreenYellow"), wxColour(_T("#ADFF2F")));
wxTheColourDatabase->AddColour(_T("HoneyDew"), wxColour(_T("#F0FFF0")));
wxTheColourDatabase->AddColour(_T("HotPink"), wxColour(_T("#FF69B4")));
wxTheColourDatabase->AddColour(_T("IndianRed "), wxColour(_T("#CD5C5C")));
wxTheColourDatabase->AddColour(_T("Indigo "), wxColour(_T("#4B0082")));
wxTheColourDatabase->AddColour(_T("Ivory"), wxColour(_T("#FFFFF0")));
wxTheColourDatabase->AddColour(_T("Khaki"), wxColour(_T("#F0E68C")));
wxTheColourDatabase->AddColour(_T("Lavender"), wxColour(_T("#E6E6FA")));
wxTheColourDatabase->AddColour(_T("LavenderBlush"), wxColour(_T("#FFF0F5")));
wxTheColourDatabase->AddColour(_T("LawnGreen"), wxColour(_T("#7CFC00")));
wxTheColourDatabase->AddColour(_T("LemonChiffon"), wxColour(_T("#FFFACD")));
wxTheColourDatabase->AddColour(_T("LightBlue"), wxColour(_T("#ADD8E6")));
wxTheColourDatabase->AddColour(_T("LightCoral"), wxColour(_T("#F08080")));
wxTheColourDatabase->AddColour(_T("LightCyan"), wxColour(_T("#E0FFFF")));
wxTheColourDatabase->AddColour(_T("LightGoldenRodYellow"), wxColour(_T("#FAFAD2")));
wxTheColourDatabase->AddColour(_T("LightGrey"), wxColour(_T("#D3D3D3")));
wxTheColourDatabase->AddColour(_T("LightGreen"), wxColour(_T("#90EE90")));
wxTheColourDatabase->AddColour(_T("LightPink"), wxColour(_T("#FFB6C1")));
wxTheColourDatabase->AddColour(_T("LightSalmon"), wxColour(_T("#FFA07A")));
wxTheColourDatabase->AddColour(_T("LightSeaGreen"), wxColour(_T("#20B2AA")));
wxTheColourDatabase->AddColour(_T("LightSkyBlue"), wxColour(_T("#87CEFA")));
wxTheColourDatabase->AddColour(_T("LightSlateGray"), wxColour(_T("#778899")));
wxTheColourDatabase->AddColour(_T("LightSteelBlue"), wxColour(_T("#B0C4DE")));
wxTheColourDatabase->AddColour(_T("LightYellow"), wxColour(_T("#FFFFE0")));
wxTheColourDatabase->AddColour(_T("Lime"), wxColour(_T("#00FF00")));
wxTheColourDatabase->AddColour(_T("LimeGreen"), wxColour(_T("#32CD32")));
wxTheColourDatabase->AddColour(_T("Linen"), wxColour(_T("#FAF0E6")));
wxTheColourDatabase->AddColour(_T("Magenta"), wxColour(_T("#FF00FF")));
wxTheColourDatabase->AddColour(_T("Maroon"), wxColour(_T("#800000")));
wxTheColourDatabase->AddColour(_T("MediumAquaMarine"), wxColour(_T("#66CDAA")));
wxTheColourDatabase->AddColour(_T("MediumBlue"), wxColour(_T("#0000CD")));
wxTheColourDatabase->AddColour(_T("MediumOrchid"), wxColour(_T("#BA55D3")));
wxTheColourDatabase->AddColour(_T("MediumPurple"), wxColour(_T("#9370D8")));
wxTheColourDatabase->AddColour(_T("MediumSeaGreen"), wxColour(_T("#3CB371")));
wxTheColourDatabase->AddColour(_T("MediumSlateBlue"), wxColour(_T("#7B68EE")));
wxTheColourDatabase->AddColour(_T("MediumSpringGreen"), wxColour(_T("#00FA9A")));
wxTheColourDatabase->AddColour(_T("MediumTurquoise"), wxColour(_T("#48D1CC")));
wxTheColourDatabase->AddColour(_T("MediumVioletRed"), wxColour(_T("#C71585")));
wxTheColourDatabase->AddColour(_T("MidnightBlue"), wxColour(_T("#191970")));
wxTheColourDatabase->AddColour(_T("MintCream"), wxColour(_T("#F5FFFA")));
wxTheColourDatabase->AddColour(_T("MistyRose"), wxColour(_T("#FFE4E1")));
wxTheColourDatabase->AddColour(_T("Moccasin"), wxColour(_T("#FFE4B5")));
wxTheColourDatabase->AddColour(_T("NavajoWhite"), wxColour(_T("#FFDEAD")));
wxTheColourDatabase->AddColour(_T("Navy"), wxColour(_T("#000080")));
wxTheColourDatabase->AddColour(_T("OldLace"), wxColour(_T("#FDF5E6")));
wxTheColourDatabase->AddColour(_T("Olive"), wxColour(_T("#808000")));
wxTheColourDatabase->AddColour(_T("OliveDrab"), wxColour(_T("#6B8E23")));
wxTheColourDatabase->AddColour(_T("Orange"), wxColour(_T("#FFA500")));
wxTheColourDatabase->AddColour(_T("OrangeRed"), wxColour(_T("#FF4500")));
wxTheColourDatabase->AddColour(_T("Orchid"), wxColour(_T("#DA70D6")));
wxTheColourDatabase->AddColour(_T("PaleGoldenRod"), wxColour(_T("#EEE8AA")));
wxTheColourDatabase->AddColour(_T("PaleGreen"), wxColour(_T("#98FB98")));
wxTheColourDatabase->AddColour(_T("PaleTurquoise"), wxColour(_T("#AFEEEE")));
wxTheColourDatabase->AddColour(_T("PaleVioletRed"), wxColour(_T("#D87093")));
wxTheColourDatabase->AddColour(_T("PapayaWhip"), wxColour(_T("#FFEFD5")));
wxTheColourDatabase->AddColour(_T("PeachPuff"), wxColour(_T("#FFDAB9")));
wxTheColourDatabase->AddColour(_T("Peru"), wxColour(_T("#CD853F")));
wxTheColourDatabase->AddColour(_T("Pink"), wxColour(_T("#FFC0CB")));
wxTheColourDatabase->AddColour(_T("Plum"), wxColour(_T("#DDA0DD")));
wxTheColourDatabase->AddColour(_T("PowderBlue"), wxColour(_T("#B0E0E6")));
wxTheColourDatabase->AddColour(_T("Purple"), wxColour(_T("#800080")));
wxTheColourDatabase->AddColour(_T("Red"), wxColour(_T("#FF0000")));
wxTheColourDatabase->AddColour(_T("RosyBrown"), wxColour(_T("#BC8F8F")));
wxTheColourDatabase->AddColour(_T("RoyalBlue"), wxColour(_T("#4169E1")));
wxTheColourDatabase->AddColour(_T("SaddleBrown"), wxColour(_T("#8B4513")));
wxTheColourDatabase->AddColour(_T("Salmon"), wxColour(_T("#FA8072")));
wxTheColourDatabase->AddColour(_T("SandyBrown"), wxColour(_T("#F4A460")));
wxTheColourDatabase->AddColour(_T("SeaGreen"), wxColour(_T("#2E8B57")));
wxTheColourDatabase->AddColour(_T("SeaShell"), wxColour(_T("#FFF5EE")));
wxTheColourDatabase->AddColour(_T("Sienna"), wxColour(_T("#A0522D")));
wxTheColourDatabase->AddColour(_T("Silver"), wxColour(_T("#C0C0C0")));
wxTheColourDatabase->AddColour(_T("SkyBlue"), wxColour(_T("#87CEEB")));
wxTheColourDatabase->AddColour(_T("SlateBlue"), wxColour(_T("#6A5ACD")));
wxTheColourDatabase->AddColour(_T("SlateGray"), wxColour(_T("#708090")));
wxTheColourDatabase->AddColour(_T("Snow"), wxColour(_T("#FFFAFA")));
wxTheColourDatabase->AddColour(_T("SpringGreen"), wxColour(_T("#00FF7F")));
wxTheColourDatabase->AddColour(_T("SteelBlue"), wxColour(_T("#4682B4")));
wxTheColourDatabase->AddColour(_T("Tan"), wxColour(_T("#D2B48C")));
wxTheColourDatabase->AddColour(_T("Teal"), wxColour(_T("#008080")));
wxTheColourDatabase->AddColour(_T("Thistle"), wxColour(_T("#D8BFD8")));
wxTheColourDatabase->AddColour(_T("Tomato"), wxColour(_T("#FF6347")));
wxTheColourDatabase->AddColour(_T("Turquoise"), wxColour(_T("#40E0D0")));
wxTheColourDatabase->AddColour(_T("Violet"), wxColour(_T("#EE82EE")));
wxTheColourDatabase->AddColour(_T("Wheat"), wxColour(_T("#F5DEB3")));
wxTheColourDatabase->AddColour(_T("White"), wxColour(_T("#FFFFFF")));
wxTheColourDatabase->AddColour(_T("WhiteSmoke"), wxColour(_T("#F5F5F5")));
wxTheColourDatabase->AddColour(_T("Yellow"), wxColour(_T("#FFFF00")));
wxTheColourDatabase->AddColour(_T("YellowGreen"), wxColour(_T("#9ACD32")));
}
<file_sep>/fbide-vs/Sdk/CmdManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
// check event
wxDECLARE_EXPORTED_EVENT(SDK_DLL, fbiCMD_CHECK, wxCommandEvent);
wxDECLARE_EXPORTED_EVENT(SDK_DLL, fbiCMD_ENABLE, wxCommandEvent);
/**
* Command manager is used for mapping between textual name and ID value
* mainly used by xml loader in UiManager.
* It alos provides a way to bind UI elements (check item, menus, dropdowns, ...) to
* the IDs so that UI loader knows how to handle such special cases.
*/
class SDK_DLL CmdManager : public wxEvtHandler, public NonCopyable
{
public :
// data structure to hold information
struct Entry {
int id; // numeric ID
int type; // type
bool checked; // For Entry_Check
bool enabled; // is control enabled ?
wxObject * object; // the control pointer
};
// Entry types
enum Type {
Type_Normal,
Type_Check,
Type_Menu
};
// Retreave registered id
// if doesn't exist will return new id value and log a warning
virtual int GetId (const wxString & name) = 0;
// Get entry for the given name. If doesn't exist log a warning and create
// a default entyr
virtual Entry & GetEntry (const wxString & name) = 0;
// retreave the entry for the given name. nullptr if doesn't exist
virtual Entry * FindEntry (const wxString & name) = 0;
// retreave entry by registered numeric ID
virtual Entry * FindEntry (int id) = 0;
// register id
virtual void Register (const wxString & name, int id,
CmdManager::Type type = CmdManager::Type_Normal,
wxObject * object = nullptr, bool checked = false, bool enabled = true) = 0;
// check if id is registred
virtual bool IsRegistered (const wxString & name) = 0;
// unregister the id
virtual void UnRegister (const wxString & name) = 0;
// toggle the checkbox
virtual void Check (const wxString & name, bool state) = 0;
// toggle checkbox identified by numeric ID
virtual void Check (int id, bool state) = 0;
// enable / disable signal by name
virtual void Enable (const wxString & name, bool state) = 0;
// enable / disable signal by numeric id
virtual void Enable (int id, bool state) = 0;
// declare the manager
DECLARE_MANAGER(CmdManager)
};
}
<file_sep>/fbide-wx/sdk/include/sdk/PluginArtProvider.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef PLUGINARTPROVIDER_H_INCLUDED
#define PLUGINARTPROVIDER_H_INCLUDED
#include "sdk/PluginManager.h"
#include "sdk/ArtProvider.h"
#include "sdk/Manager.h"
#include "sdk/UiManager.h"
namespace fb {
/**
* Simple Template to ease the Artproviders plugins
*/
template<class T> class CPluginArtProviderBase : public CPluginBase
{
protected :
Delegate<void(IArtProvider*)> m_onChange;
T m_provider;
typedef CPluginArtProviderBase<T> Self;
public :
/**
* Activate
*/
bool Attach ()
{
m_onChange = MakeDelegate(this, &Self::OnChange);
GET_UIMGR()->SetArtProvider(&m_provider);
GET_UIMGR()->onArtProvderChange += m_onChange;
return true;
}
/**
* Deactivate
*/
bool Detach (bool force)
{
if (GET_UIMGR()->GetArtProvider() == &m_provider)
{
GET_UIMGR()->onArtProvderChange -= m_onChange;
GET_UIMGR()->SetArtProvider(NULL);
}
return true;
}
/**
* Event callback
*/
void OnChange (IArtProvider * provider)
{
if (provider == &m_provider) return;
GET_UIMGR()->onArtProvderChange -= m_onChange;
}
};
/**
* Plugin registrant shorthand.
* use:
* CPluginArtProvider<ArtProviderClass> plugin (_T("PluginName"));
*/
template<class T> class CPluginArtProvider :
public CPluginProvider<CPluginArtProviderBase<T>, PLUGINTYPE_ARTPROVIDER>
{
private :
typedef CPluginProvider<CPluginArtProviderBase<T>, PLUGINTYPE_ARTPROVIDER> parent;
public :
CPluginArtProvider<T> (const wxString& name) : parent(name) {}
virtual ~CPluginArtProvider<T> () {}
};
}
#endif // PLUGINARTPROVIDER_H_INCLUDED
<file_sep>/fbide-wx/Plugins/FBIdePlugin/LineStates.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*
* This file is based on VB lexer for Scintilla by
* <NAME> <<EMAIL>>
*/
#include "LineStates.h"
// construct new object
CLineStates::CLineStates () :
m_nullState(-1, -1, 0, 0),
m_lineMax(0)
{
// push back so maps could have a valid iterators
m_allStates.push_back(m_nullState);
}
// clear states from the given line
void CLineStates::ClearFrom (int line)
{
// Remove block states
if (m_allStates.size() > 1) // skip first one
{
CStateInfoList::iterator iter = ++m_allStates.begin();
for ( ; iter != m_allStates.end(); )
{
CStateInfoList::iterator tmp = iter++;
if (tmp->lineOpen >= line)
{
m_allStates.erase (tmp);
break;
}
else if (iter->lineClose < line)
{
tmp->lineClose = -1;
}
}
}
// remove lines.
if (line <= m_lineMax)
{
// remove lines
CLineStateVector::iterator iter = m_lineStates.begin();
m_lineMax = 0;
for ( ; iter != m_lineStates.end(); iter++)
{
if (iter->first >= line)
{
m_lineStates.erase(iter, m_lineStates.end());
return;
}
m_lineMax = iter->first;
}
}
}
<file_sep>/fbide-vs/App/app_pch.cpp
/**
* Precompiled header implementation for Visual C++
*/
#include "app_pch.h"
<file_sep>/fbide-wx/Plugins/WebBrowser/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/TypeManager.h"
#include "webdoc.h"
#include <wx/stdpaths.h>
#include <wx/dir.h>
using namespace fb;
struct WebBrowser : public CPluginBase
{
// Attach plugin
bool Attach ()
{
// init the XUL path
wxString xulrunner_path = FindXulRunner(wxT("ide\\xr"));
if (xulrunner_path.IsEmpty())
{
wxMessageBox(wxT("Could not find xulrunner directory"));
return false;
}
// Finally, initialize the engine; Calling wxWebControl::InitEngine()
// is very important and has to be made before using wxWebControl.
// It instructs wxWebConnect where the xulrunner directory is.
if (!wxWebControl::InitEngine(xulrunner_path))
{
wxMessageBox(_T("Failed to initalize the xulrunner"));
return false;
}
// xulrunner is initalized!
CTypeManager * tm = GET_TYPEMGR();
tm->AddType(_T("text/html"), _T("HTML files"), new CTypeRegistrant<WebDoc>);
tm->BindExtensions(_T("text/html"), _T("html;htm"));
if (!tm->TypeExists(_T("default")))
tm->BindAlias(_T("default"), _T("text/html"));
return true;
}
// void
bool Detach (bool force)
{
return true;
}
/**
* find xul runner path
*
* @todo these should be in the plugin director
* ide/plugins/WebBrowser/xr
*/
wxString FindXulRunner(const wxString& xulrunner_dirname)
{
// get the location of this executable
wxString exe_path = wxStandardPaths::Get().GetExecutablePath();
wxString path_separator = wxFileName::GetPathSeparator();
exe_path = exe_path.BeforeLast(path_separator[0]);
exe_path += path_separator;
wxString path;
// first, check <exe_path>/<xulrunner_path>
path = exe_path + xulrunner_dirname;
if (wxDir::Exists(path))
return path;
// next, check <exe_path>/../<xulrunner_path>
path = exe_path + wxT("..") + path_separator + xulrunner_dirname;
if (wxDir::Exists(path))
return path;
// finally, check <exe_path>/../../<xulrunner_path>
path = exe_path + wxT("..") + path_separator + wxT("..") + path_separator + xulrunner_dirname;
if (wxDir::Exists(path))
return path;
return wxEmptyString;
}
};
namespace
{
CPluginProvider<WebBrowser, PLUGINTYPE_TOOL> plugin (_T("WebBrowser"));
}
<file_sep>/fbide-vs/Sdk/DocManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "Manager.h"
#include "DocManager.h"
#include "EditorManager.h"
#include "TypeManager.h"
#include "Editor.h"
#include "UiManager.h"
using namespace fbi;
struct Test : Document, wxTextCtrl
{
Test ()
{
Create (
GET_UIMGR()->GetDocumentArea(), wxID_ANY, "",
wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxTE_BESTWRAP
);
SetDocWindow(this);
}
};
/**
* Manager class implementation
*/
struct TheDocManager : DocManager
{
// create
TheDocManager()
{
auto frame = GET_FRAME();
frame->PushEventHandler(this);
// register some types
auto tm = GET_TYPEMGR();
// freebasic
tm->Register("freebasic", "FreeBASIC editor", DocumentCreator<Editor>);
tm->BindExtensions("freebasic", "bas;bi;");
// the default
tm->BindAlias("default", "freebasic");
}
// new document
void OnNew (wxCommandEvent & event)
{
// lock the ui to avoid any flicker
wxWindowUpdateLocker uiLock(GET_FRAME());
auto tm = GET_TYPEMGR();
auto doc = tm->CreateFromType("default");
if (doc)
{
GET_UIMGR()->AddDocument(doc);
}
}
// open document
void OnOpen (wxCommandEvent & event)
{
// vars
auto tm = GET_TYPEMGR();
auto & lang = GET_LANG();
// show file load dialog
wxString filters = tm->GetFileFilters(true);
wxFileDialog dlg (
GET_FRAME(),
lang["open-file"],
"", "", // default dir, default file
filters, // wildcards
wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE
);
if (dlg.ShowModal() != wxID_OK) return;
// get selected files
wxArrayString paths;
dlg.GetPaths(paths);
// lock ui to avoid flickering
wxWindowUpdateLocker uiLock(GET_FRAME());
// Open the files
for (size_t i = 0; i < paths.Count(); i++)
{
auto doc = tm->CreateFromFile(paths[i]);
if (doc)
{
GET_UIMGR()->AddDocument(doc);
}
}
}
// handle events
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(TheDocManager, DocManager)
EVT_MENU( wxID_NEW, TheDocManager::OnNew )
EVT_MENU( wxID_OPEN, TheDocManager::OnOpen )
END_EVENT_TABLE()
// Implement Manager
IMPLEMENT_MANAGER( DocManager, TheDocManager )
<file_sep>/fbide-vs/Sdk/TypeManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
// Forward reference
class Document;
// Typedef for document creator
typedef Document * (*DocCreatorFn)( );
// Create new automatic creator method method
// Use: DocumentCreator<MyDocumentProviderClass>
template<class T> Document * DocumentCreator( )
{
return new T();
}
/**
* Manage file types and associated loaders
* and construct load / save dialogs
*/
class SDK_DLL TypeManager : private NonCopyable
{
public:
// Register new type with fbide.
virtual void Register (const wxString & type,
const wxString & desc,
DocCreatorFn creator ) = 0;
// Bind file extensions to the type
virtual void BindExtensions (const wxString & type,
const wxString & extensions) = 0;
// Bind type alias to an existing target type or alias
// optionally allow overwriting if alias already exists
virtual void BindAlias (const wxString & alias,
const wxString & target,
bool overwrite = false ) = 0;
// Create new document. Deduct type from extension
// if failed show a dialog with an option to open the file
// with any other registered loaders or use OS to open it
// return nullptr if not opened in the editor
virtual Document * CreateFromFile (const wxString & file) = 0;
// Create new document using type name. If not registred
// return nullptr and log a warning.
virtual Document * CreateFromType (const wxString & type) = 0;
// Create new document by registered extenions.
// if multiple creators are registered show a dialog allowing
// to select the proper type.
// return nullptr and log a warning if no extension is registered
// with the type
virtual Document * CreateFromExtension (const wxString & ext) = 0;
// check if type is registered. Will resolve aliases to the
// actual type
virtual bool IsRegistered ( const wxString & type ) = 0;
// Get file filters to be used with file load / save dialogs
virtual wxString GetFileFilters ( bool incAllFiles ) = 0;
// declare this class as a manager
DECLARE_MANAGER(TypeManager)
};
}
<file_sep>/fbide-wx/sdk/include/sdk/Editor.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef EDITOR_H_INCLUDED
#define EDITOR_H_INCLUDED
#include "sdk/EventMap.h"
namespace fb
{
/**
* Forward reference StyleInfo
*/
class CStyleInfo;
class CStyleParser;
class CEditorEvent;
/**
* Base class for the editor
*/
class DLLIMPORT CEditor : public wxScintilla,
public CEventMap<int, void (CEditor &, CEditorEvent &)>
{
public :
/**
* Default constructor
*/
CEditor () : m_data(NULL) {}
/**
* construct the editor. same constructor
* as the base class
*/
CEditor (
wxWindow *parent, wxWindowID id=wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = _T("")
);
/**
* Destructor
*/
virtual ~CEditor();
/**
* Create the editor. Will call Setup()
*/
bool Create(
wxWindow *parent, wxWindowID id=wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0,
const wxString& name = _T("")
);
/**
* Set style
*/
void SetStyle (int nr, const CStyleInfo & styleInfo);
/**
* Save file
*/
void SaveFile (const wxString & file);
/**
* Load file
*/
void LoadFile (const wxString & file);
/**
* Mark editor as ready and fully loaded
*/
void MarkReady (bool state);
/**
* Get is ready state?
*/
bool GetReady ();
/**
* Setup the editor. Load general config
*/
void Setup (CStyleParser * styles);
private :
struct CData;
friend struct CData;
CData * m_data;
};
}
#endif // EDITOR_H_INCLUDED
<file_sep>/fbide-wx/TODO.txt
FBIde 0.5 todo list
* Create error handling and logging system. Throwing exceptions ain't good
nor flexible enough. Utilize wxLog functionality ?
* Create code::blocks build configurations for Linux
- Done. But need to sort out build process. Using wx-config (cool thing!)
but on my machine DEBUG build is missing (get it?)
- Create Release configuration too
* Create ANSI build mode for windows (linux too I guess? ... probably not)
* On Linux for some reason toolbars seem to be in reverse order
UiManager
===========
* RemoveToolBar and RemoveMenu methods - so plugins could unload
* HideToolBar and HideMenu - would allow setting up different contexts (hide irrelevent stuff...)
* SetArtProvider should
a) send unregister event - so any plugin could catch and
clean up
b) if refresh the art
* ReloadUi method to relead all UI elements (language, gfx)
* public string based event manager (delegates)
* The current toolbar and menu handling logic is not very flexible and requires
lot of hackish code to easily associate toolbar to a checkable menu item
and allow the state to be in sync. To clean things up all base menus and
toolbars will have fbide specific baseclass.
CUiMenu, CUiToolBar, (CUiMenuItem CUiToolbarItem - need these?)
* provide CUiStatusBar class for handling statusbar. Create CUiToolBarManager
and CUiMenuManager classes to simplify UiManager?
* Have global option "save state" or something. Where every file state (scroll position, foldings, cursor position, maybe some settings?) would be monitored.
<file_sep>/fbide-vs/Sdk/Ui/MenuHandler.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "../Manager.h"
#include "../UiManager.h"
#include "../CmdManager.h"
#include "IArtProvider.h"
#include "MenuHandler.h"
using namespace fbi;
/**
* Construct
*/
UiMenuHandler::UiMenuHandler() : m_mbar(nullptr)
{
}
// Initalize
void UiMenuHandler::Init (wxMenuBar * menubar)
{
m_mbar = menubar;
// toggle notifications
GET_CMDMGR()->Bind(fbiCMD_CHECK, &UiMenuHandler::OnCmdMgrEvent, this, wxID_ANY);
// enable / siable
GET_CMDMGR()->Bind(fbiCMD_ENABLE, &UiMenuHandler::OnCmdMgrEvent, this, wxID_ANY);
}
// Uninitalize
void UiMenuHandler::UnInit ()
{
m_mbar = nullptr;
m_map.clear();
GET_CMDMGR()->Unbind(fbiCMD_CHECK, &UiMenuHandler::OnCmdMgrEvent, this, wxID_ANY);
GET_CMDMGR()->Unbind(fbiCMD_ENABLE, &UiMenuHandler::OnCmdMgrEvent, this, wxID_ANY);
}
// check / enable items
void UiMenuHandler::OnCmdMgrEvent (wxCommandEvent & event)
{
auto item = m_mbar->FindItem(event.GetId());
if (item == nullptr) return;
if (event.GetEventType() == fbiCMD_CHECK)
{
item->Check(event.IsChecked());
}
else if (event.GetEventType() == fbiCMD_ENABLE)
{
item->Enable(event.GetInt());
}
}
/**
* Load Menu description from xml
*/
void UiMenuHandler::Load (wxXmlNode * xml, wxMenu * parent)
{
wxString id;
Manager * mgr = GET_MGR();
Language & lang = mgr->GetLang();
auto cmdMgr = mgr->GetCmdManager();
for ( ; xml; xml = xml->GetNext())
{
if (xml->GetType() == wxXML_COMMENT_NODE) continue;
// check that this is a menu entry
if (xml->GetName() == "menu")
{
// get id and check
if((id = xml->GetAttribute("id")) == "")
{
wxLogError("Id attribute missing in <menu> entry");
continue;
}
// create new menu ?
wxMenu * menu = GetMenu(id);
if (menu == nullptr)
{
auto entry = cmdMgr->FindEntry("menu." + id);
if (entry != nullptr
&& entry->type == CmdManager::Type_Menu
&& (menu = dynamic_cast<wxMenu*>(entry->object)) != nullptr);
else menu = new wxMenu();
m_map[id] = menu;
}
// Need to show
if (menu->GetParent() == nullptr && menu->GetMenuBar() == nullptr)
{
if (parent == nullptr) m_mbar->Append(menu, lang["group." + id]);
else parent->AppendSubMenu(menu, lang["group." + id]);
}
// the children
if (xml->GetChildren() != nullptr) Load(xml->GetChildren(), menu);
// next item
continue;
}
// integrity check. Follwing can only appear in <menu> block
if (parent == nullptr)
{
wxLogWarning("<menu> entry expected <%s> found", xml->GetName());
continue;
}
// the menu item
if (xml->GetName() == "item")
{
// get id and check
if((id = xml->GetAttribute("id")) == "")
{
wxLogError("Id attribute missing in <item> entry");
continue;
}
// add an item to the menu
AddMenuItem (id, parent);
}
else if (xml->GetName() == "separator")
{
parent->AppendSeparator();
}
else
{
wxLogWarning("Unknown tag in <menu> section named '<%s>'", xml->GetName());
}
}
}
// Get menu by ID
wxMenu * UiMenuHandler::GetMenu (const wxString & id)
{
auto iter = m_map.find(id);
if (iter == m_map.end()) return nullptr;
return iter->second;
}
// Add new menu
void UiMenuHandler::AddMenu (const wxString & id, wxMenu * menu, bool show)
{
assert(id != "");
assert(menu != nullptr);
if (GetMenu(id) != nullptr)
{
wxLogWarning ("Menu with id '%s' already registered", id);
return;
}
m_map[id] = menu;
if (show) m_mbar->Append(menu, GET_LANG()["group." + id]);
}
// Add a new item to the menu
void UiMenuHandler::AddMenuItem (const wxString & name, wxMenu * parent)
{
assert(parent != nullptr);
assert(name != "");
Manager * mgr = GET_MGR();
Language & lang = mgr->GetLang();
CmdManager * cmdMgr= mgr->GetCmdManager();
auto &entry = cmdMgr->GetEntry(name);
auto label = lang[name];
auto help = lang[name + ".help"];
auto art = mgr->GetUiManager()->GetArtProvider();
if (entry.type == CmdManager::Type_Normal)
{
auto item = new wxMenuItem (parent, entry.id, label, help, wxITEM_NORMAL);
if (art != NULL) item->SetBitmap(art->GetIcon(name));
parent->Append(item);
}
else if (entry.type == CmdManager::Type_Check)
{
auto item = new wxMenuItem (parent, entry.id, label, help, wxITEM_CHECK);
parent->Append(item);
item->Check(entry.checked);
// connect
// cmdMgr->Connect(name, MakeDelegate(this, &UiMenuHandler::CheckItem));
}
}
/**
* Mark the item
*/
/*
void UiMenuHandler::CheckItem(const wxString & name, CmdManager::Entry & entry)
{
auto item = m_mbar->FindItem(entry.id);
if (item == nullptr) return;
item->Check(entry.checked);
}
*/<file_sep>/fbide-vs/Sdk/CmdManager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "Manager.h"
#include "CmdManager.h"
using namespace fbi;
// check event
wxDEFINE_EVENT(fbi::fbiCMD_CHECK, wxCommandEvent);
wxDEFINE_EVENT(fbi::fbiCMD_ENABLE, wxCommandEvent);
/**
* Manager class implementation
*/
struct TheCmdManager : CmdManager
{
// Add new entry. Internal call only
inline Entry & AddEntry (const wxString & name, int id, CmdManager::Type type, wxObject * object, bool checked, bool enabled)
{
auto sp = std::make_shared<InternalEntry>();
m_map[name] = sp;
m_idMap[id] = sp;
Entry & entry = sp->m_entry;
entry.id = id;
entry.type = type;
entry.object = object;
entry.checked = checked;
entry.enabled = enabled;
return entry;
}
// Retreave registered id
// if doesn't exist will return new id value and log a warning
virtual int GetId (const wxString & name)
{
auto iter = m_map.find(name);
if (iter == m_map.end())
{
wxLogWarning("Id '%s' is not registered with CmdManager", name);
Entry & entry = AddEntry(name, ::wxNewId(), CmdManager::Type_Normal, nullptr, false, true);
return entry.id;
}
return iter->second->m_entry.id;
}
// Retreave registered control kind
virtual Entry * FindEntry (const wxString & name)
{
auto iter = m_map.find(name);
if (iter == m_map.end())
{
return nullptr;
}
return &iter->second->m_entry;
}
// retreave entry by registered numeric ID
virtual Entry * FindEntry (int id)
{
auto iter = m_idMap.find(id);
if (iter == m_idMap.end())
{
return nullptr;
}
return &iter->second->m_entry;
}
// get entry or create a default one
virtual Entry & GetEntry (const wxString & name)
{
auto iter = m_map.find(name);
if (iter == m_map.end())
{
wxLogWarning("Id '%s' is not registered with CmdManager", name);
return AddEntry(name, ::wxNewId(), CmdManager::Type_Normal, nullptr, false, true);
}
return iter->second->m_entry;
}
// register id
virtual void Register (const wxString & name, int id, CmdManager::Type type, wxObject * object, bool checked, bool enabled)
{
// Already registered?
if (m_map.find(name) != m_map.end())
{
wxLogWarning("Attempting to overwrite existing id '%s' in CmdManager", name);
return;
}
// check for integrity
if (type == CmdManager::Type_Menu && !dynamic_cast<wxMenu*>(object))
{
wxLogError("Object passed must be an instance of wxMenu");
return;
}
// insert
AddEntry(name, id, type, object, checked, enabled);
}
// check if id is registred
virtual bool IsRegistered (const wxString & name)
{
return m_map.find(name) != m_map.end();
}
// unregister the id
virtual void UnRegister (const wxString & name)
{
auto iter = m_map.find(name);
if (iter == m_map.end()) return;
m_idMap.erase(iter->second->m_entry.id);
m_map.erase(iter);
}
// toggle the checkbox
virtual void Check (const wxString & name, bool state)
{
_check(FindEntry(name), state);
}
// toggle checkbox identified by numeric ID
virtual void Check (int id, bool state)
{
_check(FindEntry(id), state);
}
// toggle the item
void _check(Entry * entry, bool state)
{
if (entry == nullptr) return;
if (entry->checked == state || entry->type != Type_Check) return;
entry->checked = state;
wxCommandEvent event(fbiCMD_CHECK, entry->id);
event.SetInt( state );
ProcessEvent(event);
}
// enable / disable item
virtual void Enable (const wxString & name, bool state)
{
_enable(FindEntry(name), state);
}
// toggle checkbox identified by numeric ID
virtual void Enable (int id, bool state)
{
_enable(FindEntry(id), state);
}
// toggle the item
void _enable(Entry * entry, bool state)
{
if (entry == nullptr) return;
if (entry->enabled == state) return;
entry->enabled = state;
wxCommandEvent event(fbiCMD_ENABLE, entry->id);
event.SetInt( state );
ProcessEvent(event);
}
// Internal data structure for entries
struct InternalEntry
{
Entry m_entry; // the public data entry
};
// data
typedef std::shared_ptr<InternalEntry> EntryPtr;
HashMap<EntryPtr> m_map; // hold name id pairs
std::unordered_map<int, EntryPtr> m_idMap; // hold association by numeric id
};
// Implement Manager
IMPLEMENT_MANAGER(CmdManager, TheCmdManager)<file_sep>/fbide-vs/Sdk/Document.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Base class for all documents
*/
class SDK_DLL Document
{
public :
/**
* Create new document
*/
Document();
/**
* Destroy document
*/
virtual ~Document();
/**
* Load file in this document
*/
virtual bool LoadDocFile (const wxString & file) { return false; }
/**
* Set document file
*/
virtual void SetDocFilename (const wxString & file) { m_filename = file; }
/**
* Get document file
*/
virtual const wxString & GetDocFilename () const { return m_filename; }
/**
* return wxWindow pointer if this
* document has a window that can be
* placed into tabbed document area.
*/
virtual wxWindow * GetDocWindow () const
{
if (m_window) return m_window;
return dynamic_cast<wxWindow *>(const_cast<Document *>(this));
}
/**
* Set document window ptr
*/
void SetDocWindow (wxWindow * wnd) { m_window = wnd; }
/**
* Title is used on the frame window and
* other plaves where file have to be
* identified by name.
*/
virtual const wxString & GetDocTitle() const { return m_title; }
/**
* Setname
*/
virtual void SetDocTitle (const wxString & name);
/**
* return unique document id
*/
inline int GetDocId () const { return m_id; }
protected:
int m_id; // document unique ID
wxString m_title; // document title
wxString m_filename; // filename associated with teh document
wxWindow * m_window; // document window ptr
};
}
<file_sep>/fbide-rw/sdk/uimanager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "manager.h"
#include "uimanager.h"
#include "wx/aui/aui.h"
using namespace fb;
/**
* Manager class implementation
*/
struct TheUiManager : UiManager, wxEvtHandler
{
// create
TheUiManager () : m_frame(NULL) {}
// destroy
~TheUiManager ()
{}
// Load user interface. Return false if failed.
virtual bool Load ()
{
m_frame = new wxFrame(
NULL, wxID_ANY, GetTitle() ,
wxDefaultPosition, wxSize(300,200)
);
wxTheApp->SetTopWindow(m_frame);
m_frame->PushEventHandler(this);
m_frame->Show();
m_aui.SetFlags(wxAUI_MGR_LIVE_RESIZE | wxAUI_MGR_DEFAULT);
m_aui.SetManagedWindow(m_frame);
m_aui.Update();
return true;
}
// Get application title
// - maybe use later a title template
// to allow customing?
virtual wxString GetTitle ()
{
return wxString("FBIde ") + GET_MGR()->GetVersion().string;
}
// get the main frame
virtual wxFrame * GetFrame ()
{
return m_frame;
}
virtual wxWindow * GetDocumentArea ()
{
return NULL;
}
// Handle close event
void OnClose (wxCloseEvent & event)
{
m_aui.UnInit();
m_frame->RemoveEventHandler(this);
m_frame->Destroy();
}
// main frame
wxFrame * m_frame;
// the wxAui manager
wxAuiManager m_aui;
// route events
DECLARE_EVENT_TABLE();
};
// event dispatching
BEGIN_EVENT_TABLE(TheUiManager, wxEvtHandler)
EVT_CLOSE(TheUiManager::OnClose)
END_EVENT_TABLE()
// Implement Manager
IMPLEMENT_MANAGER(UiManager, TheUiManager)
<file_sep>/fbide-wx/sdk/tests/test-registry.h
/**
* Check registry and variants
*/
CRegistry r;
wxString key1 = _T("key1");
const char * key2 = "key2";
const wxChar * key3 = _T("key3");
// test against "const wxChar *"
r[key1] = _T("Hello");
r[key1] += _T(" world");
wxASSERT(r[key1] == _T("Hello world"));
r[key1] += _T("!");
wxASSERT(r[key1] != _T("Hello world"));
// test against CVariant
r[key2] = r[key1];
wxASSERT(r[key2] == r[key1]);
r[key2] += r[key1];
wxASSERT(r[key2] != r[key1]);
// test against const char *
r[key3] = "const";
r[key3] += " char";
wxASSERT(r[key3] == "const char");
r[key3] += " *";
wxASSERT(r[key3] != _T("const char"));
// test against wxString
r["key4"] = wxString(_T("wx"));
r["key4"] += wxString(_T("String"));
wxASSERT(r["key4"] == wxString(_T("wxString")));
r["key4"] += wxString(_T("()"));
wxASSERT(r["key4"] != wxString(_T("wxString")));
// test against int
r["int1"] = 10;
r["int2"] = r["int1"].AsInt();
wxASSERT(r["int2"] == 10);
wxASSERT(r["int1"] != 50);
wxASSERT(r["int1"] == "10");
r["int3"] = -15;
wxASSERT(r["int3"] == "-15");
wxASSERT(r["int3"] == -15);
r["int3"] += 20;
wxASSERT(r["int3"] == 5);
// test againnst bool
r["bool1"] = true;
r["bool2"] = false;
wxASSERT(r["bool1"] == true);
wxASSERT(r["bool1"] == "true");
wxASSERT(r["bool1"] == 1);
wxASSERT(r["int3"] == true); // test against another numic value
wxASSERT(r["bool2"] != true);
r["bool4"] = (int)true;
wxASSERT(r["bool4"] == true);
wxASSERT(r["bool4"] != false);
wxASSERT(r["bool4"] == 1);
wxASSERT(r["bool4"] != 0);
wxASSERT(r["bool4"] == "1");
wxASSERT(r["bool4"] != "2");
wxASSERT(r["bool4"].AsInt() == (int)true);
r["bool5"] = false;
wxASSERT(r["bool5"] == false);
wxASSERT(r["bool5"] != true);
wxASSERT(r["bool5"] == "false");
wxASSERT(r["bool5"] != "true");
wxASSERT(r["bool5"] == 0);
r["bool6"] = (int)false;
wxASSERT(r["bool6"] == false);
wxASSERT(r["bool6"] != true);
wxASSERT(r["bool6"] == "0");
wxASSERT(r["bool6"] != "1");
wxASSERT(r["bool6"] == 0);
wxASSERT(r["bool6"] != 1);<file_sep>/fbide-vs/Sdk/Ui/ToolbarHandler.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "../Manager.h"
#include "../CmdManager.h"
#include "../UiManager.h"
#include "IArtProvider.h"
#include "MenuHandler.h"
#include "ToolbarHandler.h"
using namespace fbi;
// show / hide toolbars menu constant
const int ID_ToolbarToggle = ::wxNewId();
/**
* Construct
*/
UiToolbarHandler::UiToolbarHandler() :
m_aui(nullptr), m_parent(nullptr),
m_menu(nullptr), m_showTbars(false),
m_visibleCnt(0)
{
}
// Initalize
void UiToolbarHandler::Init (wxAuiManager * aui, bool useMenu)
{
// vars
m_aui = aui;
m_parent = m_aui->GetManagedWindow();
auto cmdMgr = GET_CMDMGR();
// bind event handlers
m_aui->Bind(wxEVT_AUI_PANE_CLOSE, &UiToolbarHandler::OnPaneClose, this, wxID_ANY);
m_parent->Bind(wxEVT_COMMAND_MENU_SELECTED, &UiToolbarHandler::OnCommandEvent, this, wxID_ANY);
// register toolbars menu
if (!cmdMgr->IsRegistered("menu.toolbars"))
{
m_menu = new wxMenu();
cmdMgr->Register("menu.toolbars", ::wxNewId(), CmdManager::Type_Menu, m_menu);
}
// toggle toolbars
if (!cmdMgr->IsRegistered("toolbars.toggle"))
{
/// @todo - read from config ?
m_showTbars = true;
cmdMgr->Register("toolbars.toggle", ID_ToolbarToggle, CmdManager::Type_Check, nullptr, true, m_showTbars);
}
else
{
m_showTbars = cmdMgr->GetEntry("toolbars.toggle").checked;
}
// don't use menus
if (!useMenu) m_menu = nullptr;
// toggle
cmdMgr->Bind(fbiCMD_CHECK, &UiToolbarHandler::OnCmdMgrEvent, this, wxID_ANY);
cmdMgr->Bind(fbiCMD_ENABLE, &UiToolbarHandler::OnCmdMgrEvent, this, wxID_ANY);
}
// toggle the checkboxes
void UiToolbarHandler::OnCmdMgrEvent(wxCommandEvent & event)
{
// allow others to catch the event
event.Skip();
// update the toolbars
wxAuiPaneInfoArray & panes = m_aui->GetAllPanes();
for (size_t iter = 0; iter < panes.Count(); iter++)
{
wxAuiPaneInfo & pane = panes[iter];
if (!pane.IsToolbar()) continue;
auto tbar = dynamic_cast<wxAuiToolBar*>(pane.window);
if (tbar == nullptr) continue;
if (event.GetEventType() == fbiCMD_CHECK)
{
tbar->ToggleTool(event.GetId(), event.IsChecked());
}
else if (event.GetEventType() == fbiCMD_ENABLE)
{
tbar->EnableTool(event.GetId(), event.IsChecked());
}
}
m_aui->Update();
}
// toolbars menu item clicked
void UiToolbarHandler::OnCommandEvent(wxCommandEvent & event)
{
// allow other event handlers to catch this event
event.Skip();
// vars
int id = event.GetId();
bool show = event.IsChecked();
// show / hide toolbars ?
if (id == ID_ToolbarToggle)
{
ToggleToolbars(event.IsChecked());
return;
}
// find the id. Skip otherwise
auto iter = m_idbridge.find(id);
if (iter == m_idbridge.end()) return;
int tbId = iter->second;
// show toolbars if they are hidden
if (!m_showTbars && show)
{
m_visibleMap[tbId] = true;
ToggleToolbars(true);
GET_CMDMGR()->Check(ID_ToolbarToggle, true);
return;
}
// iterate through the panes
wxAuiPaneInfoArray & panes = m_aui->GetAllPanes();
for (size_t iter = 0; iter < panes.Count(); iter++)
{
// if fount go and mark and return
wxAuiPaneInfo & pane = panes[iter];
if (pane.window->GetId() == tbId)
{
// mark and update aui
pane.Show(show);
if (show) m_visibleCnt ++;
else m_visibleCnt--;
m_visibleMap[tbId] = show;
m_aui->Update();
break;
}
}
// if show the toolbar and toolbars globally are hidden then update
// the "show toolbars" toggle
GET_CMDMGR()->Enable(ID_ToolbarToggle, m_visibleCnt);
}
// Close toolbar?
void UiToolbarHandler::OnPaneClose(wxAuiManagerEvent & event)
{
//event.
// allow other event handlers to catch this event by defalt
event.Skip();
// not a toolbar pane ?
if (!event.GetPane()->IsToolbar() || m_menu == nullptr) return;
// find id mapping
int tbId = event.GetPane()->window->GetId();
auto iter = m_idbridge.find(tbId);
if (iter == m_idbridge.end()) return;
// find menu item
wxMenuItem * item = m_menu->FindItem(iter->second);
if (item == nullptr) return;
// mark
event.Skip(false);
item->Check(false);
m_visibleCnt--;
m_visibleMap[tbId] = false;
// disable
if (m_visibleCnt == 0) GET_CMDMGR()->Enable(ID_ToolbarToggle, false);
}
// Show or hide the toolbars
void UiToolbarHandler::ToggleToolbars(bool show)
{
if (m_showTbars == show || m_menu == nullptr) return;
// m_showTbars = show;
for (auto iter = m_map.begin(); iter != m_map.end(); iter++)
{
// toggle the toolbar
wxAuiToolBar * tbar = iter->second;
if (m_visibleMap[tbar->GetId()])
{
m_aui->GetPane(tbar).Show(show);
m_visibleCnt += show ? 1 : -1;
// toggle associated menu command
// find ID
if (m_menu == nullptr) continue;
auto idIter = m_idbridge.find(tbar->GetId());
if (idIter == m_idbridge.end()) continue;
// find menu entry and toggle if exists
auto item = m_menu->FindItem(idIter->second);
if (item != nullptr) item->Check(show);
}
}
m_aui->Update();
m_showTbars = m_visibleCnt > 0;
}
// Uninitalize
// @todo remove all toolbar links from the menu
void UiToolbarHandler::UnInit ()
{
// Release event handlers
m_parent->Unbind(wxEVT_COMMAND_MENU_SELECTED, &UiToolbarHandler::OnCommandEvent, this, wxID_ANY);
m_aui->Unbind(wxEVT_AUI_PANE_CLOSE, &UiToolbarHandler::OnPaneClose, this, wxID_ANY);
GET_CMDMGR()->Unbind(fbiCMD_CHECK, &UiToolbarHandler::OnCmdMgrEvent, this, wxID_ANY);
GET_CMDMGR()->Unbind(fbiCMD_ENABLE, &UiToolbarHandler::OnCmdMgrEvent, this, wxID_ANY);
// clear up
m_menu = nullptr;
m_aui = nullptr;
m_parent = nullptr;
m_map.clear();
}
/**
* Load Menu description from xml
*/
void UiToolbarHandler::Load (wxXmlNode * xml)
{
// vars
wxString id;
Manager * mgr = GET_MGR();
Language & lang = mgr->GetLang();
auto art = mgr->GetUiManager()->GetArtProvider();
// styles
int style = wxAUI_TB_GRIPPER
| wxAUI_TB_HORZ_LAYOUT
| wxAUI_TB_OVERFLOW
;
if (art == nullptr) style |= wxAUI_TB_TEXT;
// iterate
for ( ; xml; xml = xml->GetNext())
{
if (xml->GetType() == wxXML_COMMENT_NODE) continue;
// check that this is a menu entry
if (xml->GetName() != "toolbar")
{
wxLogWarning("Only <toolbar> entries allowed in <toolbars> section. <%s> found", xml->GetName());
continue;
}
// empty toolbar
if (xml->GetChildren() == nullptr) continue;
// get id and check
if((id = xml->GetAttribute("id")) == "")
{
wxLogError("Id attribute missing in <toolbar> entry");
continue;
}
// add this toolbar
bool addTb = false;
// show this toolbar
bool show = xml->GetAttribute("show", "yes") == "yes";
// get tbar
wxAuiToolBar * tbar = GetToolBar(id);
if (tbar == nullptr)
{
tbar = new wxAuiToolBar (
m_parent, ::wxNewId(),
wxDefaultPosition, wxDefaultSize,
style
);
if (art) tbar->SetToolBitmapSize(art->GetIconSize());
addTb = true;
}
// iterate through children (if any) and add them to the toolbar
for (auto child = xml->GetChildren(); child; child = child->GetNext())
{
if (child->GetType() == wxXML_COMMENT_NODE) continue;
wxString tag = child->GetName();
// seperator
if (tag == "separator")
{
tbar->AddSeparator ();
}
else if (tag == "item")
{
wxString item_id = child->GetAttribute("id");
if (item_id == "")
{
wxLogError("Id attribute missing in <item> entry");
continue;
}
AddToolBarItem (item_id, tbar);
}
else
{
wxLogWarning("Unknown tag in <toolbar> section named '<%s>'", tag);
}
}
// refresh the toolbar
tbar->Realize ();
if (addTb) AddToolBar (id, tbar, show);
}
m_aui->Update();
}
// get toolbar by id
wxAuiToolBar * UiToolbarHandler::GetToolBar (const wxString & id)
{
auto iter = m_map.find(id);
if (iter == m_map.end()) return nullptr;
return iter->second;
}
// Add toolbar
void UiToolbarHandler::AddToolBar (const wxString & name, wxAuiToolBar * toolbar, bool show)
{
if (GetToolBar(name))
{
wxLogWarning("Toolbar with id '%s' already exists", name);
return;
}
m_map[name] = toolbar;
// is toolbar really visible?
bool isVisible = show && m_showTbars;
// vars
Manager * mgr = GET_MGR();
wxString label = mgr->GetLang()["toolbar." + name];
// Add to aui
m_aui->AddPane(
toolbar,
wxAuiPaneInfo().Name(name).Caption(label)
.ToolbarPane().Top().Dockable(true).Show(isVisible)
);
if (isVisible) m_visibleCnt += 1;
m_visibleMap[toolbar->GetId()] = show;
// no menu... don't bother
if (m_menu == nullptr) return;
// Add menu item
int menuId = ::wxNewId();
wxMenuItem * item = m_menu->AppendCheckItem(menuId, label);
item->Check(isVisible);
// id bridge. Is this OK? each ID should be unique ... so it should be okay
m_idbridge[toolbar->GetId()] = menuId;
m_idbridge[menuId] = toolbar->GetId();
}
/**
* Add an item to the toolbar
*/
void UiToolbarHandler::AddToolBarItem (const wxString & name, wxAuiToolBar * toolbar)
{
assert(toolbar != nullptr);
assert(name != "");
Manager * mgr = GET_MGR();
Language & lang = mgr->GetLang();
CmdManager * cmdMgr = mgr->GetCmdManager();
auto &entry = cmdMgr->GetEntry(name);
auto label = lang[name];
auto help = lang[name + ".help"];
auto art = mgr->GetUiManager()->GetArtProvider();
auto id = entry.id;
if (entry.type == CmdManager::Type_Normal)
{
wxBitmap bmp = art ? art->GetIcon(name) : wxNullBitmap;
auto tool = toolbar->AddTool(id, label, bmp, help, wxITEM_NORMAL);
tool->SetLongHelp(help);
}
else if (entry.type == CmdManager::Type_Check)
{
wxBitmap bmp = art ? art->GetIcon(name) : wxNullBitmap;
auto tool = toolbar->AddTool(id, label, bmp, help, wxITEM_CHECK);
tool->SetLongHelp(help);
toolbar->ToggleTool(id, entry.checked);
}
}
<file_sep>/tests/tests.cpp
// tests.cpp : Defines the entry point for the console application.
//
// #include "stdafx.h"
#include <iostream>
//#include "make_delegate.h"
//#include "multi_delegate.h"
#include "boost/function.hpp"
#include "boost/signals2.hpp"
using namespace std;
int main(int argc, char * argv[])
{
auto fn = [](void) { cout << "hi\n"; };
boost::signals2::signal<void ()> sig;
sig.connect(fn);
sig();
}
<file_sep>/fbide-wx/bin/Release/ide/en.ini
# Language file for FBIde
# Author: VonGodric
#
# main menus
group.file = &File
group.edit = &Edit
group.search = &Search
group.help = &Help
group.toolbars = &Toolbars
group.view = &View
# new
new = New
new.help = New document
# open
open = Open
open.help = Open existing document
# save
save = Save
save.help = Save document
# quit
quit = Quit
quit.help = Quit FBIde
# cut
cut = Cut
cut.help = Cut selection
# undo
undo = Undo
undo.help = Undo last change
# redo
redo = Redo
redo.help = Revert last change
#copy
copy = Copy
copy.help = Copy selection
# paste
paste = Paste
paste.help = Paste from clipboard
# find
find = Find
find.help = Find...
# replace
replace = Replace
replace.help = Replace...
# goto
goto = Goto
goto.help = Goto line
# about
about = About
about.help = About FBIde
# fullscreen
fullscreen = Full Screen\tF11
fullscreen.help = Toggle full screen mode
# toolbars
toolbar.common = Standard
toolbar.search = Search
toolbar.edit = Edit
# Document related...
document.unnamed= Untitled {id}
# error when file not found
# default: File '{filename}' not found.
error.file-not-found = File '{filename}' not found
# error. File type is not supported by FBIde
# default: Cannot load file '{filename}' because this type it's not supported
error.type-not-supported= Cannot load file '{filename}' because it's type is not supported
# generate "Save file" Message
save-file = Save file
save-project = Save project
save-file-as = Save file as ...
save-project-as = Save project as ...
#general "Load file" message
load-file = Open file
load-project = Open project
<file_sep>/fbide-vs/Sdk/Utilities.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Declare non copyable class
*/
struct SDK_DLL NonCopyable
{
protected:
NonCopyable() {}
~NonCopyable() {}
private: // emphasize the following members are private
NonCopyable( const NonCopyable& );
const NonCopyable& operator=( const NonCopyable& );
};
/**
* Simple instantiation of Hashmap for String bound maps.
*/
template<typename T> struct HashMap : std::unordered_map<wxString, T, wxStringHash, wxStringEqual> {};
/**
* String hash map
*/
typedef std::unordered_map<
wxString, wxString,
wxStringHash, wxStringEqual
> StringHashMap;
/**
* Template to declare singleton classes
*/
template <class T> class Singleton : public NonCopyable
{
private :
static T * m_instance;
protected :
// private constructor
Singleton()
{
assert(Singleton<T>::m_instance == nullptr);
}
// private destructor
virtual ~Singleton()
{
Singleton<T>::m_instance = nullptr;
}
public:
/**
* Return true if Singleton instance exists
*/
static inline bool HasInstance () { return m_instance != nullptr; }
/**
* Get singleton class instance. Create if doesn't exist
*/
static inline T * GetInstance()
{
if(m_instance == nullptr) m_instance = new T();
return m_instance;
}
/**
* Release existing singleton instance
*/
static inline void Release()
{
if (m_instance == nullptr) return;
delete m_instance;
m_instance = nullptr;
}
};
template<class T>T * Singleton<T>::m_instance = nullptr;
}
<file_sep>/fbide-wx/Plugins/FBIdePlugin/LineStates.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*
* This file is based on VB lexer for Scintilla by
* <NAME> <<EMAIL>>
*/
#ifndef LINESTATE_H_INCLUDED
#define LINESTATE_H_INCLUDED
#include <list>
#include <vector>
#include <utility>
/**
* this holds state info. Indent amount
*
* holds the amount to indent the code
* and the state of the block. Also opening
* and closing lines
*/
struct CStateInfo
{
int lineOpen, lineClose;
unsigned char indent, state;
// simple constructor.
CStateInfo (int open = 0, int close = 0, unsigned char _indent = 0, unsigned char _state = 0)
: lineOpen(open), lineClose(close), indent(_indent), state(_state)
{}
};
// list to hold the states
typedef std::list<CStateInfo> CStateInfoList;
// the state info range
typedef std::pair<CStateInfoList::iterator, CStateInfoList::iterator> CStateRange;
// the line - range pairs.
typedef std::pair<int, CStateRange> CLineStateInfo;
typedef std::vector<CLineStateInfo> CLineStateVector;
/**
* hold all line states.
* - code folding (can be used I'm SURE)
* - coloring the blocks
* - determining the previous state when closing the block
*/
class CLineStates
{
public :
// create new states
CLineStates ();
// Clear line state from this line
void ClearFrom (int line);
// adds the line if it doesn't yet exist
void SetLine (int line, CStateRange ** range = NULL)
{
CLineStateVector::reverse_iterator riter = m_lineStates.rbegin();
CLineStateVector::reverse_iterator rend = m_lineStates.rend();
for ( ; riter != rend ; riter-- )
{
if (riter->first < line)
{
m_lineStates.push_back(CLineStateInfo(line, riter->second));
m_lineMax = line;
if (range != NULL) *range = &m_lineStates.rbegin()->second;
return;
}
else if (riter->first == line)
{
if (range != NULL) *range = &riter->second;
return;
}
}
// m_lineStates[line] = CStateRange (m_allStates.begin(), m_allStates.begin());
m_lineStates.push_back(CLineStateInfo(line, CStateRange (m_allStates.begin(), m_allStates.begin())));
m_lineMax = line;
if (range != NULL) *range = &m_lineStates.rbegin()->second;
}
// add new state to the line
void PushState (int line, unsigned short indent, unsigned short state)
{
CStateRange & range = InitLineRange(line);
range.second = m_allStates.insert(++range.second, CStateInfo(line, -1, indent, state));
}
/**
* Set line state and return the range
*/
CStateRange & InitLineRange (int line)
{
CStateRange * p = NULL;
SetLine(line, &p);
return *p;
}
// Retreave last state in the stack (curently active)
CStateInfo GetActiveState (int line)
{
CLineStateVector::reverse_iterator riter = m_lineStates.rbegin();
CLineStateVector::reverse_iterator rend = m_lineStates.rend();
for ( ; riter != rend ; riter-- )
{
if (riter->first <= line) return *((riter->second).second);
}
return m_nullState;
}
// remove state from the line and return it
CStateInfo PopState (int line)
{
CStateRange & range = InitLineRange(line);
// no states to return...
if (range.first == range.second) return m_nullState;
// get result
CStateInfo & result = *(range.second--);
// mark the closing line
result.lineClose = line;
// ran out of states.
if (range.first == range.second)
range.first = range.second = m_allStates.insert(m_allStates.end(), m_nullState);
return result;
}
/**
* Get state range iterator
*/
CStateRange GetStateRange (int line)
{
CLineStateVector::reverse_iterator riter = m_lineStates.rbegin();
CLineStateVector::reverse_iterator rend = m_lineStates.rend();
for ( ; riter != rend ; riter-- )
{
if (riter->first <= line) return riter->second;
}
return CStateRange(m_allStates.end(), m_allStates.end());
}
public :
int m_dialect;
bool m_drawIndentedBoxes;
int m_tabWidth;
bool m_optionEscape;
private :
CStateInfoList m_allStates;
CLineStateVector m_lineStates;
int m_lineMax;
CStateInfo m_nullState;
};
#endif // LINESTATE_H_INCLUDED
<file_sep>/fbide-wx/sdk/src/Editor.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/Editor.h"
#include "sdk/StyleInfo.h"
#include "sdk/EditorEvent.h"
#include "sdk/EditorManager.h"
#include "EditorModMargin.h"
#include <stdlib.h>
// #include "sdk/LexFreeBasic.hxx"
using namespace fb;
/**
* Constants
*/
enum
{
MARGIN_LINENUMBERS = 0,
MARGIN_CHANGE = 1,
MARGIN_FOLDING = 2
};
/**
* Private data implementation for the CEditor
*/
struct CEditor::CData : public wxEvtHandler
{
// action states for modification margin
enum
{
MOD_MARGIN_MODIFY = 1,
MOD_MARGIN_UNDO_REDO
};
// simple constructor
CData (CEditor * parent)
: m_parent(parent),
m_dynamicLineNumberWidth(false),
m_changeMargin(false),
m_width3(0), m_width4(0), m_width5(0),
m_width6(0), m_width7(0),
m_modMarginState(0),
m_modMargin(0)
{
m_modMargin = new CEditorModMargin(*m_parent);
}
~CData ()
{
delete m_modMargin;
}
// On key down
void OnKeyDown ( wxKeyEvent &event )
{
event.Skip();
}
// Code was modified
void OnModified (wxScintillaEvent & event)
{
if (!m_ready) return;
// edit flags
enum
{
editFlags = wxSCI_MOD_INSERTTEXT | wxSCI_MOD_DELETETEXT,
beforeEditFlags= wxSCI_MOD_BEFOREDELETE | wxSCI_MOD_BEFOREINSERT,
undoRedoFlags = wxSCI_PERFORMED_UNDO | wxSCI_PERFORMED_REDO
};
int mod = event.GetModificationType();
int line = m_parent->LineFromPosition(event.GetPosition());
int lines = event.GetLinesAdded();
// insert or edit text
if ( mod & editFlags )
{
// performed by user
if ( mod & wxSCI_PERFORMED_USER )
{
// this is a beginning of the new action
// save the previous one.
if ( mod & wxSTI_STARTACTION )
{
// m_modMargin->SubmitChanges();
// m_modMargin->SubmitModify ();
m_modMargin->Flush();
}
// mark line as modified
m_modMargin->Modify( line, lines, CEditorModMargin::FLAG_EDITED );
m_modMarginState = MOD_MARGIN_MODIFY;
}
// performed undo or redo action
else if ( mod & undoRedoFlags )
{
// First step undo / redo
if ( m_modMarginState != MOD_MARGIN_UNDO_REDO )
{
// flush any existing lines
m_modMargin->Flush();
// set state
m_modMarginState = MOD_MARGIN_UNDO_REDO;
}
// perform undo or redo
if ( mod & wxSCI_PERFORMED_UNDO )
m_modMargin->Undo ( line, lines );
else
m_modMargin->Redo ( line, lines );
// the last step
if ( mod & wxSCI_LASTSTEPINUNDOREDO )
{
m_modMargin->ApplyMarkers();
m_modMarginState = 0;
}
}
}
// event object
bool show = false;
show = true;
if ( show )
{
bool add = false;
#define EVT_INFO(_id) if (mod & _id) { LOG_MSG(#_id); add = true; }
EVT_INFO(wxSCI_MOD_INSERTTEXT)
EVT_INFO(wxSCI_MOD_DELETETEXT)
EVT_INFO(wxSCI_PERFORMED_UNDO)
EVT_INFO(wxSCI_PERFORMED_REDO)
EVT_INFO(wxSCI_MULTISTEPUNDOREDO)
EVT_INFO(wxSCI_LASTSTEPINUNDOREDO)
EVT_INFO(wxSCI_MOD_BEFOREINSERT)
EVT_INFO(wxSCI_MOD_BEFOREDELETE)
EVT_INFO(wxSCI_MULTILINEUNDOREDO)
EVT_INFO(wxSTI_STARTACTION)
// EVT_INFO(wxSCI_MOD_CHANGEMARKER)
// EVT_INFO(wxSCI_MOD_CHANGESTYLE)
// EVT_INFO(wxSCI_MOD_CHANGEFOLD)
// EVT_INFO(wxSTI_MOD_CHANGEINDICATOR)
// EVT_INFO(wxSTI_MOD_CHANGELINESTATE)
// EVT_INFO(wxSCI_MODEVENTMASKALL)
if (add)
{
EVT_INFO(wxSCI_PERFORMED_USER)
LOG_INT(line);
LOG_INT(lines);
LOG_MSG("--------------------");
}
#undef EVT_INFO
}
}
// Update UI...
void OnUpdateUi (wxScintillaEvent & event)
{
// int line = m_parent->GetCurrentLine();
if (m_showLineNumbers && m_dynamicLineNumberWidth)
{
// get last visible line
int lastLine = m_parent->GetFirstVisibleLine() + m_parent->LinesOnScreen();
// detect width
int w = lastLine < 99 ?
m_width3 : lastLine < 999 ?
m_width4 : lastLine < 9999 ?
m_width5 : lastLine < 99999 ?
m_width6 : m_width7;
// set width
m_parent->SetMarginWidth (0, w);
}
}
// Margin was clicked. Move this to CEditor ???
void OnMarginClick ( wxScintillaEvent &event )
{
if (event.GetMargin() == MARGIN_FOLDING)
{
int lineClick = m_parent->LineFromPosition (event.GetPosition());
int levelClick = m_parent->GetFoldLevel (lineClick);
if ((levelClick & wxSCI_FOLDLEVELHEADERFLAG) > 0) {
m_parent->ToggleFold (lineClick);
}
}
}
// Character added
void OnCharAdded (wxScintillaEvent & event)
{
/*
* Indent caret to a position if \n
*/
if (m_indent && event.GetKey() == '\n')
{
wxScintilla * editor = m_parent;
int cLine = editor->GetCurrentLine();
int lineInd = editor->GetLineIndentation(cLine - 1);
editor->SetLineIndentation (cLine, lineInd);
editor->GotoPos(editor->PositionFromLine (cLine) + lineInd);
}
}
// Undo
void OnEditorEvent (wxCommandEvent & event)
{
switch (event.GetId())
{
case wxID_UNDO :
m_parent->Undo();
break;
case wxID_REDO :
m_parent->Redo();
break;
case wxID_CUT :
m_parent->Cut();
break;
case wxID_COPY :
m_parent->Copy();
break;
case wxID_PASTE :
m_parent->Paste();
break;
default :
wxLogMessage(_T("Unhandled EditorEvent"));
return;
}
// don't loose the caret
m_parent->EnsureCaretVisible();
}
// Zoom in/out
void OnZoom (wxScintillaEvent & event)
{
CalcLineMarginWidth();
if (m_showLineNumbers && !m_dynamicLineNumberWidth)
{
m_parent->SetMarginWidth (MARGIN_LINENUMBERS, m_width6);
}
}
// Calculate margin widths for dynamic line margin
void CalcLineMarginWidth ()
{
int w = m_parent->TextWidth (wxSCI_STYLE_LINENUMBER, _T("0"));
m_width3 = w * 3;
m_width4 = w * 4;
m_width5 = w * 5;
m_width6 = w * 6;
m_width7 = w * 7;
}
CEditor * m_parent; // parent class
bool m_indent; // can indent code ?
bool m_ready;
bool m_showLineNumbers;
bool m_dynamicLineNumberWidth;
bool m_changeMargin;
int m_width3;
int m_width4;
int m_width5;
int m_width6;
int m_width7;
int m_modMarginState;
// CChangeHistory m_changes;
CEditorModMargin * m_modMargin;
DECLARE_EVENT_TABLE();
};
/**
* Event routing
*/
BEGIN_EVENT_TABLE (CEditor::CData, wxEvtHandler)
// EVT_KEY_DOWN (CEditor::CData::OnKeyDown)
EVT_SCI_MODIFIED (-1, CEditor::CData::OnModified)
EVT_SCI_MARGINCLICK (-1, CEditor::CData::OnMarginClick)
EVT_SCI_CHARADDED (-1, CEditor::CData::OnCharAdded)
EVT_SCI_PAINTED (-1, CEditor::CData::OnUpdateUi)
EVT_SCI_ZOOM (-1, CEditor::CData::OnZoom)
EVT_MENU (wxID_UNDO, CEditor::CData::OnEditorEvent)
EVT_MENU (wxID_REDO, CEditor::CData::OnEditorEvent)
EVT_MENU (wxID_CUT, CEditor::CData::OnEditorEvent)
EVT_MENU (wxID_COPY, CEditor::CData::OnEditorEvent)
EVT_MENU (wxID_PASTE,CEditor::CData::OnEditorEvent)
END_EVENT_TABLE()
/**
* Construct new CEditor widget
*/
CEditor::CEditor (
wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size,
long style, const wxString& name
)
{
CEditor::Create (parent, id, pos, size, style, name);
}
/**
* Clean up.
*/
CEditor::~CEditor ()
{
wxEvtHandler::SetNextHandler(NULL);
if (m_data) delete m_data;
}
/**
* Create the editor widget
*/
bool CEditor::Create(
wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size,
long style, const wxString& name
)
{
// call parent Create method
wxScintilla::Create (parent, id, pos, size, style, name);
// private data
m_data = new CEditor::CData (this);
// Set event handler
wxEvtHandler::SetNextHandler(m_data);
}
/**
* Mark editor as ready and fully loaded
*/
void CEditor::MarkReady (bool state)
{
GET_EDITORMGR()->RegisterEditor(this);
if (m_data) m_data->m_ready = state;
}
/**
* Get is ready state?
*/
bool CEditor::GetReady ()
{
return m_data && m_data->m_ready;
}
/**
* Setup general editor configuration
* Should be called after editor is fully styled
* otherwise some sizes won't fit properly
*
* @todo have all default values come from constants that
* would be easy to change/modify/update ?
*/
void CEditor::Setup (CStyleParser * styles)
{
CRegistry & reg = GET_REG();
// set default highlight
if (styles) SetStyle(wxSCI_STYLE_DEFAULT, styles->GetStyle(_T(".default")));
// Set Tab Width
int tabWidth = reg["editor.tabWidth"].AsInt(4);
SetTabWidth (tabWidth);
// set to use tabs or spaces
SetUseTabs(reg["editor.useTabs"].AsBool(false));
// set if tab key indents or not?
SetTabIndents(reg["editor.tabIndents"].AsBool(true));
SetBackSpaceUnIndents (true); // ???
// Set Indent size
SetIndent(reg["editor.indentSize"].AsInt(tabWidth));
// Set edge column size
SetEdgeColumn(reg["editor.edgeColumnSize"].AsInt(80));
// Set edge column mode
wxString edgeModeType = reg["editor.edgeMode"].AsString(_T("line"));
int edgeMode = wxSCI_EDGE_NONE;
if (edgeModeType==_T("line")) edgeMode = wxSCI_EDGE_LINE;
else if (edgeModeType==_T("background")) edgeMode = wxSCI_EDGE_BACKGROUND;
SetEdgeMode (edgeMode);
// Set EOL mode
wxString eolModeType = reg["editor.eolMode"].AsString();
int eolMode = wxSCI_EOL_CRLF;
if (eolModeType == _T("CR"))
eolMode = wxSCI_EOL_CR;
else if (eolModeType == _T("LF"))
eolMode = wxSCI_EOL_LF;
SetEOLMode(eolMode);
// view EOL characters ?
SetViewEOL(reg["editor.viewEOL"].AsBool());
// show indent guides ?
SetIndentationGuides(reg["editor.indentationGuides"].AsBool());
// Show whitespaces ?
SetViewWhiteSpace (
reg["editor.viewWhiteSpace"].AsBool()
? wxSCI_WS_VISIBLEALWAYS : wxSCI_WS_INVISIBLE
);
// show line numbers ?
if (reg["editor.showLineNumbers"].AsBool(true))
{
// line numbers
if (styles && styles->PathExists(_T(".line-margin")))
{
SetStyle(wxSCI_STYLE_LINENUMBER, styles->GetStyle(_T(".line-margin")));
}
// calculate line widths
bool dyn = m_data->m_dynamicLineNumberWidth = reg["editor.dynamicLineNumberWidth"].AsBool(true);
m_data->CalcLineMarginWidth();
SetMarginWidth (MARGIN_LINENUMBERS, dyn ? m_data->m_width3 : m_data->m_width6);
SetMarginType(MARGIN_LINENUMBERS, wxSCI_MARGIN_NUMBER);
m_data->m_showLineNumbers = true;
}
else SetMarginWidth (MARGIN_LINENUMBERS,0);
// caret
if (styles && styles->PathExists(_T(".caret")))
{
CStyleInfo info = styles->GetStyle(_T(".caret"));
SetCaretForeground(info.fg);
SetCaretWidth(info.width ? info.width : 1);
/**
* @todo figure out why alpha doesn't work
*/
/*
if (reg["editor.highlightCurrentLine"].AsBool(true))
{
if (info.bg.IsOk())
{
SetCaretLineVisible(true);
SetCaretLineBackground(info.bg);
if (info.opacity)
{
SetCaretLineBackAlpha(info.opacity);
}
}
}
*/
}
// Auto indent code
if (m_data)
{
m_data->m_indent = reg["editor.autoIndent"].AsBool(false);
}
// Code folding
if (reg["editor.codeFolding"].AsBool(false))
{
// void SetFoldMarginColour(bool useSetting, const wxColour& back);
// void SetFoldMarginHiColour(bool useSetting, const wxColour& fore);
CStyleInfo info = styles->GetStyle(_T(".fold-margin"));
SetMarginWidth (MARGIN_FOLDING, info.width ? info.width : 12);
SetMarginType (MARGIN_FOLDING, wxSCI_MARGIN_SYMBOL);
SetMarginMask (MARGIN_FOLDING, wxSCI_MASK_FOLDERS);
wxColor & outline = info.fg;
wxColor & fore = info.bg;
SetFoldFlags(wxSCI_FOLDFLAG_LINEAFTER_CONTRACTED);
MarkerDefine(wxSCI_MARKNUM_FOLDER, wxSCI_MARK_BOXPLUS, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEREND, wxSCI_MARK_BOXPLUSCONNECTED,fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERMIDTAIL, wxSCI_MARK_TCORNER, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEROPEN, wxSCI_MARK_BOXMINUS, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDEROPENMID, wxSCI_MARK_BOXMINUSCONNECTED,fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERSUB, wxSCI_MARK_VLINE, fore, outline);
MarkerDefine(wxSCI_MARKNUM_FOLDERTAIL, wxSCI_MARK_LCORNER, fore, outline);
SetMarginSensitive (MARGIN_FOLDING, 1);
SetProperty (_T("fold"), _T("1"));
SetProperty (_T("fold.comment"), _T("1"));
SetProperty (_T("fold.compact"), _T("1"));
SetProperty (_T("fold.preprocessor"), _T("1"));
}
// Show modification margin
if (reg["editor.showChangeMargin"].AsBool(true))
{
const CStyleInfo & info = styles->GetStyle(_T(".edit-margin"));
m_data->m_changeMargin = true;
SetMarginWidth(MARGIN_CHANGE, 4);
SetMarginType(MARGIN_CHANGE, wxSCI_MARGIN_SYMBOL);
SetMarginWidth(MARGIN_CHANGE, 4);
SetMarginMask(MARGIN_CHANGE, (1 << CEditorModMargin::MARKER_SAVED) | (1 << CEditorModMargin::MARKER_EDITED) );
// edited marker
MarkerDefine(CEditorModMargin::MARKER_EDITED, wxSCI_MARK_FULLRECT);
MarkerSetBackground(CEditorModMargin::MARKER_EDITED, info.bg);
// saved marker
MarkerDefine(CEditorModMargin::MARKER_SAVED, wxSCI_MARK_FULLRECT);
MarkerSetBackground(CEditorModMargin::MARKER_SAVED, info.fg);
}
// process TAB key manually to allow
// adding switching between tabs ????
// CmdKeyClear (wxSCI_KEY_TAB, 0);
}
/**
* Set style
*/
void CEditor::SetStyle (int nr, const CStyleInfo & styleInfo)
{
StyleSetFaceName (nr, styleInfo.font);
StyleSetSize (nr, styleInfo.size);
StyleSetItalic (nr, styleInfo.italic);
StyleSetBold (nr, styleInfo.bold);
StyleSetUnderline (nr, styleInfo.underlined);
StyleSetForeground (nr, styleInfo.fg);
StyleSetBackground (nr, styleInfo.bg);
}
/**
* Save the file
*/
void CEditor::SaveFile (const wxString & file)
{
wxScintilla::SaveFile(file);
m_data->m_modMargin->SetSavePos ( );
}
/**
* Load file
*/
void CEditor::LoadFile (const wxString & file)
{
m_data->m_ready = false;
wxScintilla::LoadFile(file);
m_data->m_ready = true;
}
<file_sep>/fbide-wx/sdk/include/sdk/sdk_pch.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef SDK_PCH_H_INCLUDED
#define SDK_PCH_H_INCLUDED
// wxWudgets headers
#include <wx/wxprec.h>
#include <wx/hashmap.h>
#include <wx/filename.h>
#include <wx/button.h>
#include <wx/aui/aui.h>
#include <wx/xml/xml.h>
#include <wx/fileconf.h>
#include <wx/wfstream.h>
#include <wx/artprov.h>
#include <wx/aui/auibook.h>
#include <wx/variant.h>
#include <wx/dynlib.h>
#include <wx/log.h>
#include <wx/wxscintilla.h>
// Include STL
#include <memory>
#include <map>
#include <vector>
// FBIde specific global headers
#include "sdk/sdk.h"
#include "sdk/Exception.h"
#include "sdk/MultiDelegate.h"
#include "sdk/Log.h"
namespace fb
{
// Global declarations
WX_DECLARE_HASH_MAP(wxString, wxString, wxStringHash, wxStringEqual, CStringStringHashMap);
WX_DECLARE_STRING_HASH_MAP(int, wxStringIntMap);
};
#endif // WX_PCH_H_INCLUDED
<file_sep>/fbide-wx/sdk/src/Exception.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Exception.h"
/**
* Show messagebox conatining exception message
*/
void ShowException (const wxString & msg)
{
wxMessageBox(msg, _T("FATAL ERROR: Uncought exception"), wxICON_ERROR);
}
/**
* Show the exception information
*/
void ShowException (const CException & e)
{
// WIERD! << stream operator BROKEN ?
wxString tmp;
tmp.Printf(wxT("%d"), e.GetLine());
wxString msg = e.GetMessage();
msg << _T("\n\n") << e.GetMethod();
msg << _T("\n") << e.GetFile() << _T(" (") << tmp << _T(")");
ShowException (msg);
}
<file_sep>/fbide-wx/sdk/include/sdk/DocManager.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef DOCMANAGER_H_INCLUDED
#define DOCMANAGER_H_INCLUDED
namespace fb
{
/**
* Forward references
*/
class CManager;
class CDocumentBase;
/**
* This manager handles the open documens.
* Keeps a list, forwards the save, open and etc
* events. Does not handle document specific logic.
*
* Can be accessed only through CManager class
*/
class DLLIMPORT CDocManager : public wxEvtHandler
{
public :
bool CloseAll ();
CDocumentBase * FindDocument (wxWindow * wnd);
CDocumentBase * Open (const wxString & filename, bool show = true);
void Open (const wxArrayString & filenames);
private :
friend class CManager;
CDocManager ();
~CDocManager ();
struct CData;
CData * m_data;
};
}
#endif // DOCMANAGER_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Ui/ClassicThemeProvider.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "IArtProvider.h"
#include "ClassicThemeProvider.h"
using namespace fbi;
namespace XPM {
#include "xpm/xpm_tango/newsrc.xpm"
#include "xpm/xpm_tango/opnproj.xpm"
#include "xpm/xpm_tango/save.xpm"
#include "xpm/xpm_tango/close.xpm"
#include "xpm/xpm_tango/undo.xpm"
#include "xpm/xpm_tango/redo.xpm"
#include "xpm/xpm_tango/cut.xpm"
#include "xpm/xpm_tango/copy.xpm"
#include "xpm/xpm_tango/paste.xpm"
#include "xpm/xpm_tango/search.xpm"
#include "xpm/xpm_tango/srchrep.xpm"
#include "xpm/xpm_tango/xpm_goto.xpm"
#include "xpm/xpm_tango/screen.xpm"
#include "xpm/xpm_tango/about.xpm"
#include "xpm/xpm_tango/empty.xpm"
}
// construct
ClassicThemeProvider::ClassicThemeProvider ()
{
// we use only xpm's so...
m_bitmaps["new"] = new wxBitmap (XPM::newsrc);
m_bitmaps["open"] = new wxBitmap (XPM::opnproj);
m_bitmaps["save"] = new wxBitmap (XPM::save);
m_bitmaps["quit"] = new wxBitmap (XPM::close);
m_bitmaps["undo"] = new wxBitmap (XPM::undo);
m_bitmaps["redo"] = new wxBitmap (XPM::redo);
m_bitmaps["cut"] = new wxBitmap (XPM::cut);
m_bitmaps["copy"] = new wxBitmap (XPM::copy);
m_bitmaps["paste"] = new wxBitmap (XPM::paste);
m_bitmaps["find"] = new wxBitmap (XPM::search);
m_bitmaps["replace"] = new wxBitmap (XPM::srchrep);
m_bitmaps["goto"] = new wxBitmap (XPM::xpm_goto);
m_bitmaps["about"] = new wxBitmap (XPM::about);
m_bitmaps["log"] = new wxBitmap (XPM::screen);
m_bitmaps["icon.empty"]= new wxBitmap (XPM::empty);
for (auto iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
iter->second->SetMask(new wxMask(*iter->second, wxColour(191, 191, 191)));
}
}
// destroy
ClassicThemeProvider::~ClassicThemeProvider()
{
for (auto iter = m_bitmaps.begin(); iter != m_bitmaps.end(); iter++)
{
delete iter->second;
}
}
/**
* Get icon
*/
wxBitmap ClassicThemeProvider::GetIcon (const wxString & name, int size)
{
auto iter = m_bitmaps.find(name);
if (iter != m_bitmaps.end()) return *iter->second;
return *m_bitmaps["icon.empty"];
}
/**
* get icon size
*/
wxSize ClassicThemeProvider::GetIconSize (int type)
{
return wxSize(16, 16);
}
<file_sep>/fbide-wx/Plugins/WebBrowser/webdoc.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/UiManager.h"
#include "webdoc.h"
#include <wx/stdpaths.h>
#include <wx/dir.h>
/**
* contruct the wen view
*/
WebDoc::WebDoc(const wxString & file)
: m_browser(NULL)
{
// construct the editor
wxPanel::Create (
GET_UIMGR()->GetDocWindow(),
wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_SIMPLE
);
// for the example, disable cookies and popups
wxWebPreferences webprefs = wxWebControl::GetPreferences();
webprefs.SetIntPref(wxT("network.cookie.cookieBehavior"), 2 /* disable all cookies */);
webprefs.SetIntPref(wxT("privacy.popups.policy"), 2 /* reject popups */);
m_browser = new wxWebControl(this, -1);
m_browser->OpenURI(_T("http://www.google.co.uk"));
m_browser->Show();
Show();
if (!m_browser->IsOk())
{
wxMessageBox(_T("NOT OKAY"));
}
}
<file_sep>/fbide-vs/Sdk/MultiSplitter.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
#include <wx/splitter.h>
namespace fbi
{
/**
* Region names for associated panes
*/
enum MultiSplitRegion
{
MULTISPLIT_TOP_LEFT = 1,
MULTISPLIT_TOP_RIGHT = 2,
MULTISPLIT_BOTTOM_LEFT = 4,
MULTISPLIT_BOTTOM_Right = 8
};
/**
* Action states
*/
enum MultiSplitDrag
{
MULTISPLIT_DRAG_NONE,
MULTISPLIT_DRAG_HORIZONTAL,
MULTISPLIT_DRAG_VERTICAL,
MULTISPLIT_DRAG_BOTH,
MULTISPLIT_DRAG_LEFT_DOWN
};
/**
* This container is similar to wxSplitWindow except it
* is able to handle 1 to 4 panes.
* Each pane is associated with 4 corners. Any compination can be shown
* and this class will gigure out the proper layout.
*/
class SDK_DLL MultiSplitWindow : public wxWindow
{
public :
// window pane numbers
enum
{
PaneTopLeft,
PaneTopRight,
PaneBottomLeft,
PaneBottomRight,
};
// pane layout flags
enum
{
LayoutTopLeft = 1 << 0,
LayoutTopRight = 1 << 1,
LayoutBottomLeft = 1 << 2,
LayoutBottomRight = 1 << 3,
LayoutAll = LayoutTopLeft | LayoutTopRight | LayoutBottomLeft | LayoutBottomRight,
LayoutVerticalTop = 1 << 5,
LayoutVerticalBottom = 1 << 6,
LayoutVerticalFull = LayoutVerticalTop | LayoutVerticalBottom,
LayoutHorizontalLeft = 1 << 8,
LayoutHorizontalRight = 1 << 9,
LayoutHorizontalFull = LayoutHorizontalLeft | LayoutHorizontalRight,
};
// hit test
enum
{
DragVertical = 1 << 0,
DragHorizontal = 1 << 1,
DragBoth = DragVertical | DragHorizontal
};
// Default constructor
MultiSplitWindow()
{
Init();
}
// Normal constructor
MultiSplitWindow(wxWindow *parent, wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxSP_3D,
const wxString& name = wxT("multisplitter"))
{
Init();
Create(parent, id, pos, size, style, name);
}
// destructor
virtual ~MultiSplitWindow();
// manual construction
bool Create(wxWindow *parent, wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxSP_3D,
const wxString& name = wxT("multisplitter"));
// Get top left window
wxWindow * GetTopLeftWindow () const { return m_managed[PaneTopLeft]; }
// Get top right window
wxWindow * GetTopRightWindow () const { return m_managed[PaneTopRight]; }
// Get bottom left window
wxWindow * GetBottomLeftWindow () const { return m_managed[PaneBottomLeft]; }
// Get bottom right window
wxWindow * GetBottomRightWindow () const { return m_managed[PaneBottomRight]; }
// Generic get widnow by 0 based index
// 0 - top left, 1 - top right
// 2 - bottom left, 3 - bottom right
wxWindow * GetWindow (int index) const
{
wxASSERT_MSG((index >= 0 && index <= 3),
"Window index must be between 0 and 3");
return m_managed[index];
}
// Show top-left window
// optionally assign window pointer if it doesn't exist yet
void ShowTopLeft (wxWindow * topLeft = NULL, bool show = true) { ShowWindow(PaneTopLeft, topLeft, show); }
// Hide top-left window
void HideTopLeft (bool hide = true) { HideWindow(PaneTopLeft, hide); }
// Is top-left pane visible
bool IsTopLeftVisible () const { return IsWindowVisible( PaneTopLeft ); }
// Show top-right window
// optionally assign window pointer if it doesn't exist yet
void ShowTopRight (wxWindow * topRight = NULL, bool show = true) { ShowWindow(PaneTopRight, topRight, show); }
// Hide top-right window
void HideTopRight (bool hide = true) { HideWindow(PaneTopRight, hide); }
// Is top-right pane visible
bool IsTopRightVisible () const { return IsWindowVisible( PaneTopRight ); }
// Show bottom-left window
// optionally assign window pointer if it doesn't exist yet
void ShowBottomLeft (wxWindow * bottomLeft = NULL, bool show = true) { ShowWindow(PaneBottomLeft, bottomLeft, show); }
// Hide bottom-left window
void HideBottomLeft (bool hide = true) { HideWindow(PaneBottomLeft, hide); }
// Is bottom-left pane visible
bool IsBottomLeftVisible () const { return IsWindowVisible( PaneBottomLeft ); }
// Show bottom-right window
// optionally assign window pointer if it doesn't exist yet
void ShowBottomRight (wxWindow * bottomRight = NULL, bool show = true) { ShowWindow(PaneBottomRight, bottomRight, show); }
// Hide bottom-right window
void HideBottomRight (bool hide = true) { HideWindow(PaneBottomRight, hide); }
// Is bottom-right pane visible
bool IsBottomRightVisible () const { return IsWindowVisible( PaneBottomRight ); }
// Show window by index
// optionally assign window pointer if it doesn't exist yet
void ShowWindow (int index, wxWindow * wnd = NULL, bool show = true);
// Hide window by index
void HideWindow (int index, bool hide = true) { ShowWindow(index, NULL, !hide); }
// Is window visible ?
bool IsWindowVisible (int index ) const
{
wxASSERT(index >= 0 && index <= 3);
return m_managed[index] != nullptr && m_managed[index]->IsShown();
}
// set minimum left size
void SetMinLeftSize (int size) { m_minLeft = size; }
// get minimum left size
int GetMinLeftSize () const { return m_minLeft; }
// set minimum right size
void SetMinRightSize (int size) { m_minRight = size; }
// get minimum right size
int GetMinRightSize () const { return m_minRight; }
// set minimum top size
void SetMinTopSize (int size) { m_minTop = size; }
// get minimum top size
int GetMinTopSize () const { return m_minTop; }
// set minimum bottom size
void SetMinBottomSize (int size) { m_minBottom = size; }
// get minimum bottom size
int GetMinBottomSize () const { return m_minBottom; }
// Set minimum size
void SetMinSize ( int left, int right, int top, int bottom )
{
SetMinLeftSize(left);
SetMinRightSize(right);
SetMinTopSize(top);
SetMinBottomSize(bottom);
}
// Set vertical gravity
void SetVerticalGravity ( double gravity ) { m_vertGravity = gravity; }
// Get vertical gravity
double GetVerticalGravity () const { return m_vertGravity; }
// Set vertical gravity
void SetHorizontalGravity ( double gravity ) { m_horGravity = gravity; }
// Get vertical gravity
double GetHorizontalGravity () const { return m_horGravity; }
// Set gravity
void SetGravity (double vertical, double horizontal)
{
SetVerticalGravity( vertical );
SetHorizontalGravity( horizontal );
}
// Resize sub windows
virtual void SizeWindows();
// Gets the border size
int GetBorderSize() const;
// Get the sash size
int GetSashSize() const;
// resize
void OnSize(wxSizeEvent & event);
// Handles mouse events
void OnMouseEvent(wxMouseEvent& event);
// Aborts dragging mode
void OnMouseCaptureLost(wxMouseCaptureLostEvent& event);
// get hash at position
virtual int SashHitTest(int x, int y, int tolerance = 5);
void SetNeedUpdating(bool needUpdating) { m_needUpdating = needUpdating; }
bool GetNeedUpdating() const { return m_needUpdating ; }
protected :
// common part of all ctors
void Init();
private :
// build visible array
void SetVisiblePanes(int flags);
// set sash cursor
void SetDragCursor(int flags);
// Calculate sash positions
void CalculateSash();
// window panes that are managed
// PaneXxx flags for positions
wxWindow * m_managed[4];
// visible window panes
// PaneXxx flags for positions
wxWindow * m_visible[4];
// current state flags
int m_stateFlags;
// sash size. -1 means default size
int m_sashSize;
// vertical sash position
int m_sashVertical;
// horizontal sash position
int m_sashHorizontal;
// drag mode
int m_dragMode;
// need update?
bool m_needUpdating;
// mimum sizes
int m_minLeft, m_minRight, m_minTop, m_minBottom;
// old size
int m_oldw, m_oldh;
// gravity
double m_vertGravity, m_horGravity;
// cursor for vertical sash
wxCursor m_sashCursorWE;
// cursor for horizontal sash
wxCursor m_sashCursorNS;
// cursor for both axis
wxCursor m_sashCursorBoth;
// declarations
WX_DECLARE_CONTROL_CONTAINER();
DECLARE_DYNAMIC_CLASS(MultiSplitWindow)
DECLARE_EVENT_TABLE()
wxDECLARE_NO_COPY_CLASS(MultiSplitWindow);
};
} // ~namespace<file_sep>/fbide-wx/sdk/include/sdk/Log.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef LOG_H_INCLUDED
#define LOG_H_INCLUDED
// Log simple message
static inline void fbLogMsg(const wxString & msg)
{
wxLogMessage(_T("%s"), msg.c_str());
}
static inline void fbLogMsg(const char * msg)
{
fbLogMsg(wxString(msg, wxConvUTF8));
}
#define LOG_MSG(_msg) fbLogMsg(_msg);
// log integer
#define LOG_INT(_v) \
wxLogMessage(_T("%s = %d"), _T(#_v), (int)_v);
// log message and an integer
static inline void fbLogMsg(const wxString & msg, const wxString & var, int value)
{
// wxLogMessage(_T("%s\t\t\t(line: %d)"), msg.c_str(), line);
wxLogMessage(_T("%s %s = %d"), msg.c_str(), var.c_str(), value);
}
static inline void fbLogMsg(const char * msg, const wxString & var, int value)
{
fbLogMsg(wxString(msg, wxConvUTF8), var, value);
}
#define LOG_MSG_INT(_msg, _v) fbLogMsg(_msg, _T(#_v), (int)_v);
// log binary number
#define LOG_BIN(_n) \
{ wxString s; for (int i = (sizeof(_n) * 8)-1; i >= 0 ; i--) \
s << (_n & (1 << i) ? _T("1") : _T("0")); \
wxLogMessage(_T("%s = %s"), _T(#_n), s.c_str()); }
static inline void fbLogMsg(const wxString & msg, const wxString & var, const wxString & value)
{
// wxLogMessage(_T("%s\t\t\t(line: %d)"), msg.c_str(), line);
wxLogMessage(_T("%s %s = %s"), msg.c_str(), var.c_str(), value.c_str());
}
static inline void fbLogMsg(const char * msg, const wxString & var, const wxString & value)
{
fbLogMsg(wxString(msg, wxConvUTF8), var, value);
}
// log binary number
#define LOG_MSG_BIN(_msg, _n) \
{ wxString s; for (int i = (sizeof(_n) * 8)-1; i >= 0 ; i--) \
s << (_n & (1 << i) ? _T("1") : _T("0")); \
fbLogMsg(_msg, _T(#_n), s.c_str()); }
#endif // LOG_H_INCLUDED
<file_sep>/fbide-wx/sdk/include/sdk/Document.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef DOCUMENT_H_INCLUDED
#define DOCUMENT_H_INCLUDED
namespace fb
{
/**
* document types
*/
enum DocumentType
{
DOCUMENT_MANAGED, // is loaded into document tab area (text, rad, ...)
DOCUMENT_CUSTOM // any collection document (non tab area) projects, sessions, ...
};
/**
* Standard document events
*/
namespace DocEvent
{
const int DESTROY = 1;
const int RENAME = 2;
const int FOCUS = 3;
};
/**
* Base class for Documents
*
* In FBIde Dcoument is an abstract entity that in most
* basic sense handles the file types accordingly.
* For instance text/source files are handles in texteditor
* while project or session files open other documents and so o
*/
class DLLIMPORT CDocumentBase
{
int m_id;
int m_type;
wxString m_title;
wxString m_file;
static int NewId()
{
static int cnt = 0;
return ++cnt;
}
public :
CDocumentBase(DocumentType type) : m_id(NewId()), m_type(type) {}
virtual ~CDocumentBase() { SendDocEvent(DocEvent::DESTROY); }
/**
* this function is used to lookup if document is able to perform
* tasks specified by id (exID_SAVE - can it save or wxID_REDO - can it redo)
*/
virtual bool CanDocDo (int evtId) { return false; }
/**
* Save document
*/
virtual bool SaveDoc (const wxString & file) { return false; }
/**
* Load file in this document
*/
virtual void LoadDoc (const wxString & file) { return; }
/**
* Set document file
*/
virtual void SetDocFile (const wxString & file) { m_file = file; }
/**
* Get document file
*/
const wxString & GetDocFile () const { return m_file; }
/**
* return wxWindow pointer if this
* document has a window that can be
* placed into tabbed document area.
*/
virtual wxWindow * GetDocWindow () { return 0L; }
/**
* Title is used on the frame window and
* other plaves where file have to be
* identified by name.
*/
virtual const wxString & GetDocTitle()
{
if (!m_title.Len()) SetDocTitle (_T(""));
return m_title;
}
/**
* Setname
*/
virtual void SetDocTitle (const wxString & name);
/**
* return unique document id
*/
inline int GetDocId () const { return m_id; }
/**
* return type of the document
*/
inline int GetDocType () const { return m_type; }
/**
* Event map
*/
typedef std::map<int, CMultiDelegate<void(CDocumentBase * doc, int evt)> > DocEvtMap;
DocEvtMap evt;
/**
* send document event
*/
void SendDocEvent (int event);
};
/**
* Extender template for document types
*/
template <class T, DocumentType TYPE = DOCUMENT_CUSTOM> class CDocument : public CDocumentBase, public T
{
public :
/**
* set document type as well
*/
CDocument() : CDocumentBase(TYPE)
{
// check if this is a managable document
if (TYPE == DOCUMENT_MANAGED)
{
wxASSERT(dynamic_cast<wxWindow *>(this) != NULL);
}
}
/**
* return pointer to wxWindow object
* of the document
*/
virtual wxWindow * GetDocWindow () { return dynamic_cast<wxWindow *>(this); }
};
}
#endif // DOCUMENT_H_INCLUDED
<file_sep>/fbide-wx/sdk/include/sdk/MultiDelegate.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef MULTIDELEGATE_H_INCLUDED
#define MULTIDELEGATE_H_INCLUDED
#include "sdk/FastDelegate.h"
using namespace fastdelegate;
/**
* To simplify CMultiDelegate
* specialized templates some common
* stuff is in this base.
* also individual delegates are stored
* as void * because compiler otherwise
* seems to prove problematic when
* nested partial templates are parameters
* to one - another.
*/
template<class T> class CMultiDelegateBase
{
public :
void Add (T delegate)
{
m_list.push_back(new T(delegate));
}
void operator += (T delegate)
{
m_list.push_back(new T(delegate));
}
void Remove (T delegate)
{
Remove(&delegate);
}
void operator -= (T delegate)
{
Remove(&delegate);
}
/**
* create
*/
CMultiDelegateBase () : activeLevel(0), toCleanup(0)
{
}
/**
* Clean up
*/
virtual ~CMultiDelegateBase()
{
iterator iter = m_list.begin();
while (iter != m_list.end())
{
T * dg = reinterpret_cast<T *>(*iter);
delete dg;
iter++;
}
}
protected :
typedef std::vector<void *> list;
typedef std::vector<void *>::iterator iterator;
list m_list;
int activeLevel; //
int toCleanup;
/**
* Cleanup empty entries (caused by callee trying to remove itself
* from call list
*/
void Cleanup ()
{
if (activeLevel || !toCleanup) return;
iterator iter = m_list.begin();
while (iter != m_list.end())
{
if (*iter == NULL)
{
iter = m_list.erase(iter);
}
else
{
iter++;
}
}
toCleanup = 0;
}
private :
void Remove (T * delegate)
{
iterator iter = m_list.begin();
while (iter != m_list.end())
{
T * dg = reinterpret_cast<T *>(*iter);
if ((*dg) == *delegate)
{
delete dg;
if (activeLevel)
{
*iter = NULL;
toCleanup++;
}
else
{
iter = m_list.erase(iter);
continue;
}
}
iter++;
}
}
};
/**
* Declare this is as template class and specialize
* later on.
*/
template <typename Signature>
class CMultiDelegate;
/**
* To provide *safe* calling of delegate functions we need to wrap things
* up a bit. The problem being a callee wanting to erase itself from the
* multidelegate. This cannot be done cleanly. SO this kind of wrapping
* is required.
*/
#define DLG_CALL_START \
parent::activeLevel++; \
std::vector<void *>::iterator iter = parent::m_list.begin(); \
while (iter != parent::m_list.end()) \
{ \
type * dg = reinterpret_cast<type *>(*iter); \
if (NULL != dg)
/**
* End block. Wrap delegate method call
*/
#define DLG_CALL_END \
else if (parent::activeLevel == 1) \
{ \
iter = parent::m_list.erase(iter); \
parent::toCleanup--; \
continue; \
} \
iter++; \
} \
parent::activeLevel--; \
parent::Cleanup();
/**
* N=0
* R ();
*/
template<typename R>
class CMultiDelegate < R ( ) >
: public CMultiDelegateBase<Delegate0<R> >
{
typedef Delegate0<R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () ()
{
DLG_CALL_START
{
(*dg)();
}
DLG_CALL_END
}
};
/**
* N=1
* R (P1);
*/
template<typename R, class P1>
class CMultiDelegate < R ( P1 ) >
: public CMultiDelegateBase<Delegate1<P1, R> >
{
typedef Delegate1<P1, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1)
{
DLG_CALL_START
{
(*dg)(p1);
}
DLG_CALL_END
}
};
/**
* N=2
* R (P1, P2);
*/
template<typename R, class P1, class P2>
class CMultiDelegate < R ( P1, P2 ) >
: public CMultiDelegateBase<Delegate2<P1, P2, R> >
{
typedef Delegate2<P1, P2, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1, P2 p2)
{
DLG_CALL_START
{
(*dg)(p1, p2);
}
DLG_CALL_END
}
};
/**
* N=3
* R (P1, P2, P3);
*/
template<typename R, class P1, class P2, class P3>
class CMultiDelegate < R ( P1, P2, P3 ) >
: public CMultiDelegateBase<Delegate3<P1, P2, P3, R> >
{
typedef Delegate3<P1, P2, P3, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1, P2 p2, P3 p3)
{
DLG_CALL_START
{
(*dg)(p1, p2, p3);
}
DLG_CALL_END
}
};
/**
* N=4
* R (P1, P2, P3, P4);
*/
template<typename R, class P1, class P2, class P3, class P4>
class CMultiDelegate < R ( P1, P2, P3, P4 ) >
: public CMultiDelegateBase<Delegate4<P1, P2, P3, P4, R> >
{
typedef Delegate4<P1, P2, P3, P4, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1, P2 p2, P3 p3, P4 p4)
{
DLG_CALL_START
{
(*dg)(p1, p2, p3, p4);
}
DLG_CALL_END
}
};
/**
* N=5
* R (P1, P2, P3, P4, P5);
*/
template<typename R, class P1, class P2, class P3, class P4, class P5>
class CMultiDelegate < R ( P1, P2, P3, P4, P5 ) >
: public CMultiDelegateBase<Delegate5<P1, P2, P3, P4, P5, R> >
{
typedef Delegate5<P1, P2, P3, P4, P5, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
{
DLG_CALL_START
{
(*dg)(p1, p2, p3, p4, p5);
}
DLG_CALL_END
}
};
/**
* N=6
* R (P1, P2, P3, P4, P5, P6);
*/
template<typename R, class P1, class P2, class P3, class P4, class P5, class P6>
class CMultiDelegate < R ( P1, P2, P3, P4, P5, P6 ) >
: public CMultiDelegateBase<Delegate6<P1, P2, P3, P4, P5, P6, R> >
{
typedef Delegate6<P1, P2, P3, P4, P5, P6, R> type;
typedef CMultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6)
{
DLG_CALL_START
{
(*dg)(p1, p2, p3, p4, p5, p6);
}
DLG_CALL_END
}
};
#endif // MULTIDELEGATE_H_INCLUDED
<file_sep>/fbide-vs/Sdk/Variant.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Simple SDK specific variant class
*
* internally all are stored as strings so conversions
* between the types are possible.
*
* supported types
* - string, int, bool, float
* - wxSize, wxColour, wxPoint
*/
struct SDK_DLL Variant
{
// default constructor and destructor
Variant () {};
~Variant () {};
// Variant
Variant (const Variant & value);
void operator = (const Variant & rhs);
bool operator == (const Variant & rhs) const;
bool operator != (const Variant & rhs) const;
// wxString
Variant (const wxString & value);
void operator = (const wxString & rhs);
bool operator == (const wxString & rhs) const;
bool operator != (const wxString & rhs) const;
wxString AsString (const wxString & def = "") const;
inline operator wxString () const { return AsString(); }
// const char *
Variant (const char * value);
void operator = (const char * rhs);
bool operator == (const char * rhs) const;
bool operator != (const char * rhs) const;
// const wxChar *
Variant (const wxChar * value);
void operator = (const wxChar * rhs);
bool operator == (const wxChar * rhs) const;
bool operator != (const wxChar * rhs) const;
// integer ( works for bools too )
Variant (int value);
void operator = (int rhs);
bool operator == (int rhs) const;
bool operator != (int rhs) const;
int AsInt (int def = 0) const;
inline operator int () const { return AsInt(); }
// boolean values
bool AsBool (bool def = false) const;
// double
Variant (double value);
void operator = (double rhs);
bool operator == (double rhs) const;
bool operator != (double rhs) const;
double AsDouble (double def = 0.0) const;
inline operator double () const { return AsDouble(); }
// wxSize {w, h}
Variant (const wxSize & size);
void operator = (const wxSize & rhs);
bool operator == (const wxSize & rhs) const;
bool operator != (const wxSize & rhs) const;
wxSize AsSize (const wxSize & def = wxDefaultSize) const;
static wxString MakeString (const wxSize & size);
inline operator wxSize () const { return AsSize(); }
// wxPoint {x, y}
Variant (const wxPoint & point);
void operator = (const wxPoint & rhs);
bool operator == (const wxPoint & rhs) const;
bool operator != (const wxPoint & rhs) const;
wxPoint AsPoint (const wxPoint & def = wxDefaultPosition) const;
static wxString MakeString (const wxPoint & point);
inline operator wxPoint () const { return AsPoint(); }
// wxColour
Variant (const wxColour & colour);
void operator = (const wxColour & rhs);
bool operator == (const wxColour & rhs) const;
bool operator != (const wxColour & rhs) const;
wxColour AsColour (const wxColour & def = *wxBLACK) const;
static wxString MakeString (const wxColour & colour);
inline operator wxColour () const { return AsColour(); }
private :
wxString m_value;
};
/**
* Associative hashmap for variants
*/
typedef std::unordered_map<
wxString, Variant,
wxStringHash, wxStringEqual
> VariantHashMap;
}
<file_sep>/fbide-vs/Sdk/Editor/StyleInfo.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
#include "StyleInfo.h"
using namespace fbi;
/**
* Construct style info and set default values
*/
StyleInfo::StyleInfo () :
isOk(false),
bold(false), italic(false), underlined(false),
size(StyleDefaultFontSize), width(0), opacity(0),
font(StyleDefaultFont),
fg(StyleDefaultForeColor), bg(StyleDefaultBackColor)
{}
/**
* Get style info as a string
*/
wxString StyleInfo::AsString () const
{
wxString tmp;
// font-weight
tmp << _T("font-weight : ");
if (bold) tmp << _T("bold");
else tmp << _T("normal");
tmp << _T(";\n");
// font-style
tmp << _T("font-style : ");
if (italic) tmp << _T("italic");
else tmp << _T("normal");
tmp << _T(";\n");
// text decoration
tmp << _T("text-decoration : ");
if (underlined) tmp << _T("underline");
else tmp << _T("none");
tmp << _T(";\n");
// font size
tmp << _T("font-size : ");
tmp << size << _T("px");
tmp << _T(";\n");
// width
tmp << _T("width : ");
tmp << width << _T("px");
tmp << _T(";\n");
// fg
if (fg.IsOk())
{
tmp << _T("color : ");
tmp << fg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
}
// bg
if (bg.IsOk())
{
tmp << _T("background-color : ");
tmp << bg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
}
// border
if (outline.IsOk())
{
tmp << _T("outline-color : ");
tmp << outline.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX);
tmp << _T(";\n");
}
// opacity
tmp << _T("opacity : ");
tmp << opacity;
tmp << _T(";");
return tmp;
}
/**
* Construct new style info object
*/
StyleParser::StyleParser (const wxString & filename)
{
// this style is returned as default
m_defaultStyle.isOk = true;
// Load CSS
LoadFile(filename);
}
/**
* Find rule value
*/
wxString StyleParser::GetRule (CssRule & info, const wxString & rule, const wxString & selector)
{
// check if this rule has a value
if (info.styles[rule].Len() && info.styles[rule] != "inherit")
return info.styles[rule];
// no inherit or try to inherit from self?
if (!info.inheritFrom.Len() || info.inheritFrom == selector) return "";
// check if inherit exists
if (!PathExists(info.inheritFrom)) return "";
// call recursievly
return GetRule(m_cssRuleMap[info.inheritFrom], rule, info.inheritFrom);
}
// Reset styleinfo's so that changes would reflect in the
// next call to get styles
void StyleParser::ResetStyleInfoCache ()
{
for (auto iter = m_styleInfoMap.begin(); iter != m_styleInfoMap.end(); iter++)
iter->second.isOk = false;
}
/**
* Parse the CSS file.
* This is a very simple and primitive CSS
* parser capable only function within FBIDE
* styling needs.
*/
void StyleParser::LoadFile (const wxString & filename)
{
if (!filename.Len()) return;
if (!::wxFileExists(filename))
{
wxLogWarning("Style file '%s' not found", filename);
return;
}
// load the file
wxTextFile file;
file.Open(filename);
// parse through the file
wxString buffer;
for (wxString str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
buffer << str << "\n";
// parse states
bool inComment = false,
inString = false,
inSection = false,
inDefine = false,
inIdentifier=false;
wxChar cCh = 0;
wxChar pCh = 0;
wxChar nCh = 0;
wxString section, key, value;
wxArrayString values;
int line = 1, col = 0;
#define CSS_ERROR() \
{ \
wxString error; \
wxLogWarning("Invalid character at %d:%d (%d)", line, col, __LINE__); \
return; \
}
for (size_t i = 0; i < buffer.Len(); i++)
{
pCh = cCh;
cCh = buffer[i];
nCh = (i < buffer.Len()-1) ? buffer[i+1] : 0;
// count lines and columns
if (cCh == 10) { line++; col=0; }
else col++;
// if inside a comment
if (inComment)
{
if (cCh == '*' && nCh == '/')
{
inComment = false;
col++, i++;
}
continue;
}
// in quoted text ?
else if (inString)
{
if (cCh == '"')
{
inString = false;
values.Add(value);
value = _T("");
}
else value << cCh;
continue;
}
// identifier
else if (inIdentifier)
{
if ((cCh >= 'a' && cCh <= 'z')
|| (cCh >= 'A' && cCh <= 'Z')
|| (cCh >= '0' && cCh <= '9')
|| cCh == '-' || cCh == '.' || cCh == '_')
{
if (inSection)
{
if (inDefine) value << cCh;
else key << cCh;
}
else section << cCh;
continue;
}
else if (inSection && inDefine)
{
values.Add(value);
value = _T("");
}
inIdentifier = false;
}
// a comment ?
if (cCh == '/' && nCh == '*')
{
inComment = true;
col++, i++;
continue;
}
// a whitespace ?
if (cCh == ' ' || cCh == '\t' || cCh == 10 || cCh == 13)
{
continue;
}
// section start ?
if (cCh == '{')
{
if (inSection || !section.Len()) CSS_ERROR();
inSection = true;
continue;
}
// section end ?
if (cCh == '}')
{
if (!inSection || inDefine) CSS_ERROR();
inSection = false;
section = _T("");
continue;
}
// couted text ?
if (cCh == '"')
{
if (!inDefine) CSS_ERROR();
inString = true;
continue;
}
if (cCh == ':')
{
if (!inSection || inDefine || !key.Len())
CSS_ERROR();
inDefine = true;
continue;
}
if (cCh == ';')
{
if (!inSection || !inDefine || !values.Count())
CSS_ERROR();
inDefine = false;
SetCssRule (section, key, values);
key = _T("");
values.Clear();
continue;
}
// identifier ?
if ((cCh >= 'a' && cCh <= 'z')
|| (cCh >= 'A' && cCh <= 'Z')
|| (cCh >= '0' && cCh <= '9')
|| cCh == '-' || cCh == '.'
|| cCh == '_' || cCh == '#')
{
inIdentifier = true;
if (inSection)
{
if (inDefine) value << cCh;
else key << cCh;
}
else section << cCh;
}
}
#undef CSS_ERROR
}
// Add CSS rule
void StyleParser::SetCssRule (
const wxString & selector,
const wxString & rule,
const wxString & value,
const wxString & inheritFrom
)
{
wxArrayString values;
values.Add(value);
SetCssRule(selector, rule, values, inheritFrom);
}
void StyleParser::SetCssRule (
const wxString & selector,
const wxString & rule,
const wxArrayString & values,
const wxString & inheritFrom
)
{
if (!selector.Len() || !rule.Len() || !values.Count())
return;
// inherit default values from class...
wxString inherit = inheritFrom;
// reset style cache
ResetStyleInfoCache();
// split classes
wxStringTokenizer tkz(selector, ".");
// iterate through the classes
wxString partSelector;
wxString token;
while ( tkz.HasMoreTokens() )
{
// skip if empty
token = tkz.GetNextToken();
if (!token.Len()) continue;
// the path to current class
wxString path = partSelector + "." + token;
// if there are more tokens then it means that current
// selector becomes a parent to the next one
if (tkz.HasMoreTokens())
{
if (!PathExists(path))
{
m_cssRuleMap[path].inheritFrom = inherit;
}
inherit = path;
partSelector = path;
}
else
{
// need to add inherit info ?
bool addInherit = false;
// get the style info
if (!PathExists(path)) addInherit = true;
CssRule & info = m_cssRuleMap[path];
if (addInherit) info.inheritFrom = inherit;
// parse CSS rules
wxString value = values[0];
// color
if (rule == _T("color"))
info.styles[rule] = value;
// background
else if (rule == _T("background") || rule == _T("background-color"))
info.styles[_T("background-color")] = value;
// outline
else if (rule == _T("outline-color"))
info.styles[rule] = value;
// font size
else if (rule == _T("font-size"))
{
if (value.Right(2) == _T("px"))
info.styles[rule] = value.Left(value.Len()-2);
}
// font family
else if (rule == _T("font-family"))
info.styles[rule] = value;
// font style
else if (rule == _T("font-style"))
info.styles[rule] = value;
// font weight
else if (rule == _T("font-weight"))
info.styles[rule] = value;
// text decorations
else if (rule == _T("text-decoration"))
info.styles[rule] = value;
else if (rule == _T("opacity"))
info.styles[rule] = value;
else if (rule == _T("width"))
{
if (value.Right(2) == _T("px"))
info.styles[rule] = value.Left(value.Len()-2);
}
}
}
}
/**
* Get styles
* If selector is not defined try to inherit styles from it's base
* or default selector.
*/
const StyleInfo & StyleParser::GetStyle (const wxString & selector, const wxString & inherit)
{
// invalid path?
if (!PathExists(selector))
{
SetCssRule(selector, "font-size", "inherit", inherit.Len() ? inherit : ".default");
}
// get styleinfo from cache. if it exists then return it
StyleInfo & style = m_styleInfoMap[selector];
if (style.isOk) return style;
// get data
CssRule & info = m_cssRuleMap[selector];
wxString value;
// get bold
value = GetRule(info, "font-weight", selector);
if (value == "bold") style.bold = true;
// get italic
value = GetRule(info, "font-style", selector);
if (value == "italic") style.italic = true;
// get underlined
value = GetRule(info, "text-decoration", selector);
if (value == "underlined") style.underlined = true;
// get font size
value = GetRule(info, "font-size", selector);
if (value.Len())
{
long size = 0;
value.ToLong(&size);
style.size = (int)size;
}
else style.size = StyleDefaultFontSize;
// get font size
value = GetRule(info, "width", selector);
if (value.Len())
{
long width = 0;
value.ToLong(&width);
style.width = (int)width;
}
// get font size
value = GetRule(info, "opacity", selector);
if (value.Len())
{
long opacity = 0;
value.ToLong(&opacity);
style.opacity = (int)opacity;
}
// get font family
value = GetRule(info, "font-family", selector);
if (value.Len()) style.font = value;
else style.font = StyleDefaultFont;
// get color
value = GetRule(info, "color", selector);
if (value.Len()) style.fg.Set(value);
else style.fg.Set(StyleDefaultForeColor);
// get background color
value = GetRule(info, "background-color", selector);
if (value.Len())
{
if (value != "none" && value != "transparent") style.bg.Set(value);
}
else style.bg.Set(StyleDefaultBackColor);
// outline color
value = GetRule(info, "outline-color", selector);
if (value.Len())
{
if (value != "none" && value != "transparent")
style.outline.Set(value);
}
else style.outline.Set(StyleDefaultBackColor);
style.isOk = true;
return style;
}
/**
* Check if CSS path exists
*/
bool StyleParser::PathExists (const wxString & selector)
{
return m_cssRuleMap.find(selector) != m_cssRuleMap.end();
}
<file_sep>/fbide-vs/Sdk/MultiDelegate.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#ifndef MULTIDELEGATE_H_INCLUDED
#define MULTIDELEGATE_H_INCLUDED
#include "Delegate.h"
/**
* To simplify MultiDelegate
* specialized templates some common
* stuff is in this base.
* also individual delegates are stored
* as void * because compiler otherwise
* seems to prove problematic when
* nested partial templates are parameters
* to one - another.
*/
template<class T, class Container = std::vector<T*>> class MultiDelegateBase
{
public :
// convinience overload for connecting slots
void operator += (const T & delegate)
{
Connect(delegate);
}
// Connect slot
void Connect (const T & delegate)
{
m_list.push_back(new T(delegate));
}
// convinience method to disconnect
void operator -= (const T & delegate)
{
Disconnect(delegate);
}
// disconnect a slot
void Disconnect (const T & delegate)
{
auto iter = m_list.begin();
while (iter != m_list.end())
{
if (**iter == delegate)
{
delete *iter;
if (activeLevel)
{
*iter = nullptr;
toCleanup++;
}
else
{
iter = m_list.erase(iter);
continue;
}
}
iter++;
}
}
/**
* create
*/
MultiDelegateBase () : activeLevel(0), toCleanup(0) {}
/**
* Clean up
*/
virtual ~MultiDelegateBase()
{
for (auto iter = m_list.begin(); iter != m_list.end(); iter++)
{
delete *iter;
}
}
protected :
Container m_list;
int activeLevel;
int toCleanup;
/**
* Cleanup empty entries (caused by callee trying to remove itself
* from call list
*/
void Cleanup ()
{
// can't or nothing to clean up
if (activeLevel || !toCleanup) return;
// do the cleanup
auto iter = m_list.begin();
while (iter != m_list.end())
{
if (*iter == nullptr) iter = m_list.erase(iter);
else iter++;
}
toCleanup = 0;
}
};
/**
* Declare this is as template class and specialize
* later on.
*/
template <typename Signature>
class MultiDelegate;
/**
* To provide *safe* calling of delegate functions we need to wrap things
* up a bit. The problem being a callee wanting to erase itself from the
* multidelegate. This cannot be done cleanly. SO this kind of wrapping
* is required.
*/
#define DLG_CALL_START \
parent::activeLevel++; \
auto iter = parent::m_list.begin(); \
while (iter != parent::m_list.end()) \
{ \
if (nullptr != *iter)
/**
* End block. Wrap delegate method call
*/
#define DLG_CALL_END \
else if (parent::activeLevel == 1) \
{ \
iter = parent::m_list.erase(iter); \
parent::toCleanup--; \
continue; \
} \
iter++; \
} \
parent::activeLevel--; \
parent::Cleanup();
// N=0
// R ();
template<typename R>
class MultiDelegate < R ( ) >
: public MultiDelegateBase<Delegate0<R> >
{
typedef Delegate0<R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () ()
{
DLG_CALL_START
{
(**iter)();
}
DLG_CALL_END
}
};
// N=1
// R (P1);
template<typename R, class P1>
class MultiDelegate < R ( P1 ) >
: public MultiDelegateBase<Delegate1<P1, R> >
{
typedef Delegate1<P1, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1));
}
DLG_CALL_END
}
};
// N=2
// R (P1, P2);
template<typename R, class P1, class P2>
class MultiDelegate < R ( P1, P2 ) >
: public MultiDelegateBase< Delegate2<P1, P2, R> >
{
typedef Delegate2<P1, P2, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2));
}
DLG_CALL_END
}
};
// N=3
// R (P1, P2, P3);
template<typename R, class P1, class P2, class P3>
class MultiDelegate < R ( P1, P2, P3 ) >
: public MultiDelegateBase<Delegate3<P1, P2, P3, R> >
{
typedef Delegate3<P1, P2, P3, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3));
}
DLG_CALL_END
}
};
// N=4
// R (P1, P2, P3, P4);
template<typename R, class P1, class P2, class P3, class P4>
class MultiDelegate < R ( P1, P2, P3, P4 ) >
: public MultiDelegateBase<Delegate4<P1, P2, P3, P4, R> >
{
typedef Delegate4<P1, P2, P3, P4, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3, P4 && p4)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3), std::forward<P4>(p4));
}
DLG_CALL_END
}
};
// N=5
// R (P1, P2, P3, P4, P5);
template<typename R, class P1, class P2, class P3, class P4, class P5>
class MultiDelegate < R ( P1, P2, P3, P4, P5 ) >
: public MultiDelegateBase<Delegate5<P1, P2, P3, P4, P5, R> >
{
typedef Delegate5<P1, P2, P3, P4, P5, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3, P4 && p4, P5 && p5)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3), std::forward<P4>(p4),
std::forward<P5>(p5));
}
DLG_CALL_END
}
};
// N=6
// R (P1, P2, P3, P4, P5, P6);
template<typename R, class P1, class P2, class P3, class P4, class P5, class P6>
class MultiDelegate < R ( P1, P2, P3, P4, P5, P6 ) >
: public MultiDelegateBase<Delegate6<P1, P2, P3, P4, P5, P6, R> >
{
typedef Delegate6<P1, P2, P3, P4, P5, P6, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3, P4 && p4, P5 && p5, P6 && p6)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3), std::forward<P4>(p4),
std::forward<P5>(p5), std::forward<P6>(p6));
}
DLG_CALL_END
}
};
// N=7
// R (P1, P2, P3, P4, P5, P6, P7);
template<typename R, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
class MultiDelegate < R ( P1, P2, P3, P4, P5, P6, P7 ) >
: public MultiDelegateBase<Delegate7<P1, P2, P3, P4, P5, P6, P7, R>>
{
typedef Delegate7<P1, P2, P3, P4, P5, P6, P7, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3, P4 && p4, P5 && p5, P6 && p6, P7 && p7)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3), std::forward<P4>(p4),
std::forward<P5>(p5), std::forward<P6>(p6),
std::forward<P7>(p7));
}
DLG_CALL_END
}
};
// N=8
// R (P1, P2, P3, P4, P5, P6, P7, P8);
template<typename R, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
class MultiDelegate < R ( P1, P2, P3, P4, P5, P6, P7, P8 ) >
: public MultiDelegateBase<Delegate8<P1, P2, P3, P4, P5, P6, P7, P8, R>>
{
typedef Delegate8<P1, P2, P3, P4, P5, P6, P7, P8, R> type;
typedef MultiDelegateBase<type> parent;
public :
typedef type Signature;
void operator () (P1 && p1, P2 && p2, P3 && p3, P4 && p4, P5 && p5, P6 && p6, P7 && p7, P8 && p8)
{
DLG_CALL_START
{
(**iter)(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3), std::forward<P4>(p4),
std::forward<P5>(p5), std::forward<P6>(p6),
std::forward<P7>(p7), std::forward<P8>(p8));
}
DLG_CALL_END
}
};
#endif // MULTIDELEGATE_H_INCLUDED
<file_sep>/fbide-vs/wxScintillaCtrl/Makefile.in
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.1 (http://bakefile.sourceforge.net)
# Do not modify, all changes will be overwritten!
# =========================================================================
@MAKE_SET@
prefix = @prefix@
exec_prefix = @exec_prefix@
INSTALL = @INSTALL@
SHARED_LD_CXX = @SHARED_LD_CXX@
LIBEXT = @LIBEXT@
LIBPREFIX = @LIBPREFIX@
SO_SUFFIX = @SO_SUFFIX@
DLLIMP_SUFFIX = @DLLIMP_SUFFIX@
LN_S = @LN_S@
WINDRES = @WINDRES@
PIC_FLAG = @PIC_FLAG@
SONAME_FLAG = @SONAME_FLAG@
STRIP = @STRIP@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_DIR = @INSTALL_DIR@
BK_DEPS = @BK_DEPS@
srcdir = @srcdir@
top_srcdir = @top_srcdir@
libdir = @libdir@
includedir = @includedir@
DLLPREFIX = @DLLPREFIX@
LIBS = @LIBS@
AR = @AR@
AROPTIONS = @AROPTIONS@
RANLIB = @RANLIB@
CXX = @CXX@
CXXFLAGS = @CXXFLAGS@
CPPFLAGS = @CPPFLAGS@
LDFLAGS = @LDFLAGS@
VENDOR = @VENDOR@
WX_FLAVOUR = @WX_FLAVOUR@
WX_LIB_FLAVOUR = @WX_LIB_FLAVOUR@
TOOLKIT = @TOOLKIT@
TOOLKIT_LOWERCASE = @TOOLKIT_LOWERCASE@
TOOLKIT_VERSION = @TOOLKIT_VERSION@
TOOLCHAIN_FULLNAME = @TOOLCHAIN_FULLNAME@
EXTRALIBS = @EXTRALIBS@
EXTRALIBS_GUI = @EXTRALIBS_GUI@
HOST_SUFFIX = @HOST_SUFFIX@
wx_top_builddir = @wx_top_builddir@
### Variables: ###
DESTDIR =
WX_RELEASE = 2.9
WX_RELEASE_NODOT = 29
WX_VERSION_NODOT = $(WX_RELEASE_NODOT)0
LIBDIRNAME = $(wx_top_builddir)/lib
STCDLL_CXXFLAGS = -D__WX$(TOOLKIT)__ $(__WXUNIV_DEFINE_p) \
$(__EXCEPTIONS_DEFINE_p) $(__RTTI_DEFINE_p) $(__THREAD_DEFINE_p) \
-I$(srcdir)/../../include -I$(srcdir)/scintilla/include \
-I$(srcdir)/scintilla/src -D__WX__ -DSCI_LEXER -DLINK_LEXERS -DWXUSINGDLL \
-DWXMAKINGDLL_STC $(PIC_FLAG) $(CPPFLAGS) $(CXXFLAGS)
STCDLL_OBJECTS = \
$(__stcdll___win32rc) \
stcdll_PlatWX.o \
stcdll_ScintillaWX.o \
stcdll_stc.o \
stcdll_AutoComplete.o \
stcdll_CallTip.o \
stcdll_CellBuffer.o \
stcdll_CharClassify.o \
stcdll_ContractionState.o \
stcdll_Document.o \
stcdll_DocumentAccessor.o \
stcdll_Editor.o \
stcdll_ExternalLexer.o \
stcdll_Indicator.o \
stcdll_KeyMap.o \
stcdll_KeyWords.o \
stcdll_LexAPDL.o \
stcdll_LexAU3.o \
stcdll_LexAVE.o \
stcdll_LexAda.o \
stcdll_LexAsm.o \
stcdll_LexAsn1.o \
stcdll_LexBaan.o \
stcdll_LexBash.o \
stcdll_LexBasic.o \
stcdll_LexBullant.o \
stcdll_LexCLW.o \
stcdll_LexCPP.o \
stcdll_LexCSS.o \
stcdll_LexCaml.o \
stcdll_LexCsound.o \
stcdll_LexConf.o \
stcdll_LexCrontab.o \
stcdll_LexEScript.o \
stcdll_LexEiffel.o \
stcdll_LexErlang.o \
stcdll_LexFlagship.o \
stcdll_LexForth.o \
stcdll_LexFortran.o \
stcdll_LexGui4Cli.o \
stcdll_LexHTML.o \
stcdll_LexHaskell.o \
stcdll_LexInno.o \
stcdll_LexKix.o \
stcdll_LexLisp.o \
stcdll_LexLout.o \
stcdll_LexLua.o \
stcdll_LexMMIXAL.o \
stcdll_LexMPT.o \
stcdll_LexMSSQL.o \
stcdll_LexMatlab.o \
stcdll_LexMetapost.o \
stcdll_LexNsis.o \
stcdll_LexOpal.o \
stcdll_LexOthers.o \
stcdll_LexPB.o \
stcdll_LexPOV.o \
stcdll_LexPS.o \
stcdll_LexPascal.o \
stcdll_LexPerl.o \
stcdll_LexPython.o \
stcdll_LexRebol.o \
stcdll_LexRuby.o \
stcdll_LexSQL.o \
stcdll_LexSmalltalk.o \
stcdll_LexTADS3.o \
stcdll_LexScriptol.o \
stcdll_LexSpecman.o \
stcdll_LexSpice.o \
stcdll_LexTCL.o \
stcdll_LexTeX.o \
stcdll_LexVB.o \
stcdll_LexVHDL.o \
stcdll_LexVerilog.o \
stcdll_LexYAML.o \
stcdll_LineMarker.o \
stcdll_PropSet.o \
stcdll_RESearch.o \
stcdll_ScintillaBase.o \
stcdll_Style.o \
stcdll_StyleContext.o \
stcdll_UniConversion.o \
stcdll_ViewStyle.o \
stcdll_WindowAccessor.o \
stcdll_XPM.o
STCLIB_CXXFLAGS = -D__WX$(TOOLKIT)__ $(__WXUNIV_DEFINE_p) \
$(__EXCEPTIONS_DEFINE_p) $(__RTTI_DEFINE_p) $(__THREAD_DEFINE_p) \
-I$(srcdir)/../../include -I$(srcdir)/scintilla/include \
-I$(srcdir)/scintilla/src -D__WX__ -DSCI_LEXER -DLINK_LEXERS $(CPPFLAGS) \
$(CXXFLAGS)
STCLIB_OBJECTS = \
stclib_PlatWX.o \
stclib_ScintillaWX.o \
stclib_stc.o \
stclib_AutoComplete.o \
stclib_CallTip.o \
stclib_CellBuffer.o \
stclib_CharClassify.o \
stclib_ContractionState.o \
stclib_Document.o \
stclib_DocumentAccessor.o \
stclib_Editor.o \
stclib_ExternalLexer.o \
stclib_Indicator.o \
stclib_KeyMap.o \
stclib_KeyWords.o \
stclib_LexAPDL.o \
stclib_LexAU3.o \
stclib_LexAVE.o \
stclib_LexAda.o \
stclib_LexAsm.o \
stclib_LexAsn1.o \
stclib_LexBaan.o \
stclib_LexBash.o \
stclib_LexBasic.o \
stclib_LexBullant.o \
stclib_LexCLW.o \
stclib_LexCPP.o \
stclib_LexCSS.o \
stclib_LexCaml.o \
stclib_LexCsound.o \
stclib_LexConf.o \
stclib_LexCrontab.o \
stclib_LexEScript.o \
stclib_LexEiffel.o \
stclib_LexErlang.o \
stclib_LexFlagship.o \
stclib_LexForth.o \
stclib_LexFortran.o \
stclib_LexGui4Cli.o \
stclib_LexHTML.o \
stclib_LexHaskell.o \
stclib_LexInno.o \
stclib_LexKix.o \
stclib_LexLisp.o \
stclib_LexLout.o \
stclib_LexLua.o \
stclib_LexMMIXAL.o \
stclib_LexMPT.o \
stclib_LexMSSQL.o \
stclib_LexMatlab.o \
stclib_LexMetapost.o \
stclib_LexNsis.o \
stclib_LexOpal.o \
stclib_LexOthers.o \
stclib_LexPB.o \
stclib_LexPOV.o \
stclib_LexPS.o \
stclib_LexPascal.o \
stclib_LexPerl.o \
stclib_LexPython.o \
stclib_LexRebol.o \
stclib_LexRuby.o \
stclib_LexSQL.o \
stclib_LexSmalltalk.o \
stclib_LexTADS3.o \
stclib_LexScriptol.o \
stclib_LexSpecman.o \
stclib_LexSpice.o \
stclib_LexTCL.o \
stclib_LexTeX.o \
stclib_LexVB.o \
stclib_LexVHDL.o \
stclib_LexVerilog.o \
stclib_LexYAML.o \
stclib_LineMarker.o \
stclib_PropSet.o \
stclib_RESearch.o \
stclib_ScintillaBase.o \
stclib_Style.o \
stclib_StyleContext.o \
stclib_UniConversion.o \
stclib_ViewStyle.o \
stclib_WindowAccessor.o \
stclib_XPM.o
### Conditionally set variables: ###
@COND_DEPS_TRACKING_0@CXXC = $(CXX)
@COND_DEPS_TRACKING_1@CXXC = $(BK_DEPS) $(CXX)
@COND_PLATFORM_MACOSX_1@WXMACVERSION_CMD = \
@COND_PLATFORM_MACOSX_1@ -compatibility_version 1.0 -current_version 1.0
@COND_USE_GUI_0@PORTNAME = base
@COND_USE_GUI_1@PORTNAME = $(TOOLKIT_LOWERCASE)$(TOOLKIT_VERSION)
@COND_TOOLKIT_MAC@WXBASEPORT = _carbon
@COND_PLATFORM_WIN32_1@WXCOMPILER = _gcc
@COND_OFFICIAL_BUILD_0_PLATFORM_WIN32_1@VENDORTAG = _$(VENDOR)
@COND_OFFICIAL_BUILD_1_PLATFORM_WIN32_1@VENDORTAG =
@COND_BUILD_DEBUG_DEBUG_FLAG_DEFAULT@WXDEBUGFLAG = d
@COND_DEBUG_FLAG_1@WXDEBUGFLAG = d
@COND_UNICODE_1@WXUNICODEFLAG = u
@COND_WXUNIV_1@WXUNIVNAME = univ
@COND_PLATFORM_WIN32_0@WXDLLNAMEPREFIXGUI = wx_$(PORTNAME)$(WXUNIVNAME)
@COND_PLATFORM_WIN32_1@WXDLLNAMEPREFIXGUI = \
@COND_PLATFORM_WIN32_1@ wx$(PORTNAME)$(WXUNIVNAME)$(WX_VERSION_NODOT)
@COND_PLATFORM_WIN32_0@WXDLLVERSIONTAG = -$(WX_RELEASE)
@COND_PLATFORM_WIN32_1@WXDLLVERSIONTAG =
@COND_MONOLITHIC_0@EXTRALIBS_FOR_BASE = $(EXTRALIBS)
@COND_MONOLITHIC_1@EXTRALIBS_FOR_BASE = $(EXTRALIBS) $(EXTRALIBS_GUI)
@COND_MONOLITHIC_0@EXTRALIBS_FOR_GUI = $(EXTRALIBS_GUI)
@COND_MONOLITHIC_1@EXTRALIBS_FOR_GUI =
COND_SHARED_1___stcdll___depname = \
$(LIBDIRNAME)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3)
@COND_SHARED_1@__stcdll___depname = $(COND_SHARED_1___stcdll___depname)
@COND_WXUNIV_1@__WXUNIV_DEFINE_p_1 = --define __WXUNIVERSAL__
@COND_USE_EXCEPTIONS_0@__EXCEPTIONS_DEFINE_p_1 = --define wxNO_EXCEPTIONS
@COND_USE_RTTI_0@__RTTI_DEFINE_p_1 = --define wxNO_RTTI
@COND_USE_THREADS_0@__THREAD_DEFINE_p_1 = --define wxNO_THREADS
@COND_SHARED_1@__install_stcdll___depname = install_stcdll
@COND_SHARED_1@__uninstall_stcdll___depname = uninstall_stcdll
COND_PLATFORM_MACOSX_1___stcdll___macinstnamecmd = -install_name \
$(libdir)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2)
@COND_PLATFORM_MACOSX_1@__stcdll___macinstnamecmd = $(COND_PLATFORM_MACOSX_1___stcdll___macinstnamecmd)
COND_PLATFORM_OS2_1___stcdll___importlib = -import \
$(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
@COND_PLATFORM_OS2_1@__stcdll___importlib = $(COND_PLATFORM_OS2_1___stcdll___importlib)
COND_WINDOWS_IMPLIB_1___stcdll___importlib = \
-Wl,--out-implib=$(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
@COND_WINDOWS_IMPLIB_1@__stcdll___importlib = $(COND_WINDOWS_IMPLIB_1___stcdll___importlib)
@COND_PLATFORM_MACOSX_0_USE_SOVERSION_1@__stcdll___targetsuf2 \
@COND_PLATFORM_MACOSX_0_USE_SOVERSION_1@ = .$(SO_SUFFIX).0
@COND_PLATFORM_MACOSX_1_USE_SOVERSION_1@__stcdll___targetsuf2 \
@COND_PLATFORM_MACOSX_1_USE_SOVERSION_1@ = .0.$(SO_SUFFIX)
@COND_USE_SOVERSION_0@__stcdll___targetsuf2 = .$(SO_SUFFIX)
@COND_PLATFORM_MACOSX_0_USE_SOVERCYGWIN_0_USE_SOVERSION_1@__stcdll___targetsuf3 \
@COND_PLATFORM_MACOSX_0_USE_SOVERCYGWIN_0_USE_SOVERSION_1@ = \
@COND_PLATFORM_MACOSX_0_USE_SOVERCYGWIN_0_USE_SOVERSION_1@ .$(SO_SUFFIX).0.0.0
@COND_PLATFORM_MACOSX_1_USE_SOVERSION_1@__stcdll___targetsuf3 \
@COND_PLATFORM_MACOSX_1_USE_SOVERSION_1@ = .0.0.0.$(SO_SUFFIX)
@COND_USE_SOVERCYGWIN_1_USE_SOVERSION_1@__stcdll___targetsuf3 \
@COND_USE_SOVERCYGWIN_1_USE_SOVERSION_1@ = -0.$(SO_SUFFIX)
@COND_USE_SOVERSION_0@__stcdll___targetsuf3 = .$(SO_SUFFIX)
COND_USE_SOVERLINUX_1___stcdll___soname_flags = \
$(SONAME_FLAG)$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2)
@COND_USE_SOVERLINUX_1@__stcdll___soname_flags = $(COND_USE_SOVERLINUX_1___stcdll___soname_flags)
COND_USE_SOVERSOLARIS_1___stcdll___soname_flags = \
$(SONAME_FLAG)$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3)
@COND_USE_SOVERSOLARIS_1@__stcdll___soname_flags = $(COND_USE_SOVERSOLARIS_1___stcdll___soname_flags)
COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_cmd = (cd $(LIBDIRNAME)/; rm -f \
$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2); \
$(LN_S) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2); \
$(LN_S) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2) \
$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX))
@COND_USE_SOSYMLINKS_1@__stcdll___so_symlinks_cmd = $(COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_cmd)
COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_inst_cmd = rm -f \
$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2); \
$(LN_S) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2); \
$(LN_S) \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2) \
$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
@COND_USE_SOSYMLINKS_1@__stcdll___so_symlinks_inst_cmd = $(COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_inst_cmd)
COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_uninst_cmd = rm -f \
$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2) \
$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
@COND_USE_SOSYMLINKS_1@__stcdll___so_symlinks_uninst_cmd = $(COND_USE_SOSYMLINKS_1___stcdll___so_symlinks_uninst_cmd)
@COND_TOOLKIT_MSW@__RCDEFDIR_p = --include-dir \
@COND_TOOLKIT_MSW@ $(LIBDIRNAME)/wx/include/$(TOOLCHAIN_FULLNAME)
@COND_PLATFORM_WIN32_1@__stcdll___win32rc = stcdll_version_rc.o
COND_MONOLITHIC_1___WXLIB_MONO_p = \
-lwx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_MONOLITHIC_1@__WXLIB_MONO_p = $(COND_MONOLITHIC_1___WXLIB_MONO_p)
@COND_USE_GUI_1_WXUSE_LIBTIFF_BUILTIN@__LIB_TIFF_p \
@COND_USE_GUI_1_WXUSE_LIBTIFF_BUILTIN@ = \
@COND_USE_GUI_1_WXUSE_LIBTIFF_BUILTIN@ -lwxtiff$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_USE_GUI_1_WXUSE_LIBJPEG_BUILTIN@__LIB_JPEG_p \
@COND_USE_GUI_1_WXUSE_LIBJPEG_BUILTIN@ = \
@COND_USE_GUI_1_WXUSE_LIBJPEG_BUILTIN@ -lwxjpeg$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_USE_GUI_1_WXUSE_LIBPNG_BUILTIN@__LIB_PNG_p \
@COND_USE_GUI_1_WXUSE_LIBPNG_BUILTIN@ = \
@COND_USE_GUI_1_WXUSE_LIBPNG_BUILTIN@ -lwxpng$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_WXUSE_ZLIB_BUILTIN@__LIB_ZLIB_p = \
@COND_WXUSE_ZLIB_BUILTIN@ -lwxzlib$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_WXUSE_ODBC_BUILTIN@__LIB_ODBC_p = \
@COND_WXUSE_ODBC_BUILTIN@ -lwxodbc$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
COND_WXUSE_REGEX_BUILTIN___LIB_REGEX_p = \
-lwxregex$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_WXUSE_REGEX_BUILTIN@__LIB_REGEX_p = $(COND_WXUSE_REGEX_BUILTIN___LIB_REGEX_p)
@COND_WXUSE_EXPAT_BUILTIN@__LIB_EXPAT_p = \
@COND_WXUSE_EXPAT_BUILTIN@ -lwxexpat$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
COND_MONOLITHIC_0___WXLIB_CORE_p = \
-lwx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_core-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_MONOLITHIC_0@__WXLIB_CORE_p = $(COND_MONOLITHIC_0___WXLIB_CORE_p)
COND_MONOLITHIC_0___WXLIB_BASE_p = \
-lwx_base$(WXBASEPORT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)-$(WX_RELEASE)$(HOST_SUFFIX)
@COND_MONOLITHIC_0@__WXLIB_BASE_p = $(COND_MONOLITHIC_0___WXLIB_BASE_p)
COND_SHARED_0___stclib___depname = \
$(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX)$(LIBEXT)
@COND_SHARED_0@__stclib___depname = $(COND_SHARED_0___stclib___depname)
@COND_SHARED_0@__install_stclib___depname = install_stclib
@COND_SHARED_0@__uninstall_stclib___depname = uninstall_stclib
@COND_WXUNIV_1@__WXUNIV_DEFINE_p = -D__WXUNIVERSAL__
@COND_USE_EXCEPTIONS_0@__EXCEPTIONS_DEFINE_p = -DwxNO_EXCEPTIONS
@COND_USE_RTTI_0@__RTTI_DEFINE_p = -DwxNO_RTTI
@COND_USE_THREADS_0@__THREAD_DEFINE_p = -DwxNO_THREADS
### Targets: ###
all: $(__stcdll___depname) $(__stclib___depname)
install: all $(__install_stcdll___depname) $(__install_stclib___depname)
$(INSTALL_DIR) $(DESTDIR)$(includedir)/wx-$(WX_RELEASE)$(WX_FLAVOUR)
for f in wx/stc/stc.h; do \
if test ! -d $(DESTDIR)$(includedir)/wx-$(WX_RELEASE)$(WX_FLAVOUR)/`dirname $$f` ; then \
$(INSTALL_DIR) $(DESTDIR)$(includedir)/wx-$(WX_RELEASE)$(WX_FLAVOUR)/`dirname $$f`; \
fi; \
$(INSTALL_DATA) $(srcdir)/../../include//$$f $(DESTDIR)$(includedir)/wx-$(WX_RELEASE)$(WX_FLAVOUR)/$$f; \
done
uninstall: $(__uninstall_stcdll___depname) $(__uninstall_stclib___depname)
for f in wx/stc/stc.h; do \
rm -f $(DESTDIR)$(includedir)/wx-$(WX_RELEASE)$(WX_FLAVOUR)/$$f; \
done
install-strip: install
$(STRIP) $(DESTDIR)$(libdir)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3)
clean:
rm -rf ./.deps ./.pch
rm -f ./*.o
rm -f $(LIBDIRNAME)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3)
rm -f $(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
rm -f $(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX) $(LIBDIRNAME)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf2)
rm -f $(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX)$(LIBEXT)
distclean: clean
rm -f config.cache config.log config.status bk-deps bk-make-pch shared-ld-sh Makefile
@COND_SHARED_1@$(LIBDIRNAME)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3): $(STCDLL_OBJECTS) $(__stcdll___win32rc)
@COND_SHARED_1@ $(SHARED_LD_CXX) $@ $(STCDLL_OBJECTS) $(LDFLAGS) -L$(LIBDIRNAME) $(__stcdll___macinstnamecmd) $(__stcdll___importlib) $(__stcdll___soname_flags) $(WXMACVERSION_CMD) $(LIBS) $(__WXLIB_MONO_p) $(__LIB_TIFF_p) $(__LIB_JPEG_p) $(__LIB_PNG_p) $(EXTRALIBS_FOR_GUI) $(__LIB_ZLIB_p) $(__LIB_ODBC_p) $(__LIB_REGEX_p) $(__LIB_EXPAT_p) $(EXTRALIBS_FOR_BASE) $(__WXLIB_CORE_p) $(__WXLIB_BASE_p)
@COND_SHARED_1@
@COND_SHARED_1@ $(__stcdll___so_symlinks_cmd)
@COND_SHARED_1@install_stcdll:
@COND_SHARED_1@ $(INSTALL_DIR) $(DESTDIR)$(libdir)
@COND_SHARED_1@ $(INSTALL_DATA) $(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX) $(DESTDIR)$(libdir)
@COND_SHARED_1@ $(INSTALL_PROGRAM) $(LIBDIRNAME)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3) $(DESTDIR)$(libdir)
@COND_SHARED_1@ (cd $(DESTDIR)$(libdir) ; $(__stcdll___so_symlinks_inst_cmd))
@COND_SHARED_1@uninstall_stcdll:
@COND_SHARED_1@ rm -f $(DESTDIR)$(libdir)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX).$(DLLIMP_SUFFIX)
@COND_SHARED_1@ rm -f $(DESTDIR)$(libdir)/$(DLLPREFIX)$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG)$(__stcdll___targetsuf3)
@COND_SHARED_1@ (cd $(DESTDIR)$(libdir) ; $(__stcdll___so_symlinks_uninst_cmd))
@COND_SHARED_0@$(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX)$(LIBEXT): $(STCLIB_OBJECTS)
@COND_SHARED_0@ rm -f $@
@COND_SHARED_0@ $(AR) $(AROPTIONS) $@ $(STCLIB_OBJECTS)
@COND_SHARED_0@ $(RANLIB) $@
@COND_SHARED_0@install_stclib:
@COND_SHARED_0@ $(INSTALL_DIR) $(DESTDIR)$(libdir)
@COND_SHARED_0@ $(INSTALL_DATA) $(LIBDIRNAME)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX)$(LIBEXT) $(DESTDIR)$(libdir)
@COND_SHARED_0@uninstall_stclib:
@COND_SHARED_0@ rm -f $(DESTDIR)$(libdir)/$(LIBPREFIX)wx_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc-$(WX_RELEASE)$(HOST_SUFFIX)$(LIBEXT)
stcdll_version_rc.o: $(srcdir)/../../../src/msw/version.rc
$(WINDRES) -i$< -o$@ --define __WX$(TOOLKIT)__ $(__WXUNIV_DEFINE_p_1) $(__EXCEPTIONS_DEFINE_p_1) $(__RTTI_DEFINE_p_1) $(__THREAD_DEFINE_p_1) --define WXDLLNAME=$(WXDLLNAMEPREFIXGUI)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_stc$(WXCOMPILER)$(VENDORTAG)$(WXDLLVERSIONTAG) $(__RCDEFDIR_p) --include-dir $(top_srcdir)/include
stcdll_PlatWX.o: $(srcdir)/PlatWX.cpp
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/PlatWX.cpp
stcdll_ScintillaWX.o: $(srcdir)/ScintillaWX.cpp
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/ScintillaWX.cpp
stcdll_stc.o: $(srcdir)/stc.cpp
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/stc.cpp
stcdll_AutoComplete.o: $(srcdir)/scintilla/src/AutoComplete.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/AutoComplete.cxx
stcdll_CallTip.o: $(srcdir)/scintilla/src/CallTip.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/CallTip.cxx
stcdll_CellBuffer.o: $(srcdir)/scintilla/src/CellBuffer.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/CellBuffer.cxx
stcdll_CharClassify.o: $(srcdir)/scintilla/src/CharClassify.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/CharClassify.cxx
stcdll_ContractionState.o: $(srcdir)/scintilla/src/ContractionState.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/ContractionState.cxx
stcdll_Document.o: $(srcdir)/scintilla/src/Document.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/Document.cxx
stcdll_DocumentAccessor.o: $(srcdir)/scintilla/src/DocumentAccessor.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/DocumentAccessor.cxx
stcdll_Editor.o: $(srcdir)/scintilla/src/Editor.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/Editor.cxx
stcdll_ExternalLexer.o: $(srcdir)/scintilla/src/ExternalLexer.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/ExternalLexer.cxx
stcdll_Indicator.o: $(srcdir)/scintilla/src/Indicator.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/Indicator.cxx
stcdll_KeyMap.o: $(srcdir)/scintilla/src/KeyMap.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/KeyMap.cxx
stcdll_KeyWords.o: $(srcdir)/scintilla/src/KeyWords.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/KeyWords.cxx
stcdll_LexAPDL.o: $(srcdir)/scintilla/src/LexAPDL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAPDL.cxx
stcdll_LexAU3.o: $(srcdir)/scintilla/src/LexAU3.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAU3.cxx
stcdll_LexAVE.o: $(srcdir)/scintilla/src/LexAVE.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAVE.cxx
stcdll_LexAda.o: $(srcdir)/scintilla/src/LexAda.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAda.cxx
stcdll_LexAsm.o: $(srcdir)/scintilla/src/LexAsm.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAsm.cxx
stcdll_LexAsn1.o: $(srcdir)/scintilla/src/LexAsn1.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexAsn1.cxx
stcdll_LexBaan.o: $(srcdir)/scintilla/src/LexBaan.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexBaan.cxx
stcdll_LexBash.o: $(srcdir)/scintilla/src/LexBash.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexBash.cxx
stcdll_LexBasic.o: $(srcdir)/scintilla/src/LexBasic.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexBasic.cxx
stcdll_LexBullant.o: $(srcdir)/scintilla/src/LexBullant.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexBullant.cxx
stcdll_LexCLW.o: $(srcdir)/scintilla/src/LexCLW.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCLW.cxx
stcdll_LexCPP.o: $(srcdir)/scintilla/src/LexCPP.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCPP.cxx
stcdll_LexCSS.o: $(srcdir)/scintilla/src/LexCSS.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCSS.cxx
stcdll_LexCaml.o: $(srcdir)/scintilla/src/LexCaml.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCaml.cxx
stcdll_LexCsound.o: $(srcdir)/scintilla/src/LexCsound.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCsound.cxx
stcdll_LexConf.o: $(srcdir)/scintilla/src/LexConf.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexConf.cxx
stcdll_LexCrontab.o: $(srcdir)/scintilla/src/LexCrontab.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexCrontab.cxx
stcdll_LexEScript.o: $(srcdir)/scintilla/src/LexEScript.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexEScript.cxx
stcdll_LexEiffel.o: $(srcdir)/scintilla/src/LexEiffel.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexEiffel.cxx
stcdll_LexErlang.o: $(srcdir)/scintilla/src/LexErlang.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexErlang.cxx
stcdll_LexFlagship.o: $(srcdir)/scintilla/src/LexFlagship.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexFlagship.cxx
stcdll_LexForth.o: $(srcdir)/scintilla/src/LexForth.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexForth.cxx
stcdll_LexFortran.o: $(srcdir)/scintilla/src/LexFortran.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexFortran.cxx
stcdll_LexGui4Cli.o: $(srcdir)/scintilla/src/LexGui4Cli.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexGui4Cli.cxx
stcdll_LexHTML.o: $(srcdir)/scintilla/src/LexHTML.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexHTML.cxx
stcdll_LexHaskell.o: $(srcdir)/scintilla/src/LexHaskell.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexHaskell.cxx
stcdll_LexInno.o: $(srcdir)/scintilla/src/LexInno.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexInno.cxx
stcdll_LexKix.o: $(srcdir)/scintilla/src/LexKix.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexKix.cxx
stcdll_LexLisp.o: $(srcdir)/scintilla/src/LexLisp.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexLisp.cxx
stcdll_LexLout.o: $(srcdir)/scintilla/src/LexLout.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexLout.cxx
stcdll_LexLua.o: $(srcdir)/scintilla/src/LexLua.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexLua.cxx
stcdll_LexMMIXAL.o: $(srcdir)/scintilla/src/LexMMIXAL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexMMIXAL.cxx
stcdll_LexMPT.o: $(srcdir)/scintilla/src/LexMPT.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexMPT.cxx
stcdll_LexMSSQL.o: $(srcdir)/scintilla/src/LexMSSQL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexMSSQL.cxx
stcdll_LexMatlab.o: $(srcdir)/scintilla/src/LexMatlab.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexMatlab.cxx
stcdll_LexMetapost.o: $(srcdir)/scintilla/src/LexMetapost.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexMetapost.cxx
stcdll_LexNsis.o: $(srcdir)/scintilla/src/LexNsis.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexNsis.cxx
stcdll_LexOpal.o: $(srcdir)/scintilla/src/LexOpal.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexOpal.cxx
stcdll_LexOthers.o: $(srcdir)/scintilla/src/LexOthers.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexOthers.cxx
stcdll_LexPB.o: $(srcdir)/scintilla/src/LexPB.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPB.cxx
stcdll_LexPOV.o: $(srcdir)/scintilla/src/LexPOV.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPOV.cxx
stcdll_LexPS.o: $(srcdir)/scintilla/src/LexPS.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPS.cxx
stcdll_LexPascal.o: $(srcdir)/scintilla/src/LexPascal.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPascal.cxx
stcdll_LexPerl.o: $(srcdir)/scintilla/src/LexPerl.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPerl.cxx
stcdll_LexPython.o: $(srcdir)/scintilla/src/LexPython.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexPython.cxx
stcdll_LexRebol.o: $(srcdir)/scintilla/src/LexRebol.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexRebol.cxx
stcdll_LexRuby.o: $(srcdir)/scintilla/src/LexRuby.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexRuby.cxx
stcdll_LexSQL.o: $(srcdir)/scintilla/src/LexSQL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexSQL.cxx
stcdll_LexSmalltalk.o: $(srcdir)/scintilla/src/LexSmalltalk.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexSmalltalk.cxx
stcdll_LexTADS3.o: $(srcdir)/scintilla/src/LexTADS3.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexTADS3.cxx
stcdll_LexScriptol.o: $(srcdir)/scintilla/src/LexScriptol.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexScriptol.cxx
stcdll_LexSpecman.o: $(srcdir)/scintilla/src/LexSpecman.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexSpecman.cxx
stcdll_LexSpice.o: $(srcdir)/scintilla/src/LexSpice.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexSpice.cxx
stcdll_LexTCL.o: $(srcdir)/scintilla/src/LexTCL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexTCL.cxx
stcdll_LexTeX.o: $(srcdir)/scintilla/src/LexTeX.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexTeX.cxx
stcdll_LexVB.o: $(srcdir)/scintilla/src/LexVB.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexVB.cxx
stcdll_LexVHDL.o: $(srcdir)/scintilla/src/LexVHDL.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexVHDL.cxx
stcdll_LexVerilog.o: $(srcdir)/scintilla/src/LexVerilog.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexVerilog.cxx
stcdll_LexYAML.o: $(srcdir)/scintilla/src/LexYAML.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LexYAML.cxx
stcdll_LineMarker.o: $(srcdir)/scintilla/src/LineMarker.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/LineMarker.cxx
stcdll_PropSet.o: $(srcdir)/scintilla/src/PropSet.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/PropSet.cxx
stcdll_RESearch.o: $(srcdir)/scintilla/src/RESearch.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/RESearch.cxx
stcdll_ScintillaBase.o: $(srcdir)/scintilla/src/ScintillaBase.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/ScintillaBase.cxx
stcdll_Style.o: $(srcdir)/scintilla/src/Style.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/Style.cxx
stcdll_StyleContext.o: $(srcdir)/scintilla/src/StyleContext.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/StyleContext.cxx
stcdll_UniConversion.o: $(srcdir)/scintilla/src/UniConversion.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/UniConversion.cxx
stcdll_ViewStyle.o: $(srcdir)/scintilla/src/ViewStyle.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/ViewStyle.cxx
stcdll_WindowAccessor.o: $(srcdir)/scintilla/src/WindowAccessor.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/WindowAccessor.cxx
stcdll_XPM.o: $(srcdir)/scintilla/src/XPM.cxx
$(CXXC) -c -o $@ $(STCDLL_CXXFLAGS) $(srcdir)/scintilla/src/XPM.cxx
stclib_PlatWX.o: $(srcdir)/PlatWX.cpp
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/PlatWX.cpp
stclib_ScintillaWX.o: $(srcdir)/ScintillaWX.cpp
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/ScintillaWX.cpp
stclib_stc.o: $(srcdir)/stc.cpp
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/stc.cpp
stclib_AutoComplete.o: $(srcdir)/scintilla/src/AutoComplete.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/AutoComplete.cxx
stclib_CallTip.o: $(srcdir)/scintilla/src/CallTip.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/CallTip.cxx
stclib_CellBuffer.o: $(srcdir)/scintilla/src/CellBuffer.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/CellBuffer.cxx
stclib_CharClassify.o: $(srcdir)/scintilla/src/CharClassify.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/CharClassify.cxx
stclib_ContractionState.o: $(srcdir)/scintilla/src/ContractionState.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/ContractionState.cxx
stclib_Document.o: $(srcdir)/scintilla/src/Document.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/Document.cxx
stclib_DocumentAccessor.o: $(srcdir)/scintilla/src/DocumentAccessor.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/DocumentAccessor.cxx
stclib_Editor.o: $(srcdir)/scintilla/src/Editor.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/Editor.cxx
stclib_ExternalLexer.o: $(srcdir)/scintilla/src/ExternalLexer.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/ExternalLexer.cxx
stclib_Indicator.o: $(srcdir)/scintilla/src/Indicator.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/Indicator.cxx
stclib_KeyMap.o: $(srcdir)/scintilla/src/KeyMap.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/KeyMap.cxx
stclib_KeyWords.o: $(srcdir)/scintilla/src/KeyWords.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/KeyWords.cxx
stclib_LexAPDL.o: $(srcdir)/scintilla/src/LexAPDL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAPDL.cxx
stclib_LexAU3.o: $(srcdir)/scintilla/src/LexAU3.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAU3.cxx
stclib_LexAVE.o: $(srcdir)/scintilla/src/LexAVE.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAVE.cxx
stclib_LexAda.o: $(srcdir)/scintilla/src/LexAda.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAda.cxx
stclib_LexAsm.o: $(srcdir)/scintilla/src/LexAsm.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAsm.cxx
stclib_LexAsn1.o: $(srcdir)/scintilla/src/LexAsn1.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexAsn1.cxx
stclib_LexBaan.o: $(srcdir)/scintilla/src/LexBaan.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexBaan.cxx
stclib_LexBash.o: $(srcdir)/scintilla/src/LexBash.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexBash.cxx
stclib_LexBasic.o: $(srcdir)/scintilla/src/LexBasic.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexBasic.cxx
stclib_LexBullant.o: $(srcdir)/scintilla/src/LexBullant.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexBullant.cxx
stclib_LexCLW.o: $(srcdir)/scintilla/src/LexCLW.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCLW.cxx
stclib_LexCPP.o: $(srcdir)/scintilla/src/LexCPP.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCPP.cxx
stclib_LexCSS.o: $(srcdir)/scintilla/src/LexCSS.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCSS.cxx
stclib_LexCaml.o: $(srcdir)/scintilla/src/LexCaml.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCaml.cxx
stclib_LexCsound.o: $(srcdir)/scintilla/src/LexCsound.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCsound.cxx
stclib_LexConf.o: $(srcdir)/scintilla/src/LexConf.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexConf.cxx
stclib_LexCrontab.o: $(srcdir)/scintilla/src/LexCrontab.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexCrontab.cxx
stclib_LexEScript.o: $(srcdir)/scintilla/src/LexEScript.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexEScript.cxx
stclib_LexEiffel.o: $(srcdir)/scintilla/src/LexEiffel.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexEiffel.cxx
stclib_LexErlang.o: $(srcdir)/scintilla/src/LexErlang.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexErlang.cxx
stclib_LexFlagship.o: $(srcdir)/scintilla/src/LexFlagship.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexFlagship.cxx
stclib_LexForth.o: $(srcdir)/scintilla/src/LexForth.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexForth.cxx
stclib_LexFortran.o: $(srcdir)/scintilla/src/LexFortran.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexFortran.cxx
stclib_LexGui4Cli.o: $(srcdir)/scintilla/src/LexGui4Cli.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexGui4Cli.cxx
stclib_LexHTML.o: $(srcdir)/scintilla/src/LexHTML.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexHTML.cxx
stclib_LexHaskell.o: $(srcdir)/scintilla/src/LexHaskell.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexHaskell.cxx
stclib_LexInno.o: $(srcdir)/scintilla/src/LexInno.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexInno.cxx
stclib_LexKix.o: $(srcdir)/scintilla/src/LexKix.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexKix.cxx
stclib_LexLisp.o: $(srcdir)/scintilla/src/LexLisp.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexLisp.cxx
stclib_LexLout.o: $(srcdir)/scintilla/src/LexLout.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexLout.cxx
stclib_LexLua.o: $(srcdir)/scintilla/src/LexLua.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexLua.cxx
stclib_LexMMIXAL.o: $(srcdir)/scintilla/src/LexMMIXAL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexMMIXAL.cxx
stclib_LexMPT.o: $(srcdir)/scintilla/src/LexMPT.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexMPT.cxx
stclib_LexMSSQL.o: $(srcdir)/scintilla/src/LexMSSQL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexMSSQL.cxx
stclib_LexMatlab.o: $(srcdir)/scintilla/src/LexMatlab.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexMatlab.cxx
stclib_LexMetapost.o: $(srcdir)/scintilla/src/LexMetapost.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexMetapost.cxx
stclib_LexNsis.o: $(srcdir)/scintilla/src/LexNsis.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexNsis.cxx
stclib_LexOpal.o: $(srcdir)/scintilla/src/LexOpal.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexOpal.cxx
stclib_LexOthers.o: $(srcdir)/scintilla/src/LexOthers.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexOthers.cxx
stclib_LexPB.o: $(srcdir)/scintilla/src/LexPB.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPB.cxx
stclib_LexPOV.o: $(srcdir)/scintilla/src/LexPOV.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPOV.cxx
stclib_LexPS.o: $(srcdir)/scintilla/src/LexPS.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPS.cxx
stclib_LexPascal.o: $(srcdir)/scintilla/src/LexPascal.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPascal.cxx
stclib_LexPerl.o: $(srcdir)/scintilla/src/LexPerl.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPerl.cxx
stclib_LexPython.o: $(srcdir)/scintilla/src/LexPython.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexPython.cxx
stclib_LexRebol.o: $(srcdir)/scintilla/src/LexRebol.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexRebol.cxx
stclib_LexRuby.o: $(srcdir)/scintilla/src/LexRuby.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexRuby.cxx
stclib_LexSQL.o: $(srcdir)/scintilla/src/LexSQL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexSQL.cxx
stclib_LexSmalltalk.o: $(srcdir)/scintilla/src/LexSmalltalk.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexSmalltalk.cxx
stclib_LexTADS3.o: $(srcdir)/scintilla/src/LexTADS3.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexTADS3.cxx
stclib_LexScriptol.o: $(srcdir)/scintilla/src/LexScriptol.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexScriptol.cxx
stclib_LexSpecman.o: $(srcdir)/scintilla/src/LexSpecman.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexSpecman.cxx
stclib_LexSpice.o: $(srcdir)/scintilla/src/LexSpice.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexSpice.cxx
stclib_LexTCL.o: $(srcdir)/scintilla/src/LexTCL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexTCL.cxx
stclib_LexTeX.o: $(srcdir)/scintilla/src/LexTeX.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexTeX.cxx
stclib_LexVB.o: $(srcdir)/scintilla/src/LexVB.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexVB.cxx
stclib_LexVHDL.o: $(srcdir)/scintilla/src/LexVHDL.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexVHDL.cxx
stclib_LexVerilog.o: $(srcdir)/scintilla/src/LexVerilog.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexVerilog.cxx
stclib_LexYAML.o: $(srcdir)/scintilla/src/LexYAML.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LexYAML.cxx
stclib_LineMarker.o: $(srcdir)/scintilla/src/LineMarker.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/LineMarker.cxx
stclib_PropSet.o: $(srcdir)/scintilla/src/PropSet.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/PropSet.cxx
stclib_RESearch.o: $(srcdir)/scintilla/src/RESearch.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/RESearch.cxx
stclib_ScintillaBase.o: $(srcdir)/scintilla/src/ScintillaBase.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/ScintillaBase.cxx
stclib_Style.o: $(srcdir)/scintilla/src/Style.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/Style.cxx
stclib_StyleContext.o: $(srcdir)/scintilla/src/StyleContext.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/StyleContext.cxx
stclib_UniConversion.o: $(srcdir)/scintilla/src/UniConversion.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/UniConversion.cxx
stclib_ViewStyle.o: $(srcdir)/scintilla/src/ViewStyle.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/ViewStyle.cxx
stclib_WindowAccessor.o: $(srcdir)/scintilla/src/WindowAccessor.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/WindowAccessor.cxx
stclib_XPM.o: $(srcdir)/scintilla/src/XPM.cxx
$(CXXC) -c -o $@ $(STCLIB_CXXFLAGS) $(srcdir)/scintilla/src/XPM.cxx
# Include dependency info, if present:
@IF_GNU_MAKE@-include .deps/*.d
.PHONY: all install uninstall clean distclean install_stcdll uninstall_stcdll install_stclib uninstall_stclib
<file_sep>/fbide-rw/sdk/scriptmanager.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include <wx/textfile.h>
#include "manager.h"
#include "scriptmanager.h"
#include "v8/v8.h"
using namespace fb;
using namespace v8;
// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called. Prints its arguments on stdout separated by
// spaces and ending with a newline.
Handle<Value> JsPrint(const Arguments& args)
{
wxString msg = "";
bool first = true;
for (int i = 0; i < args.Length(); i++)
{
if (first) first = false;
else msg += "\n";
//convert the args[i] type to normal char* string
String::AsciiValue str(args[i]);
msg += *str;
}
wxString version = "V8: ";
version += V8::GetVersion();
wxMessageBox(msg, version);
//returning Undefined is the same as returning void...
return v8::Undefined();
}
/**
* Show JavaScript errors
*/
void jsMessages (Handle<Message> message, Handle<Value> data)
{
String::AsciiValue str(message->Get());
wxString msg;
msg << *str << " on line " << message->GetLineNumber() << "\n"
<< *String::AsciiValue(message->GetSourceLine())
;
wxMessageBox(msg, "JavaScript error");
}
/**
* Manager class implementation
*/
struct TheScriptManager : ScriptManager
{
// create
TheScriptManager ()
{}
// destroy
~TheScriptManager ()
{}
// execute arbitraru javascript
virtual void Execute (const wxString & fileName)
{
// check if file exists
if (!::wxFileExists(fileName))
{
wxLogMessage("file '" + fileName + "' is not found");
return;
}
// read file in
wxTextFile file(fileName);
if (!file.Open())
{
wxLogMessage("could not open '" + fileName + "'");
return;
}
// get the content
wxString code = file.GetFirstLine();
while ( !file.Eof() ) code += "\n" + file.GetNextLine();
// Register the error callback
V8::AddMessageListener(jsMessages);
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a template for the global object and set the
// built-in global functions.
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("print"), FunctionTemplate::New(JsPrint));
// Each processor gets its own context so different processors
// do not affect each other.
Persistent<Context> context = Context::New(NULL, global);
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Handle<String> source = String::New(code.c_str());
// Compile the source code.
Handle<Script> script = Script::Compile(source);
if (script.IsEmpty()) return;
// javascript exceptions
TryCatch trycatch;
Handle<Value> result = script->Run();
if (result.IsEmpty())
{
Handle<Value> exception = trycatch.Exception();
String::AsciiValue exception_str(exception);
wxMessageBox(*exception_str, "Exception");
}
// Dispose the persistent context.
context.Dispose();
}
};
// Implement Manager
IMPLEMENT_MANAGER(ScriptManager, TheScriptManager)
<file_sep>/fbide-wx/Plugins/ModMargin/main.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "sdk/Manager.h"
#include "sdk/PluginManager.h"
#include "sdk/PluginArtProvider.h"
#include "sdk/EditorManager.h"
#include "sdk/Editor.h"
#include "sdk/EditorEvent.h"
#include "sdk/StyleInfo.h"
using namespace fb;
class ModMarginPlugin : public CPluginBase
{
public :
enum {
MARGIN_NUMBER = 1,
MARKER_SAVED = 0,
MARKER_EDITED = 1,
MARKER_FLAGS = (1 << MARKER_SAVED) | (1 << MARKER_EDITED),
};
// Attach plugin
bool Attach ()
{
// register handler
GET_EDITORMGR()->Bind(
CEditorManager::EVT_OPEN,
MakeDelegate(this, &ModMarginPlugin::NewDocument)
);
return true;
}
/**
* Open new editor
*/
void NewDocument (int evt, CEditor & editor)
{
const CStyleInfo & info = GET_MGR()->GetStyleParser(_T("default"))
->GetStyle(_T(".edit-margin"));
editor.SetMarginWidth(MARGIN_NUMBER, 4);
editor.SetMarginType(MARGIN_NUMBER, wxSCI_MARGIN_SYMBOL);
editor.SetMarginWidth(MARGIN_NUMBER, 4);
editor.SetMarginMask(MARGIN_NUMBER, (1 << MARKER_SAVED) | (1 << MARKER_EDITED) );
// edited marker
editor.MarkerDefine(MARKER_EDITED, wxSCI_MARK_FULLRECT);
editor.MarkerSetBackground(MARKER_EDITED, info.bg);
// saved marker
editor.MarkerDefine(MARKER_SAVED, wxSCI_MARK_FULLRECT);
editor.MarkerSetBackground(MARKER_SAVED, info.fg);
// insert text event
editor.Bind (
CEditorEvent::TYPE_TEXT_INSERT,
MakeDelegate(this, &ModMarginPlugin::ModifyText)
);
// delete text event
editor.Bind (
CEditorEvent::TYPE_TEXT_DELETE,
MakeDelegate(this, &ModMarginPlugin::ModifyText)
);
}
/**
* Text modified by a user
*/
void ModifyText (CEditor & editor, CEditorEvent & event)
{
// update margin
editor.MarkerAdd(event.startLine, MARKER_EDITED);
}
// Detach plugin
bool Detach (bool force)
{
// unregister handler
GET_EDITORMGR()->UnBind(
CEditorManager::EVT_OPEN,
MakeDelegate(this, &ModMarginPlugin::NewDocument)
);
return true;
}
};
namespace
{
CPluginProvider<ModMarginPlugin, PLUGINTYPE_TOOL> plugin (_T("ModMargin"));
}
#if 0
/**
* Track changes per line. Needed for
* modification margin
*/
struct CChangeHistory
{
// Number of elements allocaed per block.
enum {
STATES_IN_CELL = 16,
BITS_PER_STATE = 2,
STATES_FLAG = (2 << BITS_PER_STATE) - 1
};
/**
* Construct new history object
*/
CChangeHistory () {}
// Set bit flags
static inline void SET_FLAG (int & value, int flag) {value |= flag;}
// unset bit flags
static inline void UNSET_FLAG (int & value, int flag) {value &= (~flag);}
/**
* Pop topmost and check next value
*/
int Pop (int line)
{
// no state here
if ((int)m_lines.size() <= line) return false;
// get mod
IntVector & mod = m_lines[line];
// if it's too small?
if (mod.size() < 2) return false;
// no states? pop topmost
if (mod[0] == 0) return false;
int cellCount = --mod[0];
LOG_MSG_INT("Pop:", cellCount);
// get offset and index into bitset
int offset = (cellCount % STATES_IN_CELL) * BITS_PER_STATE;
int index = (cellCount / STATES_IN_CELL) + 1;
// get the bit value
return (mod[index] >> offset) & STATES_FLAG;
}
/**
* check current state and "undo"
*/
int CheckAndRedo (int line)
{
// no state here
if ((int)m_lines.size() <= line) return 0;
// get mod
IntVector & mod = m_lines[line];
// if it's too small?
if (mod.size() < 2) return 0;
// get counter
int cellCount = ++mod[0];
LOG_MSG_INT("CheckAndRedo:", cellCount);
// if (cellCount == 0) return 0;
// get offset and index into bitset
int offset = (cellCount % STATES_IN_CELL) * BITS_PER_STATE;
int index = (cellCount / STATES_IN_CELL) + 1;
// get the bit value
return (mod[index] >> offset) & STATES_FLAG;
}
/**
* Push line state
*/
void Push(int line, int value)
{
if (line >= (int)m_lines.size())
{
// m_lines.resize(m_lines.capacity() + BUFFER_SIZE);
for (int i = m_lines.size(); i <= line; i++)
m_lines.push_back(IntVector());
}
// get mod
IntVector & mod = m_lines[line];
// get the cell or add a new entry
if (mod.size() < (size_t)2)
{
mod.push_back(0);
mod.push_back(0);
}
// get counter and increment count
int cellCount = mod[0]++;
LOG_MSG_INT("Push:", cellCount);
// get offset (bit offset) and index
int offset = (cellCount % STATES_IN_CELL) * BITS_PER_STATE;
int index = (cellCount / STATES_IN_CELL) + 1;
// expand array if needed
if ((int)mod.size() <= index) mod.push_back(0);
// set cell value
mod[index] = (mod[index] & (~(STATES_FLAG<<offset))) | ((value & STATES_FLAG) << offset);
}
/**
* Set current state to given value
*/
void SetCurrent (int line, int value)
{
// no state for the line?
if (line >= (int)m_lines.size()) return;
// get mod
IntVector & mod = m_lines[line];
// no state for the line yet?
if (mod.size() < (size_t)2) return;
// no states?
int cellCount = mod[0];
LOG_MSG_INT("SetCurrent:", cellCount);
// if (cellCount == 0) return;
// cellCount--;
// get offset (bit offset) and index
int offset = (cellCount % STATES_IN_CELL) * BITS_PER_STATE;
int index = (cellCount / STATES_IN_CELL) + 1;
// set cell value
mod[index] = (mod[index] & (~(STATES_FLAG<<offset))) | ((value & STATES_FLAG) << offset);
}
/**
* Set all states to
*/
void SetAllAndCurrentTo (CEditor * editor, int state, int currentState)
{
// generate common flag
int flag = (state & STATES_FLAG);
for (int offset = BITS_PER_STATE;
offset < (STATES_IN_CELL * BITS_PER_STATE);
offset += BITS_PER_STATE)
flag |= (state & STATES_FLAG) << offset;
// iterate through the lines
for (int line = 0; line < m_lines.size(); line++)
{
for (int cell = 1; cell < m_lines[line].size(); cell++)
{
m_lines[line][cell] = flag;
}
if (m_lines[line].size() > 1)
{
SetCurrent(line, currentState);
SetMargins(editor, line, currentState);
}
}
}
/**
* Add line to pending lines.
*/
void AddPendingLine (int line)
{
// add the line
m_pending.push_back(line);
}
/**
* Commit pending lines
*/
void PushAndMarkPending (CEditor * editor, int markers)
{
for ( int i = m_pending.size(); i ; )
{
int line = m_pending[--i];
Push (line, editor->MarkerGet(line) & MARKER_FLAGS);
SetMargins(editor, line, markers);
}
// reset pending
m_pending.clear();
}
/**
* Pop pending
*/
void PopPending (CEditor * editor)
{
// Push the states
// LOG_MSG_INT("PopPending:", m_pending.size());
for ( int i = m_pending.size(); i ; )
{
int line = m_pending[--i];
SetCurrent(line, editor->MarkerGet(line) & MARKER_FLAGS);
SetMargins(editor, line, Pop(line));
}
// reset pending
m_pending.clear();
}
/**
* Undo pending
*/
void UndoPending (CEditor * editor)
{
// Push the states
// LOG_MSG_INT("UndoPending:", m_pending.size());
for ( int i = m_pending.size(); i ; )
{
int line = m_pending[--i];
SetMargins(editor, line, CheckAndRedo(line));
}
// reset pending
m_pending.clear();
}
/**
* Set editor margins
*/
void SetMargins (CEditor * editor, int line, int markers)
{
// update margin
if (markers & (1 << MARKER_EDITED))
editor->MarkerAdd(line, MARKER_EDITED);
else
editor->MarkerDelete(line, MARKER_EDITED);
// set saved
if (markers & (1 << MARKER_SAVED))
editor->MarkerAdd(line, MARKER_SAVED);
else
editor->MarkerDelete(line, MARKER_SAVED);
}
// vector of int's
typedef std::vector<int> IntVector;
// the lines vector
typedef std::vector<IntVector> LinesVector;
LinesVector m_lines;
IntVector m_pending;
};
// Manage change margin
void updateChangeMargin (wxScintillaEvent & event)
{
// modification type
int mod = event.GetModificationType();
// get line range affected
int startLine = m_parent->LineFromPosition(event.GetPosition());
int linesModified = event.GetLinesAdded();
// append affected lines
m_changes.AddPendingLine(startLine);
if (linesModified > 0)
{
for ( ; linesModified > 0; linesModified-- )
m_changes.AddPendingLine(startLine + linesModified);
}
/*
else if (linesModified < 0)
{
int delLines = abs(linesModified);
if (mod & wxSCI_PERFORMED_USER)
{
for ( ; delLines; delLines--)
{
int line = startLine + delLines;
LOG_INT(line);
m_changes.Push (
line,
m_parent->MarkerGet(line) & MARKER_FLAGS
);
}
}
else
{
LOG_MSG_INT("----------->", delLines);
for ( ; delLines; delLines--)
m_changes.AddPendingLine(startLine + delLines);
}
}
*/
// performed by user (edit, delete, insert)
if (mod & wxSCI_PERFORMED_USER)
{
m_changes.PushAndMarkPending(m_parent, 1 << MARKER_EDITED);
}
// performed UNDO
else if (mod & wxSCI_PERFORMED_UNDO)
{
m_changes.PopPending(m_parent);
}
// performed REDO
else if (mod & wxSCI_PERFORMED_REDO)
{
m_changes.UndoPending(m_parent);
}
}
/*
MARKER_SAVED = 0,
MARKER_EDITED = 1,
MARKER_FLAGS = (1 << MARKER_SAVED) | (1 << MARKER_EDITED),
*/
#endif
<file_sep>/fbide-rw/bin/Release/test.js
var arr = [
"one", "two", "three"
];
function greet (name)
{
var msg = "";
for (i in arr)
{
msg += arr[i] + " ";
}
return msg + name;
}
print (greet("World"));
<file_sep>/fbide-vs/Sdk/Ui/MenuHandler.h
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* Handle menus
*/
struct UiMenuHandler
{
// constructor
UiMenuHandler();
// Initalize
void Init (wxMenuBar *);
// Uninitalize
void UnInit ();
// Load from XML
void Load (wxXmlNode * node, wxMenu * parent = nullptr);
// Get menu by ID
wxMenu * GetMenu (const wxString & id);
// Add new menu
void AddMenu (const wxString & id, wxMenu * menu, bool show = false);
// Add a new item to the menu
void AddMenuItem (const wxString & id, wxMenu * parent);
// Flag check items
void OnCmdMgrEvent(wxCommandEvent & event);
private :
HashMap<wxMenu *> m_map; // hold id-menu associations
wxMenuBar * m_mbar; // the menu bar
};
}
<file_sep>/fbide-rw/app/fbide.cpp
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
* Copyright (C) The FBIde development team
*/
#include "wx_pch.h"
#include "manager.h"
#include "uimanager.h"
#include "scriptmanager.h"
#include "variant.h"
#include "registry.h"
#include <wx/stdpaths.h>
#include <wx/apptrait.h>
using namespace fb;
/**
* The application
*/
class FBIde : public wxApp
{
/**
* start up
*/
virtual bool OnInit()
{
// load ui
GET_UIMGR()->Load();
/*if (argc > 1)
{
wxStandardPathsBase & sp = this->GetTraits()->GetStandardPaths();
auto path = ::wxPathOnly(sp.GetExecutablePath());
GET_SCRIPTMGR()->Execute(path + "/" + argv[1]);
}*/
return true;
}
/**
* Called on exit
*/
virtual int OnExit()
{
Manager::Release();
return wxApp::OnExit();
}
};
IMPLEMENT_APP(FBIde);
|
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
|
[
"JavaScript",
"Makefile",
"INI",
"Text",
"C",
"C++"
] | 96
|
C++
|
albeva/fbide-old-svn
|
bde1e72e7e182fabc89452738f7655e3307296f4
|
4add934982ce1ce95960c9b3859aeaf22477f10b
|
refs/heads/master
|
<file_sep>package edu.feicui.main.redditnews.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
import edu.feicui.main.redditnews.R;
import edu.feicui.main.redditnews.info.NewsInfo;
/**
* Created by Administrator on 2016/10/28.
*/
public class MainAdapter extends MyAdapter<NewsInfo>{
Context mContext;
public MainAdapter(Context context) {
super(context);
this.mContext=context;
}
@Override
public View setView(int position, View convertView, ViewGroup parent) {
Holder holder=null;
if (convertView == null) {
holder=new Holder();
convertView= LayoutInflater.from(mContext).inflate(R.layout.adapter_main,parent,false);
holder.mTxt_title= (TextView) convertView.findViewById(R.id.txt_adapter_main_title);
holder.mTxt_stamp= (TextView) convertView.findViewById(R.id.txt_adapter_main_stamp);
holder.mTxt_content= (TextView) convertView.findViewById(R.id.txt_adapter_main_content);
holder.mImg= (CircleImageView) convertView.findViewById(R.id.img_adapter_main);
// holder.mLyt = (LinearLayout) convertView.findViewById(R.id.lyt_adapter);
convertView.setTag(holder);
}else{
holder= (Holder) convertView.getTag();
}
holder.mTxt_title.setText(mList.get(position).getTitle());
holder.mTxt_content.setText(mList.get(position).getSummary());
holder.mTxt_stamp.setText(mList.get(position).getStamp());
// holder.mLyt.setBackgroundResource(mBackground[position%mBackground.length]);
Picasso.with(convertView.getContext()).load(mList.get(position).getIcon()).into(holder.mImg);
return convertView;
}
static class Holder{
CircleImageView mImg;
TextView mTxt_title;
TextView mTxt_content;
TextView mTxt_stamp;
LinearLayout mLyt;
}
}
<file_sep>package edu.feicui.main.redditnews.main;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Administrator on 2016/11/2.
*/
public class AccountActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onContentChanged() {
super.onContentChanged();
}
}
<file_sep>package edu.feicui.main.redditnews.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import edu.feicui.main.redditnews.R;
import edu.feicui.main.redditnews.info.HttpInfo;
import edu.feicui.main.redditnews.inter.OnLoadResponseListener;
import edu.feicui.main.redditnews.util.HttpUtil;
/**
* Created by Administrator on 2016/11/2.
*/
public class RegisterFragment extends Fragment implements View.OnClickListener,OnLoadResponseListener{
Button mBtn;
EditText mEdit_email;
EditText mEdit_name;
EditText mEdit_password;
RequestQueue mRequestQueue;
private static final String PREFS_NAME = "register";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_register,container,false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBtn= (Button) view.findViewById(R.id.btn_register);
mEdit_email= (EditText) view.findViewById(R.id.edit_register_email);
mEdit_name= (EditText) view.findViewById(R.id.edit_register_name);
mEdit_password= (EditText) view.findViewById(R.id.edit_register_password);
mBtn.setOnClickListener(this);
mRequestQueue = Volley.newRequestQueue(getActivity());
}
@Override
public void onClick(View v) {
String email = mEdit_email.getText().toString();
String name = mEdit_name.getText().toString();
String password = mEdit_password.getText().toString();
HttpUtil.collectionGET(HttpInfo.BASE_URL+HttpInfo.REGISTER+"ver=1&uid="+name+"&email="+email+"&pwd="+password,this,mRequestQueue);
// Toast.makeText(getActivity(),explain,Toast.LENGTH_SHORT).show();
}
@Override
public void getResponse(String s) {
Log.e("==","message=="+s);
try {
JSONObject jsonObject=new JSONObject(s);
String message = jsonObject.getString("message");
int status = jsonObject.getInt("status");
JSONObject data = jsonObject.getJSONObject("data");
int result = data.getInt("result");
String token = data.getString("token");
String explain = data.getString("explain");
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt("result",result);
edit.putString("token",token);
edit.putString("explain",explain);
edit.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
<file_sep>package edu.feicui.main.redditnews.main;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import edu.feicui.main.redditnews.R;
/**
* Created by Administrator on 2016/10/27.
*/
public class LogoActivity extends Activity {
private static final String PREFS_NAME = "NoFirst";
private static final String IS_FIRST = "first";
ImageView mImg_logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = this.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean flag = sharedPreferences.getBoolean(IS_FIRST, true);
if (flag) {//第一次
int position=0;
Intent intent=new Intent(LogoActivity.this,GuidActivity.class);
intent.putExtra("position",position);
startActivity(intent);
//获取编辑器对象
SharedPreferences.Editor edit = sharedPreferences.edit();
//使用编辑器对象添加数据
edit.putBoolean(IS_FIRST,false);
//提交数据
edit.commit();
this.finish();
}else{//不是第一次
setContentView(R.layout.activity_logo);
mImg_logo= (ImageView) findViewById(R.id.img_logo);
Animation loadAnimation = AnimationUtils.loadAnimation(this, R.anim.change);
mImg_logo.startAnimation(loadAnimation);
loadAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//跳转
Intent intent=new Intent(LogoActivity.this,CenterActivity.class);
startActivity(intent);
LogoActivity.this.finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
});
}
}
}
<file_sep>package edu.feicui.main.redditnews.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import edu.feicui.main.redditnews.R;
import edu.feicui.main.redditnews.main.CenterActivity;
/**
* Created by Administrator on 2016/10/27.
*/
public class LeftFragment extends Fragment implements View.OnClickListener{
ImageView mImg;
LinearLayout mLyt_news;
LinearLayout mLyt_favorite;
LinearLayout mLyt_local;
LinearLayout mLyt_comment;
LinearLayout mLyt_photo;
MainFragment mMainFragment;
//开始创建fragment方法
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_left,container,false);
}
//表示fragment中的View正式创建成功
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLyt_news= (LinearLayout) view.findViewById(R.id.lyt_left_news);
mLyt_favorite = (LinearLayout) view.findViewById(R.id.lyt_left_favorite);
mLyt_local= (LinearLayout) view.findViewById(R.id.lyt_left_local);
mLyt_comment= (LinearLayout) view.findViewById(R.id.lyt_left_comment);
mLyt_photo= (LinearLayout) view.findViewById(R.id.lyt_left_photo);
mMainFragment=new MainFragment();
mLyt_news.setOnClickListener(this);
mLyt_favorite.setOnClickListener(this);
mLyt_local.setOnClickListener(this);
mLyt_comment.setOnClickListener(this);
mLyt_photo.setOnClickListener(this);
}
//当前fragment所在的Activity正式被创建的方法
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.lyt_left_news:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flyt_main,mMainFragment);
fragmentTransaction.commit();
((CenterActivity)getActivity()).closeMenu();
break;
}
}
}
<file_sep>package edu.feicui.main.redditnews.info;
/**
* Created by Administrator on 2016/11/2.
*/
public class HttpInfo {
public static final String BASE_URL="http://192.168.3.11:9092/newsClient/";
public static final String NEWS_URL="path/news_list?ver=1&subid=1&dir=1&nid=1&stamp=20140321&cnt=20";
public static final String REGISTER="path/user_register?";
public static final String LOGIN="path/user_login?";
public static final String FORGETPASS="path/user_forgetpass?";
}
<file_sep>package edu.feicui.main.redditnews.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import edu.feicui.main.redditnews.R;
import edu.feicui.main.redditnews.info.HttpInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by Administrator on 2016/11/2.
*/
public class LoginFragment extends Fragment implements View.OnClickListener{
// ViewPager mVp;
Button mBtn_register;
Button mBtn_password;
Button mBtn_login;
EditText mEdit_name;
EditText mEdit_password;
RegisterFragment mRegisterFragment;
PasswordFragment mPasswordFragment;
OkHttpClient mClient;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_login,container,false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBtn_register= (Button) view.findViewById(R.id.btn_login_zhuce);
mBtn_password= (Button) view.findViewById(R.id.btn_login_pass);
mBtn_login= (Button) view.findViewById(R.id.btn_login_login);
mEdit_name= (EditText) view.findViewById(R.id.edit_login_name);
mEdit_password= (EditText) view.findViewById(R.id.edit_login_password);
// mVp= (ViewPager) view.findViewById(R.id.vp_login);
mBtn_register.setOnClickListener(this);
mBtn_login.setOnClickListener(this);
mBtn_password.setOnClickListener(this);
mRegisterFragment = new RegisterFragment();
mPasswordFragment=new PasswordFragment();
// mVp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// @Override
// public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
// }
//
// @Override
// public void onPageScrollStateChanged(int state) {
//
// }
//
// @Override
// public void onPageSelected(int position) {
//
// }
// });
}
String string;
Handler handler;
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_login_zhuce:{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flyt_main,mRegisterFragment);
fragmentTransaction.commit();
break;
}
case R.id.btn_login_pass:{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flyt_main,mPasswordFragment);
fragmentTransaction.commit();
break;
}
case R.id.btn_login_login:{
String name = mEdit_name.getText().toString();
String password = mEdit_password.getText().toString();
mClient=new OkHttpClient();
//构造器模式,构造请求
FormBody.Builder formbuilder=new FormBody.Builder();
formbuilder.add("ver","1");
formbuilder.add("uid",name);
formbuilder.add("pwd",password);
formbuilder.add("device","0");
Request.Builder requestbuilder=new Request.Builder();
//通过构造器构建请求 网址
requestbuilder.url(HttpInfo.BASE_URL+HttpInfo.LOGIN);
//获取请求体 FormBody extends RequestBody
RequestBody requestBody=formbuilder.build();
//使用构造器,将请求体放入请求中
requestbuilder.post(requestBody);
// 构建请求
Request request = requestbuilder.build();
//获取call模型
Call call = mClient.newCall(request);
//执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//响应体
ResponseBody responseBody = response.body();
string = responseBody.string();
handler.sendEmptyMessage(1);
}
});
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("---","string=="+string);
try {
JSONObject jsonObject=new JSONObject(string);
String message = jsonObject.getString("message");
String status = jsonObject.getString("status");
JSONObject data = jsonObject.getJSONObject("data");
int result = data.getInt("result");
String token = data.getString("token");
String explain = data.getString("explain");
} catch (JSONException e) {
e.printStackTrace();
}
}
};
}
}
}
}
|
abfab53a3bb153a2fd0c917d2a8dd67ba2ce75be
|
[
"Java"
] | 7
|
Java
|
zhao774740820/news
|
4461ecb0b8784433411658b5ec13d7710b08df79
|
2f8fe64627b7e3cd4cb447766f53d513b0fc2a90
|
refs/heads/master
|
<file_sep>package com.zh.crawler.tool;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class DownTool {
// 根据URL和网页类型生成需要保存的网页的文件名,去除 URL中的非文件名字符
private String getFileNameByUrl(String url, String contentType) {
// 移除 "http://"这七个字符
url = url.substring(7);
// 确认抓取到的页面为 text/html 类型
if (contentType.indexOf("html") != -1) {
// 把所有的url中的特殊符号转化成下划线
url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
} else {
url = url.replaceAll("[\\?/:*|<>\"]", "_") + "." + contentType.substring(contentType.lastIndexOf("/") + 1);
}
return url;
}
// 保存网页字节数组到本地文件,filePath为要保存的文件的相对地址
public void saveToLocal(byte[] data, String filePath) {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath)));
for (int i = 0; i < data.length; i++)
out.write(data[i]);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveToLocal(InputStream ins, String filePath) {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(filePath));
int hasRead = 0;
byte[] b = new byte[4096];
while ((hasRead = ins.read(b)) > 0) {
bos.write(b, 0, hasRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String readToString(InputStream ins) {
InputStreamReader inputStreamReader = null;
BufferedReader bis = null;
StringBuffer stringBuffer = new StringBuffer();
try {
inputStreamReader = new InputStreamReader(ins, "UTF-8");
bis = new BufferedReader(inputStreamReader);
String readLine = null;
while ((readLine = bis.readLine()) != null) {
stringBuffer.append(readLine);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
// 下载URL指向的网页
public String downloadFile(String url) {
String filePath = null;
// 1.生成 HttpClinet对象并设置参数
HttpClient httpClient = new HttpClient();
// 设置 HTTP连接超时 5s
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
// 2.生成 GetMethod对象并设置参数
GetMethod getMethod = new GetMethod(url);
// 设置 get请求超时 5s
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 设置请求重试处理
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
// 3.执行GET请求
try {
int statusCode = httpClient.executeMethod(getMethod);
// 判断访问的状态码
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
filePath = null;
}
// 4.处理HTTP响应内容
// 改用输入流没有警告
InputStream bodyStream = getMethod.getResponseBodyAsStream();
// 读取为字节数组
// byte[] responseBody = getMethod.getResponseBody();
// 根据网页url生成保存时的文件名
filePath = "C:/tmp/lucene/data/html" + File.separator
+ getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
// saveToLocal(responseBody, filePath);
saveToLocal(bodyStream, filePath);
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查你的http地址是否正确");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
e.printStackTrace();
} finally {
// 释放连接
getMethod.releaseConnection();
}
return filePath;
}
}<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zh.lucene</groupId>
<artifactId>lucene</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>lucene</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lucene.version>5.5.2</lucene.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version> ${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>${lucene.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-queryparser -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>${lucene.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.0.2-FINAL</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.htmlparser/htmlparser -->
<dependency>
<groupId>org.htmlparser</groupId>
<artifactId>htmlparser</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
</project> <file_sep># code-store
zt's code store
<file_sep>package com.zh.crawler;
import java.util.Set;
import com.zh.crawler.filter.LinkFilter;
import com.zh.crawler.tool.DownTool;
import com.zh.crawler.tool.HtmlParserTool;
import com.zh.crawler.vo.CrawlerQueue;
public class Crawler {
// 使用种子初始化URL队列
private void initCrawlerWithSeeds(String[] seeds) {
for (int i = 0; i < seeds.length; i++)
CrawlerQueue.addUnvisitedUrl(seeds[i]);
}
// 定义过滤器,提取以 http://www.xxxx.com开头的链接
public void crawling(String[] seeds) {
LinkFilter filter = new LinkFilter() {
public boolean accept(String url) {
if (url.startsWith("http://news.ifeng.com"))
return true;
else
return false;
}
};
// 初始化URL队列
initCrawlerWithSeeds(seeds);
// 循环条件:待抓取的链接不空且抓取的网页不多于1000
while (!CrawlerQueue.unVisitedUrlsEmpty() && CrawlerQueue.getVisitedUrlNum() <= 1000) {
// 队头URL出队列
String visitUrl = (String) CrawlerQueue.unVisitedUrlDeQueue();
if (visitUrl == null)
continue;
DownTool downLoader = new DownTool();
// 下载网页
downLoader.downloadFile(visitUrl);
// 该 URL放入已访问的URL中
CrawlerQueue.addVisitedUrl(visitUrl);
// 提取出下载网页中的URL
Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
// 新的未访问的URL入队
for (String link : links) {
CrawlerQueue.addUnvisitedUrl(link);
}
}
}
// main方法入口
public static void main(String[] args) {
Crawler crawler = new Crawler();
crawler.crawling(new String[] {"http://ifeng.com/"});
}
}
|
60a6fb9dcd2f0ab64d91d11f5cc0a8071aa6f2a2
|
[
"Markdown",
"Java",
"Maven POM"
] | 4
|
Java
|
zhtd/Code-Repository
|
a901169fea68325fb41f4fa69fa855b51fa6efe6
|
720ef6dd46465a47302ef9504ff6f48a4a6df3b8
|
refs/heads/master
|
<file_sep>//
// WXClient.swift
// SimpleWeather
//
// Created by <NAME> on 1/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import CoreLocation
import ObjectMapper
import Alamofire
class WXClient {
let apiKey : String?
init() {
var keys : NSDictionary?
if let path = Bundle.main.path(forResource: "keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
self.apiKey = dict["openWeatherApiKey"] as? String
} else {
self.apiKey = nil
}
}
func fetchCurrentConditionsForLocation(location: CLLocationCoordinate2D, completion: @escaping (WXCondition?) -> Void) {
Alamofire.request(OpenWeatherRouter.current(location, self.apiKey!))
.validate(statusCode: 200..<300)
.responseJSON{ response in
guard response.result.isSuccess else {
print("Error getting current conditions: \(response.result.error)")
completion(nil)
return
}
guard let responseJSON = response.result.value as? [String: Any] else {
print("Invalid current conditons info from the service: \(response.result.value)")
completion(nil)
return
}
completion(WXCondition(JSON: responseJSON)!)
}
}
func fetchHourlyForecastForLocation(location: CLLocationCoordinate2D, completion: @escaping ([WXCondition]) -> Void) {
Alamofire.request(OpenWeatherRouter.hourly(location, self.apiKey!))
.validate(statusCode: 200..<300)
.responseJSON{ response in
guard response.result.isSuccess else {
print("Error getting hourly forecast: \(response.result.error)")
completion([WXCondition]())
return
}
guard let responseJSON = response.result.value as? [String: Any] else {
print("Invalid hourly forecast info from the service: \(response.result.value)")
completion([WXCondition]())
return
}
completion(Mapper<WXCondition>().mapArray(JSONArray: responseJSON["list"] as! [[String: Any]])!)
}
}
}
<file_sep>//
// ViewController.swift
// SimpleWeather
//
// Created by <NAME> on 1/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import CoreLocation
class WXController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, CLLocationManagerDelegate {
var backgroundImageView : UIImageView?
var blurredImageView : UIImageView?
var tableView : UITableView?
var screenHeight : CGFloat?
var temperatureLabel : UILabel?
var cityLabel : UILabel?
var conditionsLabel : UILabel?
var iconView : UIImageView?
var hiloLabel : UILabel?
private let hourlyDateFormatter = DateFormatter()
private(set) var currentLocation: CLLocation? {
didSet {
self.updateCurrentConditions()
self.updateHourlyForecast()
}
}
private(set) var hourlyConditions: [WXCondition]? {
didSet {
self.tableView?.reloadData()
}
}
private let locationManager: CLLocationManager = CLLocationManager()
private let client: WXClient = WXClient()
private var isFirstUpdate: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
hourlyDateFormatter.dateFormat = "h a"
self.screenHeight = UIScreen.main.bounds.height
let background = UIImage(named: "bg")
self.backgroundImageView = UIImageView(image: background)
self.view.addSubview(self.backgroundImageView!)
self.blurredImageView = UIImageView()
self.blurredImageView?.contentMode = .scaleAspectFill
self.blurredImageView?.alpha = 0
// can't blur it because of having issues with import LBBlurredImage library
self.blurredImageView = UIImageView(image: background)
self.view.addSubview(self.blurredImageView!)
self.tableView = UITableView()
self.tableView?.backgroundColor = .clear
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.separatorColor = UIColor.white.withAlphaComponent(0.2)
self.tableView?.isPagingEnabled = true
self.view.addSubview(self.tableView!)
let headerFrame = UIScreen.main.bounds
let inset : CGFloat = 20
let temperatureHeight : CGFloat = 110
let hiloHeight : CGFloat = 40
let iconHeight : CGFloat = 30
let hiloFrame = CGRect(x: inset,
y: headerFrame.size.height - hiloHeight,
width: headerFrame.size.width - (2 * inset),
height: hiloHeight)
let temperatureFrame = CGRect(x: inset,
y: headerFrame.size.height - (temperatureHeight + hiloHeight),
width: headerFrame.size.width - (2 * inset),
height: temperatureHeight)
let iconFrame = CGRect(x: inset,
y: temperatureFrame.origin.y - iconHeight,
width: iconHeight,
height: iconHeight)
var conditionsFrame = iconFrame
conditionsFrame.size.width = self.view!.bounds.size.width - (((2 * inset) + iconHeight) + 10)
conditionsFrame.origin.x = iconFrame.origin.x + (iconHeight + 10)
let header = UIView(frame: headerFrame)
header.backgroundColor = .clear
self.tableView?.tableHeaderView = header
// bottom left
self.temperatureLabel = UILabel(frame: temperatureFrame)
self.temperatureLabel?.backgroundColor = .clear
self.temperatureLabel?.textColor = .white
self.temperatureLabel?.text = "0°"
self.temperatureLabel?.font = UIFont(name: "HelveticaNeue-UltraLight", size: 120)
header.addSubview(self.temperatureLabel!)
// bottom left
self.hiloLabel = UILabel(frame: hiloFrame)
self.hiloLabel?.backgroundColor = .clear
self.hiloLabel?.textColor = .white
self.hiloLabel?.text = "0° / 0°"
self.hiloLabel?.font = UIFont(name: "HelveticaNeue-UltraLight", size: 28)
header.addSubview(self.hiloLabel!)
// top
self.cityLabel = UILabel(frame: CGRect(x: 0, y: 20, width: self.view!.bounds.size.width, height: 30))
self.cityLabel?.backgroundColor = .clear
self.cityLabel?.textColor = .white
self.cityLabel?.text = "Loading..."
self.cityLabel?.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
self.cityLabel?.textAlignment = .center
header.addSubview(self.cityLabel!)
self.conditionsLabel = UILabel(frame: conditionsFrame)
self.conditionsLabel?.backgroundColor = .clear
self.conditionsLabel?.textColor = .white
self.conditionsLabel?.text = "Clear"
self.conditionsLabel?.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
header.addSubview(self.conditionsLabel!)
// bottom left
self.iconView = UIImageView(frame: iconFrame)
self.iconView?.image = UIImage(named: "weather-clear")
self.iconView?.contentMode = .scaleAspectFit
self.iconView?.backgroundColor = .clear
header.addSubview(self.iconView!)
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.findCurrentLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let bounds = self.view!.bounds
self.backgroundImageView?.frame = bounds
self.blurredImageView?.frame = bounds
self.tableView?.frame = bounds
}
// UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let hourlyConditions = self.hourlyConditions {
return hourlyConditions.count + 1
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: cellIdentifier)
}
cell!.selectionStyle = .none
cell!.backgroundColor = UIColor.white.withAlphaComponent(0.2)
cell!.textLabel?.textColor = UIColor.white
cell!.detailTextLabel?.textColor = UIColor.white
if indexPath.row == 0 {
cell!.textLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 18)
cell!.textLabel!.text = "Hourly Forecast"
cell!.detailTextLabel!.text = ""
cell!.imageView!.image = nil
} else {
let weather = hourlyConditions?[indexPath.row - 1]
cell!.textLabel!.font = UIFont(name:"HelveticaNeue-Light", size:18)
cell!.detailTextLabel!.font = UIFont(name:"HelveticaNeue-Medium", size:18)
cell!.textLabel!.text = self.hourlyDateFormatter.string(from: weather!.date!)
cell!.detailTextLabel!.text = String(format:"%.0f°", weather!.temperature!)
cell!.imageView!.image = UIImage(named: weather!.imageName())
cell!.imageView!.contentMode = .scaleAspectFit
}
return cell!
}
// UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.screenHeight! / CGFloat(self.tableView(tableView, numberOfRowsInSection: indexPath.section))
}
// UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let height = scrollView.bounds.size.height
let position = max(scrollView.contentOffset.y, 0.0)
let percent = min(position / height, 1.0)
// print("\(percent)")
self.blurredImageView?.alpha = percent
}
func findCurrentLocation() {
self.isFirstUpdate = true
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// ignore the first update because it is almost always cached
if self.isFirstUpdate {
self.isFirstUpdate = false
return
}
let location = locations.last!
if location.horizontalAccuracy > 0 {
self.currentLocation = location
self.locationManager.stopUpdatingLocation()
}
}
func updateCurrentConditions() {
self.client.fetchCurrentConditionsForLocation(location: currentLocation!.coordinate, completion: { [unowned self] wxCondition in
// print("\(wxCondition)")
if let wxCondition = wxCondition {
self.temperatureLabel?.text = String(format: "%.0f°", wxCondition.temperature!)
self.conditionsLabel?.text = wxCondition.condition?.capitalized
self.cityLabel?.text = wxCondition.locationName?.capitalized
self.iconView?.image = UIImage(imageLiteralResourceName: wxCondition.imageName())
self.hiloLabel?.text = String(format: "%.0f° / %.0f°", arguments: [wxCondition.tempHigh!, wxCondition.tempLow!])
}
})
}
func updateHourlyForecast() {
self.client.fetchHourlyForecastForLocation(location: currentLocation!.coordinate, completion: { [unowned self]
wxConditions in
// print("\(wxConditions)")
self.hourlyConditions = wxConditions
})
}
}
<file_sep>//
// OpenWeatherRouter.swift
// SimpleWeather
//
// Created by <NAME> on 23/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import CoreLocation
import Alamofire
public enum OpenWeatherRouter : URLRequestConvertible {
static let baseURLPath = "https://api.openweathermap.org/data/2.5"
case current(CLLocationCoordinate2D, String)
case hourly(CLLocationCoordinate2D, String)
var method: HTTPMethod {
switch self {
default:
return .get
}
}
var path: String {
switch self {
case .current:
return "/weather"
case .hourly:
return "/forecast"
}
}
public func asURLRequest() throws -> URLRequest {
let params: [String: Any] = {
switch self {
case .current(let location, let apiKey):
return ["APPID": apiKey, "lat": location.latitude, "lon": location.longitude, "units": "imperial"]
case .hourly(let location, let apiKey):
return ["APPID": apiKey, "lat": location.latitude, "lon": location.longitude, "units": "imperial", "cnt": 12]
}
}()
let url = try OpenWeatherRouter.baseURLPath.asURL()
var request = URLRequest(url: url.appendingPathComponent(path))
request.httpMethod = method.rawValue
request.timeoutInterval = TimeInterval(10 * 1000)
return try URLEncoding.default.encode(request, with: params)
}
}
<file_sep># SimpleWeather
[Ray Wenderlich's tutorial on iOS 7 best practices](https://www.raywenderlich.com/55384/ios-7-best-practices-part-1) provides a case study by creating a weather app. The tutorial uses Objective-C. This project is a Swift implementation of the same app.
## Why?
Just to learn the Swift language, best practices, and popular Swift Libraries.
## Using OpenWeather API
This project uses OpenWeather api to get weather data. To use their API, you need to register an account and get an API key. For security purposes, the API key is not hardcoded in the project to avoid checking it into source control. The API key is being read from a file called keys.plist, which is ignored by `.gitignore`. To build this project, you need to add this file yourself. The key name is expected to be "openWeatherApiKey".
Note that this approach only avoids checking in the api key. If you build this project and release the app, it may still be possible for users to decompile your app and retrieve the api key.
## Differences from the original project
1. I did not use TSMessages for displaying error messages.
2. Instead of using ReactiveCocoa for reactive programming, I used Alamofire for asynchronous networking and Swift's property observers to refresh data/UI.
3. Instead of Using Mantle for converting JSON to NSObject classes, I used ObjectMapper (side note: there is actually an Alamofire+ObjectMapper extension which I did not use).
4. Unlike the original tutorial, this project does not show daily forecast data. The daily forecast API requires a paid account.
## Known issues
- Blurred images is not working.
## Improvements
This is my first project in Swift and it is possible some things could be written in a better manner. If you spot any thing that can be improved, feel free to send in a PR or contact me.<file_sep>//
// WXCondition.swift
// SimpleWeather
//
// Created by <NAME> on 1/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import ObjectMapper
class WXCondition : Mappable, CustomStringConvertible {
static let IMAGE_MAP : [String : String] = ["01d": "weather-clear", "02d": "weather-few", "03d": "weather-few",
"04d": "weather-broken", "09d": "weather-shower", "10d": "weather-rain",
"11d": "weather-tstorm", "13d": "weather-snow", "50d": "weather-mist",
"01n": "weather-moon", "02n": "weather-few-night", "03n": "weather-few-night",
"04n": "weather-broken", "09n": "weather-shower", "10n": "weather-rain-night",
"11n": "weather-tstorm", "13n": "weather-snow", "50n": "weather-mist"]
var date : Date?
var humidity : Double?
var temperature : Double?
var tempHigh : Double?
var tempLow : Double?
var locationName : String?
var sunrise : Date?
var sunset : Date?
var conditionDescription : String?
var condition : String?
var windBearing : Double?
var windSpeed : Double?
var icon : String?
var description: String {
return "WXCondition: date=\(date), humidity=\(humidity), temperature=\(temperature), " +
"tempHigh=\(tempHigh), tempLow=\(tempLow), locationName=\(locationName), " +
"sunrise=\(sunrise), sunset=\(sunset), conditionDescription=\(conditionDescription), " +
"condition=\(condition), windBearing=\(windBearing), windSpeed=\(windSpeed), icon=\(icon)"
}
let dateTransform = TransformOf<Date, Double>(fromJSON: { (value: Double?) -> Date? in
if let value = value {
return Date(timeIntervalSince1970: TimeInterval(value))
} else {
return nil
}
}, toJSON: { (value: Date?) -> Double? in
if let value = value {
return value.timeIntervalSince1970
} else {
return nil
}
})
func imageName() -> String {
return WXCondition.IMAGE_MAP[self.icon!]!
}
// Mappable protocols
required init?(map: Map) {
}
func mapping(map: Map) {
humidity <- map["main.humidity"]
temperature <- map["main.temp"]
tempHigh <- map["main.temp_max"]
tempLow <- map["main.temp_min"]
locationName <- map["name"]
conditionDescription <- map["weather.0.description"]
condition <- map["weather.0.main"]
windBearing <- map["wind.deg"]
windSpeed <- map["wind.speed"]
icon <- map["weather.0.icon"]
date <- (map["dt"], dateTransform)
sunrise <- (map["sys.sunrise"], dateTransform)
sunset <- (map["sys.sunset"], dateTransform)
}
}
|
0d73d8e8a4e42963bb3e6ba5c08c55f20da5cac3
|
[
"Swift",
"Markdown"
] | 5
|
Swift
|
hendychua/simpleweather
|
992e12e20ba659a18c67882207e37c3239f2a295
|
ba8666c6be7ba18e2efb2201b337a60307226e29
|
refs/heads/main
|
<repo_name>tehpsy/cattrain<file_sep>/README.md
A stupid SwiftUI app for training your cat not to meow at night
<file_sep>/Shared/DetectSoundsView.swift
import Foundation
import SwiftUI
struct DetectSoundsView: View {
@ObservedObject var state: AppState
let config: AppConfiguration
var body: some View {
VStack {
ZStack {
Color(.black)
Self.image(given: state.detectionState.currentConfidence)
.clipped()
.edgesIgnoringSafeArea(.all)
VStack {
Spacer()
Toggle(isOn: $state.playAlert, label: {
Image(systemName: "graduationcap.fill")
Text("Training Mode").fontWeight(.bold)
})
.frame(width: 240)
.padding(.bottom)
.toggleStyle(SwitchToggleStyle(tint: .orange))
}
VStack {
Text("Sound Detection Paused").padding()
Button(action: { state.restartDetection(config: config) }) {
Text("Start")
}
}.opacity(state.soundDetectionIsRunning ? 0.0 : 1.0)
.disabled(state.soundDetectionIsRunning)
}
}
}
private static func image(given confidence: Double) -> some View {
return (
confidence > 0.8 ?
Image("open") :
Image("shut")
)
.resizable()
.scaledToFill()
}
}
struct DetectSoundsView_Previews: PreviewProvider {
static var previews: some View {
DetectSoundsView(
state: AppState(),
config: AppConfiguration()
)
}
}
<file_sep>/Shared/CatTrainApp.swift
import SwiftUI
import SoundAnalysis
import Combine
import AVFoundation
@main
struct CatTrainApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
typealias SoundIdentifier = String
struct AppConfiguration {
let inferenceWindowSize = Double(1.5)
let overlapFactor = Double(0.9)
let monitoredSound: SoundIdentifier = "cat_meow"
}
class AppState: ObservableObject {
private var detectionCancellable: AnyCancellable? = nil
private let appConfig = AppConfiguration()
private let systemAudioClassifier = SystemAudioClassifier()
private var player: AVAudioPlayer?
@Published var detectionState: DetectionState = DetectionState.default
@Published var soundDetectionIsRunning: Bool = false
@Published var playAlert: Bool = false
init() {
restartDetection(config: appConfig)
}
func restartDetection(config: AppConfiguration) {
systemAudioClassifier.stopSoundClassification()
let classificationSubject = PassthroughSubject<SNClassificationResult, Error>()
detectionCancellable =
classificationSubject
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { _ in
self.soundDetectionIsRunning = false
},
receiveValue: { result in
let confidence = result.classification(forIdentifier: self.appConfig.monitoredSound)?.confidence ?? 0
self.detectionState = DetectionState(advancedFrom: self.detectionState, currentConfidence: confidence)
if self.playAlert && confidence > 0.8 {
self.playSound()
}
})
soundDetectionIsRunning = true
systemAudioClassifier.startSoundClassification(
subject: classificationSubject,
inferenceWindowSize: config.inferenceWindowSize,
overlapFactor: config.overlapFactor
)
}
func playSound() {
guard player == nil || !(player!.isPlaying) else { return }
let data = NSDataAsset(name: "airhorn")!.data
player = try! AVAudioPlayer(data: data)
player!.prepareToPlay()
player!.play()
}
}
<file_sep>/Shared/ContentView.swift
import SwiftUI
struct ContentView: View {
let appConfig = AppConfiguration()
@StateObject var appState = AppState()
var body: some View {
DetectSoundsView(
state: appState,
config: appConfig
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
20f53930dfc4f481d0221b8d089fe1c025a319ed
|
[
"Markdown",
"Swift"
] | 4
|
Markdown
|
tehpsy/cattrain
|
2d948baf073e99c6f72b3c8cf1deb534cfe8f06f
|
bed81a260d135057381643f68624bfe22bec73f3
|
refs/heads/master
|
<file_sep>export type Item = {
date: Date,
category: string,
title: string,
value: number
}//Geralmente vc vai ter uma pasta types onde vc coloca todos os tipos gerais da pagina<file_sep>import {Category} from '../types/Category';
export const categories: Category = {//Simplesmente exportando um obj com as categorias e como sempre eu preciso tipar esse obj
food: {title: 'Alimentacao', color: 'blue', expense: true},
rent: {title: 'Aluguel', color: 'brown', expense: true},
salary: {title: 'Salario', color: 'green', expense: false}
}<file_sep>import styled from 'styled-components';
export const Table = styled.table`
width: 100%;
background-color: #fff;
padding: 20px;
box-shadow: 0px 0px 5px #ccc;
border-radius: 10px;
margin-top: 20px;
`;
export const TableHeadColumn = styled.th<{width?: number}>`
width: ${props => props.width ? `${props.width}px` : 'auto'};
padding: 10px 0;
text-align: left;
`;
//Esse <width: number> e uma forma de passar a prop para ca, se vc nao fizer isso o TS vai dizer que TableHeadColumn nao precisa de prop, o ? e pq existe alguns th que nao tem essa prop, entao deixamos ela opcional<file_sep>import styled from 'styled-components';
export const Container = styled.div``;
export const Header = styled.div`
background-color: darkblue;
height: 150px;
text-align: center;
`;
export const HeaderText = styled.h1`
margin: 0;
padding: 0;
color: #fff;
padding-top: 30px;
`;
export const body = styled.div`
margin: auto;
max-width: 980px;
margin-bottom: 50px;
`;<file_sep>import {Item} from '../types/Item';
//Esse arquivo e simplesmente para nos ajudar a separar melhor, as funcoes vao ficar aqui
export const getCurrentMonth = () => {
let now = new Date();
return `${now.getFullYear()} - ${now.getMonth() + 1}`;
}//Essa funcao simplesmente retorna o anoAtual - MesAtual
export const filterListByMonth = (list: Item[], date: string): Item[] => {//Recebe a lista original + uma data
let newList: Item[] = [];
let [year, month] = date.split('-');
for (let i in list) {
if (
list[i].date.getFullYear() === parseInt(year) &&
(list[i].date.getMonth() + 1) === parseInt(month)
)
{
newList.push(list[i]);
}//E possivel fazer list[i].date.getFullYear() pq list[i].date e uma data, logo tem o metodo getFullYear
}
return newList;
}//Essa funcao simplesmente cria a nova lista, filtrada ja com o mes e ano escolhido pelo cidadao.
export const formatDate = (date: Date): string => {
let year = date.getFullYear();//Nao preciso tipar nenhum desses pq eles ja retornam certo (number), da para ver no VSCode passando o mouse
let month = date.getMonth() + 1;
let day = date.getDate();
return `${addZeroToDate(day)}/${addZeroToDate(month)}/${year}`;
}
const addZeroToDate = (n: number): string => n < 10 ? `0${n}`: `${n}`;
export const formatCurrentMonth = (currentMonth: string): string => {
let [year, month] = currentMonth.split('-');
let months = ['Janeiro', 'Fevereiro', 'Marco', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto',
'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
return `${months[parseInt(month) - 1]} de ${year}`;
}<file_sep>export type Category = {
[tag: string]: {
title: string,
color: string,
expense: boolean
}
}//[tag: string] quer dizer que ele vai aceitar qualquer nome que seja uma string, isso acontece quando temos um obj dentro de outro obj
|
8bb5768275fa7c8d1321eb0ea837a1cdefa137ac
|
[
"TypeScript"
] | 6
|
TypeScript
|
RigobertoCaionda/expense-tracker
|
362cb2ccf4d07b0c086d65223603bc5b6f673413
|
556790579693cb3646e501173b25203d7f97cc22
|
refs/heads/master
|
<repo_name>skonovalov/tea_book<file_sep>/README.md
# tea_book
Tea encyclopedia
<file_sep>/build/js/script.js
$(document).ready(function() {
console.time('loading...');
preparePage();
console.timeEnd('loading...');
});
function preparePage() {
if( $('#main').length > 0) {
openMenu();
closeMain();
}
if($('.filter-cats')) {
lightBox();
easyTabs();
}
}
/* open menu on main page*/
function openMenu() {
var btn, menu;
btn = $('.hamb'),
menu = $('header');
btn.on('click', function() {
menu.addClass('open-menu');
setTimeout(function() {
$('.menu').addClass('menuFadeIn');
}, 300);
});
}
/* close menu on main page*/
function closeMain() {
var btn, menu;
btn = $('.icon-close'),
menu = $('header');
btn.on('click', function() {
setTimeout(function() {
menu.removeClass('open-menu');
}, 1000);
$('.menu').removeClass('menuFadeIn');
});
}
function lightBox() {
$(".fancybox").fancybox();
}
function easyTabs() {
$('#tab-container').easytabs();
}
|
c0301d2e8c5cf34ba6aa942c117d25b5669aad87
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
skonovalov/tea_book
|
da95ddd9416feb2e67df3928734d68ecc49aba1c
|
8cca36521e8eee1992ffa931eeddb3793e3af0fe
|
refs/heads/master
|
<repo_name>bakariNouhou/BankAccountKata-Bakari<file_sep>/BankAccount/src/main/java/fr/lcdlv/Bank.java
package fr.lcdlv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
class Bank {
private IBankDateTimeProvider dateProvider;
private Map<String, BankClientInfos> mapClientInfos;
Bank(IBankDateTimeProvider dateProvider) {
mapClientInfos = new HashMap<>();
this.dateProvider = dateProvider;
}
void createAccount(String clientId, int initialAmount) {
mapClientInfos.put(clientId, BankClientInfos.createBankClientInfos(BankAccount.createBankAccount(initialAmount), new ArrayList<>()));
}
String clientWithdraws(BankClient bankClient, int withdrawalAmount) {
return genericClientOperation(bankClient, withdrawalAmount, BankOperationType.WITHDRAWAL,
BankClientInfos::substractFromAccount);
}
String clientDeposits(BankClient bankClient, int depositAmount) {
return genericClientOperation(bankClient, depositAmount, BankOperationType.DEPOSIT,
BankClientInfos::addAmountToAccount);
}
int getClientBalance(BankClient bankClient) {
return getClientInfos(bankClient).getAccountBalance();
}
private String genericClientOperation(BankClient bankClient, int amount, BankOperationType operationType, BiFunction<BankClientInfos,
Integer, BankOperationResultCode> accountFunction) {
BankOperationResultCode resultCode = accountFunction.apply(getClientInfos(bankClient), amount);
if (resultCode.isOperationSuccessful()) {
addOperationToClientHistory(bankClient, amount, operationType);
}
return resultCode.getErrorMessage();
}
private void addOperationToClientHistory(BankClient bankClient, int amount, BankOperationType deposit) {
BankOperation operation = BankOperation.createBankOperation(deposit, dateProvider.getBankTimeStamp(),
amount, getClientBalance(bankClient));
getClientInfos(bankClient).addOperationToHistory(operation);
}
private BankClientInfos getClientInfos(BankClient bankClient) {
return mapClientInfos.get(bankClient.getClientId());
}
String getFormattedHistoryOfClient(BankClient bankClient) {
return getClientInfos(bankClient).getFormattedHistory();
}
boolean clientHistoryContainsOperation(BankClient bankClient, BankOperation bankOperation) {
return getClientInfos(bankClient).historyContainsOperation(bankOperation);
}
boolean clientHistoryIsEmpty(BankClient bankClient) {
return getClientInfos(bankClient).historyIsEmpty();
}
}<file_sep>/BankAccount/src/main/java/fr/lcdlv/BankClientInfos.java
package fr.lcdlv;
import java.util.List;
final class BankClientInfos {
private final BankAccount bankAccount;
private final List<BankOperation> operationsHistory;
private BankClientInfos(BankAccount bankAccount, List<BankOperation> operationsHistory) {
this.bankAccount = bankAccount;
this.operationsHistory = operationsHistory;
}
static BankClientInfos createBankClientInfos(BankAccount bankAccount, List<BankOperation> operationsHistory) {
return new BankClientInfos(bankAccount, operationsHistory);
}
void addOperationToHistory(BankOperation operation) {
operationsHistory.add(operation);
}
int getAccountBalance() {
return bankAccount.getCurrentBalance();
}
BankOperationResultCode substractFromAccount(int withdrawalAmount) {
return bankAccount.substractAmount(withdrawalAmount);
}
BankOperationResultCode addAmountToAccount(int depositAmount) {
return bankAccount.addAmount(depositAmount);
}
String getFormattedHistory() {
return BankOperationsHistoryFormatter.format(operationsHistory);
}
boolean historyContainsOperation(BankOperation bankOperation) {
return operationsHistory.contains(bankOperation);
}
boolean historyIsEmpty() {
return operationsHistory.isEmpty();
}
}
<file_sep>/BankAccount/src/test/java/fr/lcdlv/MockTimer.java
package fr.lcdlv;
import java.time.LocalDateTime;
public class MockTimer implements IBankDateTimeProvider {
private final LocalDateTime startDateTime;
private int counter = 0;
MockTimer(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
}
@Override
public LocalDateTime getBankTimeStamp() {
counter++;
return startDateTime.plusHours(counter);
}
}
<file_sep>/BankAccount/src/main/java/fr/lcdlv/BankOperationsHistoryFormatter.java
package fr.lcdlv;
import java.util.List;
import java.util.stream.Collectors;
class BankOperationsHistoryFormatter {
static String format(List<BankOperation> historyOperationClient) {
return historyOperationClient.stream().map(BankOperation::toString)
.collect(Collectors.joining("\n"));
}
}
<file_sep>/BankAccount/src/main/java/fr/lcdlv/BankOperationResultCode.java
package fr.lcdlv;
public enum BankOperationResultCode {
SUCCESS("Operation successful"),
INVALID_DEPOSIT("Deposit impossible. You can't deposit negative funds"),
INVALID_WITHDRAWAL("Withdrawal impossible. You can't withdraw negative funds"),
INSUFFICIENT_FUNDS("Withdrawal impossible. Insufficient funds");
private final String errorMessage;
BankOperationResultCode(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
boolean isOperationSuccessful() {
return SUCCESS == this;
}
}
<file_sep>/BankAccount/src/test/java/fr/lcdlv/BankClientTest.java
package fr.lcdlv;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
class BankClientTest {
private static Bank sg;
private static final LocalDateTime START_DATE_TIME = LocalDateTime.of(2019, 10, 23, 0, 0);
@BeforeEach
void setUpBeforeEach() {
IBankDateTimeProvider MOCK_TIMER = new MockTimer(START_DATE_TIME);
sg = new Bank(MOCK_TIMER);
}
@ParameterizedTest
@ValueSource(ints = {0, 42, 26})
void client_balance_is_initial_amount_when_no_operation_on_account(int initialAmount) {
BankClient paul = BankClient.createBankClient("Paul", sg, initialAmount);
assertThat(paul.getAccountBalance()).isEqualTo(initialAmount);
}
@DisplayName("Client Account Balance when deposit")
@ParameterizedTest(name = "Balance should be {0} when initial amount is {1} and deposit is {2}")
@CsvSource({"5, 1, 4", "27, 24, 3", "36, 33, 3"})
void correct_client_balance_given_deposit_initial_amount(int balance, int initialAmount, int deposit) {
BankClient michael = BankClient.createBankClient("Michael", sg, initialAmount);
michael.deposits(deposit);
assertThat(michael.getAccountBalance()).isEqualTo(balance);
}
@DisplayName("Client Account Balance when withdrawal")
@ParameterizedTest(name = "Balance should be {0} when initial amount is {1} and withdrawal is {2}")
@CsvSource({"28, 32, 4", "3, 45, 42", "11, 20, 9"})
void correct_client_balance_when_withdraw_given_initial_amount(int balance, int initialAmount, int withdrawal) {
BankClient jm = BankClient.createBankClient("JM", sg, initialAmount);
jm.withdraws(withdrawal);
assertThat(jm.getAccountBalance()).isEqualTo(balance);
}
@Test
void history_is_empty_when_no_operation() {
BankClient paul = BankClient.createBankClient("Paul", sg, 0);
assertThat(paul.historyIsEmpty()).isTrue();
}
@Test
void history_has_one_withdrawal_operation_when_one_withdrawal() {
BankClient paul = BankClient.createBankClient("Paul", sg, 100);
paul.withdraws(50);
BankOperation operation = BankOperation.createBankOperation(BankOperationType.WITHDRAWAL, START_DATE_TIME.plusHours(1),
50, 50);
assertThat(paul.historyContainsAllOperations(operation)).isTrue();
}
@Test
void history_has_one_deposit_operation_when_one_deposit() {
BankClient paul = BankClient.createBankClient("Paul", sg, 100);
paul.deposits(50);
BankOperation operation = BankOperation.createBankOperation(BankOperationType.DEPOSIT,
START_DATE_TIME.plusHours(1),
50, 150);
assertThat(paul.historyContainsAllOperations(operation));
}
@Test
void client_gets_error_message_when_trying_to_withdraw_more_than_balance() {
BankClient paul = BankClient.createBankClient("Paul", sg, 30);
assertThat(paul.withdraws(45)).isEqualTo("Withdrawal impossible. Insufficient funds");
}
@Test
void client_gets_error_message_when_trying_to_deposit_negative_funds() {
BankClient paul = BankClient.createBankClient("Paul", sg, 30);
assertThat(paul.deposits(-45)).isEqualTo("Deposit impossible. You can't deposit negative funds");
}
@Test
void client_gets_error_message_when_trying_to_withdraw_negative_amount() {
BankClient paul = BankClient.createBankClient("Paul", sg, 30);
assertThat(paul.withdraws(-30)).isEqualTo("Withdrawal impossible. You can't withdraw negative funds");
}
}<file_sep>/BankAccount/src/main/java/fr/lcdlv/BankAccount.java
package fr.lcdlv;
class BankAccount {
private int currentBalance;
private BankAccount(int initialAmount) {
currentBalance = initialAmount;
}
static BankAccount createBankAccount(int initialAmount) {
return new BankAccount(initialAmount);
}
BankOperationResultCode addAmount(int deposit) {
if (deposit < 0) {
return BankOperationResultCode.INVALID_DEPOSIT;
}
currentBalance += deposit;
return BankOperationResultCode.SUCCESS;
}
int getCurrentBalance() {
return currentBalance;
}
BankOperationResultCode substractAmount(int withdrawal) {
if (withdrawal > currentBalance) {
return BankOperationResultCode.INSUFFICIENT_FUNDS;
} else if (withdrawal < 0) {
return BankOperationResultCode.INVALID_WITHDRAWAL;
}
currentBalance -= withdrawal;
return BankOperationResultCode.SUCCESS;
}
}
|
32ba6c389df581a76ce326ddafd72e99ccd6a9f1
|
[
"Java"
] | 7
|
Java
|
bakariNouhou/BankAccountKata-Bakari
|
83f6cb4f4f3e98942472fad104f9d26b22f55421
|
24d6307d305f750d218061e8dc666cd6bd6ba2f4
|
refs/heads/master
|
<file_sep># <img src="https://github.com/tyblocker/ktane/blob/master/KTANE/ktanepsd.png" width="50" height="50"> Keep Talking and Nobody Explodes Assistant
An alternative bomb defusal manual.
## Features:
* Command-line prompts (GUI coming soon) enable quicker and easier defusal instructions
* Currently includes the following modules (with more to come)
* Wires
* Button
* Simon Says
* Who's on First
* Memory
* Complicated Wires
* Password
## Contributions
Contributions are welcome. If you are contributing a patch that you aren't the original author of, please give credits at the top of the file. If a patch has been added and you are the original author of it or know who is, issue a pull request or open an issue so that proper credits may be given.
You don't have to have any experience to contribute to this project.
All constructive criticism is welcome.
If you have never made a pull request, you can learn how from this free series by [@kentcdodds](https://twitter.com/kentcdodds):
[How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
<file_sep>#include <iostream>
#include <iomanip>
#include <cstring>
#include <istream>
using namespace std;
int batteries;
bool CAR;
bool FRK;
int Parallel;
bool vowel;
bool even;
void information();
void wires();
void button();
void keypad();
void simonsays();
void whosonfirst();
void memory();
void morsecode();
void complicatedwires();
void wiresequence();
void maze();
void password();
void main()
{
char module[17];
char more;
information();
/*if (::vowel == 1) {
cout << "The Serial Number has at least one vowel." << endl;
}
else {
cout << "The Serial Number does not have a vowel." << endl;
}
if (::even == 1) {
cout << "The Last Digit of the Serial Number is even." << endl;
}
else {
cout << "The Last Digit of the Serial Number is odd." << endl;
}
cout << "There are " << ::batteries << " batteries on the bomb." << endl;
if (::CAR == 1) {
cout << "Indicator CAR is illuminated." << endl;
}
else {
cout << "Indicator CAR is not illuminated." << endl;
}
if (::FRK == 1) {
cout << "Indicator FRK is illuminated." << endl;
}
else {
cout << "Indicator FRK is not illuminated." << endl;
}
cout << "There are " << ::Parallel << " Parallel Ports." << endl;*/
do
{
cout << endl << "Which module? ";
cin.ignore();
cin.getline(module, 17);
for (int i = 0; i < 17; i++)
{
module[i] = toupper(module[i]);
}
if (strcmp(module, "WIRES") == 0) {
wires();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "BUTTON") == 0) {
button();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "KEYPAD") == 0) {
keypad();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "SIMONSAYS") == 0) {
simonsays();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "WHOSONFIRST") == 0) {
whosonfirst();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "MEMORY") == 0) {
memory();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "MORSECODE") == 0) {
morsecode();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "COMPLICATEDWIRES") == 0) {
complicatedwires();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "WIRESEQUENCE") == 0) {
wiresequence();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "MAZE") == 0) {
maze();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else if (strcmp(module, "PASSWORD") == 0) {
password();
cout << endl << "More Modules?(Y/N) ";
cin >> more;
}
else {
cout << endl << "Enter a valid input.";
more = 'Y';
}
} while (toupper(more) == 'Y');
}
void information()
{
char line[7];
char *strPtr = nullptr;
char CAR;
char FRK;
cout << "Enter the Serial Number: ";
cin.getline(line, 7);
for (int i = 0; i < 7; i++)
{
line[i] = toupper(line[i]);
}
cout << "How many batteries? ";
cin >> ::batteries;
cout << "Is CAR illuminated?(Y/N) ";
CAR:
cin >> CAR;
if (toupper(CAR) == 'Y') {
::CAR = 1;
}
else if (toupper(CAR) == 'N') {
::CAR = 0;
}
else {
cout << "Enter a valid response.";
goto CAR;
}
cout << "Is FRK illuminated?(Y/N) ";
FRK:
cin >> FRK;
if (toupper(FRK) == 'Y') {
::FRK = 1;
}
else if (toupper(FRK) == 'N') {
::FRK = 0;
}
else {
cout << "Enter a valid response.";
goto FRK;
}
cout << "How many parallel ports? ";
cin >> ::Parallel;
//Test for Vowels
if (strstr(line, "A") != 0 || strstr(line, "E") != 0 || strstr(line, "I") != 0 || strstr(line, "O") != 0 || strstr(line, "U") != 0) {
::vowel = 1;
}
else {
::vowel = 0;
}
//Test if Last Digit is even
strPtr = strstr(line, "2");
if ((strstr(line, "2") != 0) && ((std::char_traits<char>::length(strPtr)) == 1)) {
::even = 1;
}
else {
strPtr = strstr(line, "4");
if ((strstr(line, "4") != 0) && ((std::char_traits<char>::length(strPtr)) == 1)) {
::even = 1;
}
else {
strPtr = strstr(line, "6");
if ((strstr(line, "6") != 0) && ((std::char_traits<char>::length(strPtr)) == 1)) {
::even = 1;
}
else {
strPtr = strstr(line, "8");
if ((strstr(line, "8") != 0) && ((std::char_traits<char>::length(strPtr)) == 1)) {
::even = 1;
}
else {
::even = 0;
}
}
}
}
}
void wires()
{
int wires;
int red;
int blue;
int yellow;
int black;
int white;
char test;
cout << "How many wires? ";
cin >> wires;
if (wires == 3) {
cout << endl << "How many red wires? ";
cin >> red;
if (red == 0) {
cout << endl << "Cut the second wire.";
}
else {
cout << endl << "Is the last wire white?(Y/N) ";
cin >> test;
if (toupper(test) == 'Y') {
cout << endl << "Cut the last wire.";
}
else if (toupper(test) == 'N') {
cout << endl << "How many blue wires? ";
cin >> blue;
if (blue > 1) {
cout << endl << "Cut the last blue wire.";
}
else {
cout << endl << "Cut the last wire.";
}
}
}
}
if (wires == 4) {
cout << endl << "How many red wires? ";
cin >> red;
if ((red > 1) && (::even != 1)) {
cout << endl << "Cut the last red wire.";
}
else {
cout << endl << "Is the last wire yellow?(Y/N) ";
cin >> test;
if ((toupper(test) == 'Y') && (red == 0)) {
cout << endl << "Cut the first wire.";
}
else {
cout << endl << "How many blue wires? ";
cin >> blue;
if (blue == 1) {
cout << endl << "Cut the first wire.";
}
else {
cout << endl << "How many yellow wires? ";
cin >> yellow;
if (yellow > 1) {
cout << endl << "Cut the last wire.";
}
else {
cout << endl << "Cut the second wire.";
}
}
}
}
}
if (wires == 5) {
cout << endl << "Is the last wire black?(Y/N) ";
cin >> test;
if ((toupper(test) == 'Y') && (::even != 1)) {
cout << endl << "Cut the fourth wire.";
}
else {
cout << endl << "How many red wires? ";
cin >> red;
cout << endl << "How many yellow wires? ";
cin >> yellow;
if ((red == 1) && (yellow > 1)) {
cout << endl << "Cut the first wire.";
}
else {
cout << endl << "How many black wires? ";
cin >> black;
if (black == 0) {
cout << endl << "Cut the second wire.";
}
else {
cout << endl << "Cut the first wire.";
}
}
}
}
if (wires == 6) {
cout << endl << "How many yellow wires? ";
cin >> yellow;
if ((yellow == 0) && (::even != 1)) {
cout << endl << "Cut the third wire.";
}
else {
cout << endl << "How many white wires? ";
cin >> white;
if ((yellow == 1) && (white > 1)) {
cout << endl << "Cut the fourth wire.";
}
else {
cout << endl << "How many red wires? ";
cin >> red;
if (red == 0) {
cout << endl << "Cut the last wire.";
}
else {
cout << endl << "Cut the fourth wire.";
}
}
}
}
}
void button()
{
char color[7];
char text[9];
char strip[7];
cout << endl << "What is the color of the button? ";
cin.getline(color, 7);
for (int i = 0; i < 7; i++)
{
color[i] = toupper(color[i]);
}
cout << endl << "What is the text on the button? ";
for (int i = 0; i < 9; i++)
{
text[i] = toupper(text[i]);
}
if (((::batteries > 2) && (::FRK == 1)) || ((::batteries > 1) && ((strcmp(text, "DETONATE") == 0))) || ((strcmp(color, "RED") == 0) && (strcmp(text, "HOLD") == 0))) {
cout << endl << "Press the button.";
}
else {
cout << endl << "Press and hold the button.";
cout << endl << "What is the color of the strip? ";
cin.getline(strip, 7);
for (int i = 0; i < 7; i++)
{
strip[i] = toupper(strip[i]);
}
if ((strcmp(strip, "BLUE") == 0)) {
cout << endl << "Release when there is a 4 in any position.";
}
else if ((strcmp(strip, "YELLOW") == 0)) {
cout << endl << "Release when there is a 5 in any position.";
}
else {
cout << endl << "Release when there is a 1 in any position.";
}
}
}
void keypad()
{
}
void simonsays()
{
int strikes;
char color[7];
char next;
simonsays:
cout << endl << "How many strikes? ";
cin >> strikes;
cout << endl << "Which color is blinking? ";
cin.getline(color, 7);
for (int i = 0; i < 7; i++)
{
color[i] = toupper(color[i]);
}
if (strikes == 0) {
if (::vowel == 1) {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press blue.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press red.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press green.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
else {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press blue.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press green.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press red.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
}
else if (strikes == 1) {
if (::vowel == 1) {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press green.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press blue.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press red.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
else {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press red.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press blue.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press green.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
}
else if (strikes == 2) {
if (::vowel == 1) {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press green.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press red.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press blue.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
else {
if (strcmp(color, "RED") == 0) {
cout << endl << "Press yellow.";
}
else if (strcmp(color, "BLUE") == 0) {
cout << endl << "Press green.";
}
else if (strcmp(color, "GREEN") == 0) {
cout << endl << "Press blue.";
}
else if (strcmp(color, "YELLOW") == 0) {
cout << endl << "Press red.";
}
else {
cout << endl << "Input a valid color.";
goto simonsays;
}
}
}
next:
cout << endl << "Next color?(Y/N) ";
cin >> next;
if (toupper(next) == 'Y') {
goto simonsays;
}
else if (toupper(next) == 'N') {
return;
}
else {
cout << endl << "Enter a valid input.";
goto next;
}
}
void whosonfirst()
{
char display[9];
char label[8];
char more;
checkDisplay:
cout << endl << "Enter the word on the display. ";
cin.getline(display, 9);
for (int i = 0; i < 9; i++)
{
display[i] = toupper(display[i]);
}
if (strcmp(display, "UR") == 0) {
cout << endl << "Enter the label of the first column, first row. ";
}
else if ((strcmp(display, "FIRST") == 0) || (strcmp(display, "OKAY") == 0) || (strcmp(display, "C") == 0)) {
cout << endl << "Enter the label of the second column, first row. ";
}
else if ((strcmp(display, "YES") == 0) || (strcmp(display, "NOTHING") == 0) || (strcmp(display, "LED") == 0) || (strcmp(display, "THEY ARE") == 0)) {
cout << endl << "Enter the label of the first column, second row. ";
}
else if ((strcmp(display, "BLANK") == 0) || (strcmp(display, "READ") == 0) || (strcmp(display, "RED") == 0) || (strcmp(display, "YOU") == 0) || (strcmp(display, "YOUR") == 0) || (strcmp(display, "YOU'RE") == 0) || (strcmp(display, "THEIR") == 0)) {
cout << endl << "Enter the label of the second column, second row. ";
}
else if ((strcmp(display, "EMPTY") == 0) || (strcmp(display, "REED") == 0) || (strcmp(display, "LEED") == 0) || (strcmp(display, "THEY'RE") == 0)) {
cout << endl << "Enter the label of the first column, third row. ";
}
else if ((strcmp(display, "DISPLAY") == 0) || (strcmp(display, "SAYS") == 0) || (strcmp(display, "NO") == 0) || (strcmp(display, "LEAD") == 0) || (strcmp(display, "HOLD ON") == 0) || (strcmp(display, "YOU ARE") == 0) || (strcmp(display, "THERE") == 0) || (strcmp(display, "SEE") == 0) || (strcmp(display, "CEE") == 0)) {
cout << endl << "Enter the label of the second column, third row. ";
}
else {
cout << endl << "Enter a valid display word unless the display is blank, then enter 'empty.'";
goto checkDisplay;
}
checkLabel:
cin.getline(label, 8);
for (int i = 0; i < 8; i++)
{
label[i] = toupper(label[i]);
}
if (strcmp(label, "READY") == 0) {
cout << endl << "Push YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY";
}
else if (strcmp(label, "FIRST") == 0) {
cout << endl << "Push LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST";
}
else if (strcmp(label, "NO") == 0) {
cout << endl << "Push BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO";
}
else if (strcmp(label, "BLANK") == 0) {
cout << endl << "Push WAIT, RIGHT, OKAY, MIDDLE, BLANK";
}
else if (strcmp(label, "NOTHING") == 0) {
cout << endl << "Push UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING";
}
else if (strcmp(label, "YES") == 0) {
cout << endl << "Push OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES";
}
else if (strcmp(label, "WHAT") == 0) {
cout << endl << "Push UHHH, WHAT";
}
else if (strcmp(label, "UHHH") == 0) {
cout << endl << "Push READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH";
}
else if (strcmp(label, "LEFT") == 0) {
cout << endl << "Push RIGHT, LEFT";
}
else if (strcmp(label, "RIGHT") == 0) {
cout << endl << "Push YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT";
}
else if (strcmp(label, "MIDDLE") == 0) {
cout << endl << "Push BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE";
}
else if (strcmp(label, "OKAY") == 0) {
cout << endl << "Push MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY";
}
else if (strcmp(label, "WAIT") == 0) {
cout << endl << "Push UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT";
}
else if (strcmp(label, "PRESS") == 0) {
cout << endl << "Push RIGHT, MIDDLE, YES, READY, PRESS";
}
else if (strcmp(label, "YOU") == 0) {
cout << endl << "Push SURE, YOU ARE, YOUR, YOU'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU";
}
else if (strcmp(label, "YOU ARE") == 0) {
cout << endl << "Push YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU'RE, SURE, UR, YOU ARE";
}
else if (strcmp(label, "YOUR") == 0) {
cout << endl << "Push UH UH, YOU ARE, UH HUH, YOUR";
}
else if (strcmp(label, "YOU'RE") == 0) {
cout << endl << "Push YOU, YOU'RE";
}
else if (strcmp(label, "UR") == 0) {
cout << endl << "Push DONE, U, UR";
}
else if (strcmp(label, "U") == 0) {
cout << endl << "Push UH HUH, SURE, NEXT, WHAT?, YOU'RE, UR, UH UH, DONE, U";
}
else if (strcmp(label, "UH HUH") == 0) {
cout << endl << "Push UH HUH";
}
else if (strcmp(label, "UH UH") == 0) {
cout << endl << "Push UR, U, YOU ARE, YOU'RE, NEXT, UH UH";
}
else if (strcmp(label, "WHAT?") == 0) {
cout << endl << "Push YOU, HOLD, YOU'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?";
}
else if (strcmp(label, "DONE") == 0) {
cout << endl << "Push SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE";
}
else if (strcmp(label, "NEXT") == 0) {
cout << endl << "Push WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT";
}
else if (strcmp(label, "HOLD") == 0) {
cout << endl << "Push YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU'RE, NEXT, HOLD";
}
else if (strcmp(label, "SURE") == 0) {
cout << endl << "Push YOU ARE, DONE, LIKE, YOU'RE, YOU, HOLD, UH HUH, UR, SURE";
}
else if (strcmp(label, "LIKE") == 0) {
cout << endl << "Push YOU'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE";
}
else {
cout << endl << "Enter a valid label word.";
goto checkLabel;
}
next:
cout << endl << "Next stage?(Y/N) ";
cin >> more;
if (toupper(more) == 'Y') {
goto checkDisplay;
}
else if (toupper(more) == 'N') {
return;
}
else {
cout << endl << "Enter a valid input.";
goto next;
}
}
void memory()
{
int one_dis;
int one_one;
int one_two;
int one_three;
int one_four;
int one_resultPos;
int one_resultLab;
int two_dis;
int two_one;
int two_two;
int two_three;
int two_four;
int two_resultPos;
int two_resultLab;
int three_dis;
int three_one;
int three_two;
int three_three;
int three_four;
int three_resultPos;
int three_resultLab;
int four_dis;
int four_one;
int four_two;
int four_three;
int four_four;
int four_resultPos;
int four_resultLab;
int five_dis;
int five_one;
int five_two;
int five_three;
int five_four;
char correct;
StageOne:
cout << endl << "Stage One: enter the number on the display and all four positions separated by spaces.";
cin >> one_dis >> one_one >> one_two >> one_three >> one_four;
if ((one_dis == 1) || (one_dis == 2)) {
cout << endl << "Press the button labeled " << one_two;
one_resultPos = 2;
one_resultLab = one_two;
}
else if (one_dis == 3) {
cout << endl << "Press the button labeled " << one_three;
one_resultPos = 3;
one_resultLab = one_three;
}
else if (one_dis == 4) {
cout << endl << "Press the button labeled " << one_four;
one_resultPos = 4;
one_resultLab = one_four;
}
else {
cout << endl << "Please enter a valid number array.";
goto StageOne;
}
CheckCorrectOne:
cout << endl << "Correct?(Y/N) ";
cin >> correct;
if (toupper(correct) == 'Y') {
goto StageTwo;
}
else if (toupper(correct) == 'N') {
goto StageOne;
}
else {
cout << endl << "Enter a valid input.";
goto CheckCorrectOne;
}
StageTwo:
cout << endl << "Stage Two: enter the number on the display and all four positions separated by spaces.";
cin >> two_dis >> two_one >> two_two >> two_three >> two_four;
if (two_dis == 1) {
cout << endl << "Press the button labeled '4'";
cout << endl << "What position? ";
cin >> two_resultPos;
two_resultLab = 4;
}
else if ((two_dis == 2) || (two_dis == 4)) {
cout << endl << "Press the button in position " << one_resultPos;
cout << endl << "What label? ";
cin >> two_resultLab;
two_resultPos = one_resultPos;
}
else if (two_dis == 3) {
cout << endl << "Press the button in the first position";
two_resultPos = 1;
two_resultLab = two_one;
}
else {
cout << endl << "Please enter a valid number array.";
goto StageTwo;
}
CheckCorrectTwo:
cout << endl << "Correct?(Y/N) ";
cin >> correct;
if (toupper(correct) == 'Y') {
goto StageThree;
}
else if (toupper(correct) == 'N') {
goto StageOne;
}
else {
cout << endl << "Enter a valid input.";
goto CheckCorrectTwo;
}
StageThree:
cout << endl << "Stage Three: enter the number on the display and all four positions separated by spaces.";
cin >> three_dis >> three_one >> three_two >> three_three >> three_four;
if (three_dis == 1) {
cout << endl << "Press the button with the label '" << two_resultLab << "'";
cout << endl << "What position? ";
cin >> three_resultPos;
three_resultLab = two_resultLab;
}
else if (three_dis == 2) {
cout << endl << "Press the button with the label '" << one_resultLab << "'";
cout << endl << "What position? ";
cin >> three_resultPos;
three_resultLab = one_resultLab;
}
else if (three_dis == 3) {
cout << endl << "Press the button in the third position";
three_resultPos = 3;
three_resultLab = three_three;
}
else if (three_dis == 4) {
cout << endl << "Press the button labeled '4'";
cout << endl << "What position? ";
cin >> three_resultPos;
three_resultLab = 4;
}
else {
cout << endl << "Please enter a valid number array.";
goto StageThree;
}
CheckCorrectThree:
cout << endl << "Correct?(Y/N) ";
cin >> correct;
if (toupper(correct) == 'Y') {
goto StageFour;
}
else if (toupper(correct) == 'N') {
goto StageOne;
}
else {
cout << endl << "Enter a valid input.";
goto CheckCorrectThree;
}
StageFour:
cout << endl << "Stage Four: enter the number on the display and all four positions separated by spaces.";
cin >> four_dis >> four_one >> four_two >> four_three >> four_four;
if (four_dis == 1) {
cout << endl << "Press the button in position " << one_resultPos;
cout << endl << "What label? ";
cin >> four_resultLab;
four_resultPos = one_resultPos;
}
else if (four_dis == 2) {
cout << endl << "Press the button in the first position";
four_resultPos = 1;
four_resultLab = four_one;
}
else if ((four_dis == 3) || (four_dis == 4)) {
cout << endl << "Press the button in position " << two_resultPos;
cout << endl << "What label? ";
cin >> four_resultLab;
four_resultPos = two_resultPos;
}
else {
cout << endl << "Please enter a valid number array.";
goto StageFour;
}
CheckCorrectFour:
cout << endl << "Correct?(Y/N) ";
cin >> correct;
if (toupper(correct) == 'Y') {
goto StageFive;
}
else if (toupper(correct) == 'N') {
goto StageOne;
}
else {
cout << endl << "Enter a valid input.";
goto CheckCorrectFour;
}
StageFive:
cout << endl << "Stage Five: enter the number on the display and all four positions separated by spaces.";
cin >> five_dis >> five_one >> five_two >> five_three >> five_four;
if (five_dis == 1) {
cout << endl << "Press the button labeled '" << one_resultLab << "'";
}
else if (five_dis == 2) {
cout << endl << "Press the button labeled '" << two_resultLab << "'";
}
else if (five_dis == 3) {
cout << endl << "Press the button labeled '" << four_resultLab << "'";
}
else if (five_dis == 4) {
cout << endl << "Press the button labeled '" << three_resultLab << "'";
}
else {
cout << endl << "Please enter a valid number array.";
goto StageFive;
}
CheckCorrectFive:
cout << endl << "Correct?(Y/N) ";
cin >> correct;
if (toupper(correct) == 'Y') {
}
else if (toupper(correct) == 'N') {
goto StageOne;
}
else {
cout << endl << "Enter a valid input.";
goto CheckCorrectFive;
}
}
void morsecode()
{
}
void complicatedwires()
{
char color[6];
bool star;
bool led;
char next;
cout << endl << "Describe the wire by its color, status of star, and status of led, separated by spaces.";
cout << endl << "Example: \"BOTH 1 0\" and \"WHITE 0 0\"" << endl;
cin >> color >> star >> led;
if (strcmp(color, "WHITE") == 0) {
if ((star == 0) && (led == 0)) {
cout << endl << "Cut the wire";
}
else if ((star == 0) && (led == 1)) {
cout << endl << "Do not cut the wire";
}
else if ((star == 1) && (led == 0)) {
cout << endl << "Cut the wire";
}
else if ((star == 1) && (led == 1)) {
if (::batteries >= 2) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
}
else if (strcmp(color, "RED") == 0) {
if ((star == 0) && (led == 0)) {
if (::even == 1) {
cout << endl << "Cut the wire";
}
else if (::even == 0) {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 0) && (led == 1)) {
if (::batteries >= 2) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 1) && (led == 0)) {
cout << endl << "Cut the wire";
}
else if ((star == 1) && (led == 1)) {
if (::batteries >= 2) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
}
else if (strcmp(color, "BLUE") == 0) {
if ((star == 0) && (led == 0)) {
if (::even == 1) {
cout << endl << "Cut the wire";
}
else if (::even == 0) {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 0) && (led == 1)) {
if (::Parallel >= 1) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 1) && (led == 0)) {
cout << endl << "Do not cut the wire";
}
else if ((star == 1) && (led == 1)) {
if (::Parallel >= 1) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
}
else if (strcmp(color, "BOTH") == 0) {
if ((star == 0) && (led == 0)) {
if (::even == 1) {
cout << endl << "Cut the wire";
}
else if (::even == 0) {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 0) && (led == 1)) {
if (::even == 1) {
cout << endl << "Cut the wire";
}
else if (::even == 0) {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 1) && (led == 0)) {
if (::Parallel >= 1) {
cout << endl << "Cut the wire";
}
else {
cout << endl << "Do not cut the wire";
}
}
else if ((star == 1) && (led == 1)) {
cout << endl << "Do not cut the wire";
}
}
Next:
cout << endl << "Next wire?(Y/N) ";
cin >> next;
if (toupper(next) == 'Y') {
complicatedwires();
}
else if (toupper(next) == 'N') {
}
else {
cout << endl << "Enter a valid response.";
goto Next;
}
}
void wiresequence()
{
}
void maze()
{
}
void password()
{
char one_one;
char one_two;
char one_three;
char one_four;
char one_five;
char one_six;
char two_one;
char two_two;
char two_three;
char two_four;
char two_five;
char two_six;
char three_one;
char three_two;
char three_three;
char three_four;
char three_five;
char three_six;
cout << endl << "Enter the 6 letters of the first column, separated by spaces" << endl;
cin >> one_one >> one_two >> one_three >> one_four >> one_five >> one_six;
cout << endl << "Enter the 6 letters of the second column, separated by spaces" << endl;
cin >> two_one >> two_two >> two_three >> two_four >> two_five >> two_six;
cout << endl << "Enter the 6 letters of the third column, separated by spaces" << endl;
cin >> three_one >> three_two >> three_three >> three_four >> three_five >> three_six;
if ((toupper(one_one) == 'A') || (toupper(one_two) == 'A') || (toupper(one_three) == 'A') || (toupper(one_four) == 'A') || (toupper(one_five) == 'A') || (toupper(one_six) == 'A')) {
if ((toupper(two_one) == 'B') || (toupper(two_two) == 'B') || (toupper(two_three) == 'B') || (toupper(two_four) == 'B') || (toupper(two_five) == 'B') || (toupper(two_six) == 'B')) {
if ((toupper(three_one) == 'O') || (toupper(three_two) == 'O') || (toupper(three_three) == 'O') || (toupper(three_four) == 'O') || (toupper(three_five) == 'O') || (toupper(three_six) == 'O')) {
cout << endl << "The password may be 'ABOUT'";
}
}
if ((toupper(two_one) == 'F') || (toupper(two_two) == 'F') || (toupper(two_three) == 'F') || (toupper(two_four) == 'F') || (toupper(two_five) == 'F') || (toupper(two_six) == 'F')) {
if ((toupper(three_one) == 'T') || (toupper(three_two) == 'T') || (toupper(three_three) == 'T') || (toupper(three_four) == 'T') || (toupper(three_five) == 'T') || (toupper(three_six) == 'T')) {
cout << endl << "The password may be 'AFTER'";
}
}
if ((toupper(two_one) == 'G') || (toupper(two_two) == 'G') || (toupper(two_three) == 'G') || (toupper(two_four) == 'G') || (toupper(two_five) == 'G') || (toupper(two_six) == 'G')) {
if ((toupper(three_one) == 'A') || (toupper(three_two) == 'A') || (toupper(three_three) == 'A') || (toupper(three_four) == 'A') || (toupper(three_five) == 'A') || (toupper(three_six) == 'A')) {
cout << endl << "The password may be 'AGAIN'";
}
}
}
if ((toupper(one_one) == 'B') || (toupper(one_two) == 'B') || (toupper(one_three) == 'B') || (toupper(one_four) == 'B') || (toupper(one_five) == 'B') || (toupper(one_six) == 'B')) {
if ((toupper(two_one) == 'E') || (toupper(two_two) == 'E') || (toupper(two_three) == 'E') || (toupper(two_four) == 'E') || (toupper(two_five) == 'E') || (toupper(two_six) == 'E')) {
if ((toupper(three_one) == 'L') || (toupper(three_two) == 'L') || (toupper(three_three) == 'L') || (toupper(three_four) == 'L') || (toupper(three_five) == 'L') || (toupper(three_six) == 'L')) {
cout << endl << "The password may be 'BELOW'";
}
}
}
if ((toupper(one_one) == 'C') || (toupper(one_two) == 'C') || (toupper(one_three) == 'C') || (toupper(one_four) == 'C') || (toupper(one_five) == 'C') || (toupper(one_six) == 'C')) {
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be 'COULD'";
}
}
}
if ((toupper(one_one) == 'E') || (toupper(one_two) == 'E') || (toupper(one_three) == 'E') || (toupper(one_four) == 'E') || (toupper(one_five) == 'E') || (toupper(one_six) == 'E')) {
if ((toupper(two_one) == 'V') || (toupper(two_two) == 'V') || (toupper(two_three) == 'V') || (toupper(two_four) == 'V') || (toupper(two_five) == 'V') || (toupper(two_six) == 'V')) {
if ((toupper(three_one) == 'E') || (toupper(three_two) == 'E') || (toupper(three_three) == 'E') || (toupper(three_four) == 'E') || (toupper(three_five) == 'E') || (toupper(three_six) == 'E')) {
cout << endl << "The password may be 'EVERY'";
}
}
}
if ((toupper(one_one) == 'F') || (toupper(one_two) == 'F') || (toupper(one_three) == 'F') || (toupper(one_four) == 'F') || (toupper(one_five) == 'F') || (toupper(one_six) == 'F')) {
if ((toupper(two_one) == 'I') || (toupper(two_two) == 'I') || (toupper(two_three) == 'I') || (toupper(two_four) == 'I') || (toupper(two_five) == 'I') || (toupper(two_six) == 'I')) {
if ((toupper(three_one) == 'R') || (toupper(three_two) == 'R') || (toupper(three_three) == 'R') || (toupper(three_four) == 'R') || (toupper(three_five) == 'R') || (toupper(three_six) == 'R')) {
cout << endl << "The password may be 'FIRST'";
}
}
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be 'FOUND'";
}
}
}
if ((toupper(one_one) == 'G') || (toupper(one_two) == 'G') || (toupper(one_three) == 'G') || (toupper(one_four) == 'G') || (toupper(one_five) == 'G') || (toupper(one_six) == 'G')) {
if ((toupper(two_one) == 'R') || (toupper(two_two) == 'R') || (toupper(two_three) == 'R') || (toupper(two_four) == 'R') || (toupper(two_five) == 'R') || (toupper(two_six) == 'R')) {
if ((toupper(three_one) == 'E') || (toupper(three_two) == 'E') || (toupper(three_three) == 'E') || (toupper(three_four) == 'E') || (toupper(three_five) == 'E') || (toupper(three_six) == 'E')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
}
if ((toupper(one_one) == 'H') || (toupper(one_two) == 'H') || (toupper(one_three) == 'H') || (toupper(one_four) == 'H') || (toupper(one_five) == 'H') || (toupper(one_six) == 'H')) {
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be 'HOUSE'";
}
}
}
if ((toupper(one_one) == 'L') || (toupper(one_two) == 'L') || (toupper(one_three) == 'L') || (toupper(one_four) == 'L') || (toupper(one_five) == 'L') || (toupper(one_six) == 'L')) {
if ((toupper(two_one) == 'A') || (toupper(two_two) == 'A') || (toupper(two_three) == 'A') || (toupper(two_four) == 'A') || (toupper(two_five) == 'A') || (toupper(two_six) == 'A')) {
if ((toupper(three_one) == 'R') || (toupper(three_two) == 'R') || (toupper(three_three) == 'R') || (toupper(three_four) == 'R') || (toupper(three_five) == 'R') || (toupper(three_six) == 'R')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
if ((toupper(two_one) == 'E') || (toupper(two_two) == 'E') || (toupper(two_three) == 'E') || (toupper(two_four) == 'E') || (toupper(two_five) == 'E') || (toupper(two_six) == 'E')) {
if ((toupper(three_one) == 'A') || (toupper(three_two) == 'A') || (toupper(three_three) == 'A') || (toupper(three_four) == 'A') || (toupper(three_five) == 'A') || (toupper(three_six) == 'A')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
}
if ((toupper(one_one) == 'N') || (toupper(one_two) == 'N') || (toupper(one_three) == 'N') || (toupper(one_four) == 'N') || (toupper(one_five) == 'N') || (toupper(one_six) == 'N')) {
if ((toupper(two_one) == 'E') || (toupper(two_two) == 'E') || (toupper(two_three) == 'E') || (toupper(two_four) == 'E') || (toupper(two_five) == 'E') || (toupper(two_six) == 'E')) {
if ((toupper(three_one) == 'V') || (toupper(three_two) == 'V') || (toupper(three_three) == 'V') || (toupper(three_four) == 'V') || (toupper(three_five) == 'V') || (toupper(three_six) == 'V')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
}
if ((toupper(one_one) == 'O') || (toupper(one_two) == 'O') || (toupper(one_three) == 'O') || (toupper(one_four) == 'O') || (toupper(one_five) == 'O') || (toupper(one_six) == 'O')) {
if ((toupper(two_one) == 'T') || (toupper(two_two) == 'T') || (toupper(two_three) == 'T') || (toupper(two_four) == 'T') || (toupper(two_five) == 'T') || (toupper(two_six) == 'T')) {
if ((toupper(three_one) == 'H') || (toupper(three_two) == 'H') || (toupper(three_three) == 'H') || (toupper(three_four) == 'H') || (toupper(three_five) == 'H') || (toupper(three_six) == 'H')) {
cout << endl << "The password may be 'OTHER'";
}
}
}
if ((toupper(one_one) == 'P') || (toupper(one_two) == 'P') || (toupper(one_three) == 'P') || (toupper(one_four) == 'P') || (toupper(one_five) == 'P') || (toupper(one_six) == 'P')) {
if ((toupper(two_one) == 'L') || (toupper(two_two) == 'L') || (toupper(two_three) == 'L') || (toupper(two_four) == 'L') || (toupper(two_five) == 'L') || (toupper(two_six) == 'L')) {
if ((toupper(three_one) == 'A') || (toupper(three_two) == 'A') || (toupper(three_three) == 'A') || (toupper(three_four) == 'A') || (toupper(three_five) == 'A') || (toupper(three_six) == 'A')) {
cout << endl << "The password may be 'PLANT' or 'PLACE'";
}
}
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'I') || (toupper(three_two) == 'I') || (toupper(three_three) == 'I') || (toupper(three_four) == 'I') || (toupper(three_five) == 'I') || (toupper(three_six) == 'I')) {
cout << endl << "The password may be 'POINT'";
}
}
}
if ((toupper(one_one) == 'R') || (toupper(one_two) == 'R') || (toupper(one_three) == 'R') || (toupper(one_four) == 'R') || (toupper(one_five) == 'R') || (toupper(one_six) == 'R')) {
if ((toupper(two_one) == 'I') || (toupper(two_two) == 'I') || (toupper(two_three) == 'I') || (toupper(two_four) == 'I') || (toupper(two_five) == 'I') || (toupper(two_six) == 'I')) {
if ((toupper(three_one) == 'G') || (toupper(three_two) == 'G') || (toupper(three_three) == 'G') || (toupper(three_four) == 'G') || (toupper(three_five) == 'G') || (toupper(three_six) == 'G')) {
cout << endl << "The password may be 'RIGHT'";
}
}
}
if ((toupper(one_one) == 'S') || (toupper(one_two) == 'S') || (toupper(one_three) == 'S') || (toupper(one_four) == 'S') || (toupper(one_five) == 'S') || (toupper(one_six) == 'S')) {
if ((toupper(two_one) == 'M') || (toupper(two_two) == 'M') || (toupper(two_three) == 'M') || (toupper(two_four) == 'M') || (toupper(two_five) == 'M') || (toupper(two_six) == 'M')) {
if ((toupper(three_one) == 'A') || (toupper(three_two) == 'A') || (toupper(three_three) == 'A') || (toupper(three_four) == 'A') || (toupper(three_five) == 'A') || (toupper(three_six) == 'A')) {
cout << endl << "The password may be 'SMALL'";
}
}
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be 'SOUND'";
}
}
if ((toupper(two_one) == 'P') || (toupper(two_two) == 'P') || (toupper(two_three) == 'P') || (toupper(two_four) == 'P') || (toupper(two_five) == 'P') || (toupper(two_six) == 'P')) {
if ((toupper(three_one) == 'E') || (toupper(three_two) == 'E') || (toupper(three_three) == 'E') || (toupper(three_four) == 'E') || (toupper(three_five) == 'E') || (toupper(three_six) == 'E')) {
cout << endl << "The password may be 'SPELL'";
}
}
if ((toupper(two_one) == 'T') || (toupper(two_two) == 'T') || (toupper(two_three) == 'T') || (toupper(two_four) == 'T') || (toupper(two_five) == 'T') || (toupper(two_six) == 'T')) {
if ((toupper(three_one) == 'I') || (toupper(three_two) == 'I') || (toupper(three_three) == 'I') || (toupper(three_four) == 'I') || (toupper(three_five) == 'I') || (toupper(three_six) == 'I')) {
cout << endl << "The password may be 'STILL'";
}
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
}
if ((toupper(one_one) == 'T') || (toupper(one_two) == 'T') || (toupper(one_three) == 'T') || (toupper(one_four) == 'T') || (toupper(one_five) == 'T') || (toupper(one_six) == 'T')) {
if ((toupper(two_one) == 'H') || (toupper(two_two) == 'H') || (toupper(two_three) == 'H') || (toupper(two_four) == 'H') || (toupper(two_five) == 'H') || (toupper(two_six) == 'H')) {
if ((toupper(three_one) == 'E') || (toupper(three_two) == 'E') || (toupper(three_three) == 'E') || (toupper(three_four) == 'E') || (toupper(three_five) == 'E') || (toupper(three_six) == 'E')) {
cout << endl << "The password may be 'THEIR,' 'THERE,' or 'THESE'";
}
if ((toupper(three_one) == 'I') || (toupper(three_two) == 'I') || (toupper(three_three) == 'I') || (toupper(three_four) == 'I') || (toupper(three_five) == 'I') || (toupper(three_six) == 'I')) {
cout << endl << "The password may be '<PASSWORD>' or '<PASSWORD>'";
}
if ((toupper(three_one) == 'R') || (toupper(three_two) == 'R') || (toupper(three_three) == 'R') || (toupper(three_four) == 'R') || (toupper(three_five) == 'R') || (toupper(three_six) == 'R')) {
cout << endl << "The password may be '<PASSWORD>'";
}
}
}
if ((toupper(one_one) == 'W') || (toupper(one_two) == 'W') || (toupper(one_three) == 'W') || (toupper(one_four) == 'W') || (toupper(one_five) == 'W') || (toupper(one_six) == 'W')) {
if ((toupper(two_one) == 'A') || (toupper(two_two) == 'A') || (toupper(two_three) == 'A') || (toupper(two_four) == 'A') || (toupper(two_five) == 'A') || (toupper(two_six) == 'A')) {
if ((toupper(three_one) == 'T') || (toupper(three_two) == 'T') || (toupper(three_three) == 'T') || (toupper(three_four) == 'T') || (toupper(three_five) == 'T') || (toupper(three_six) == 'T')) {
cout << endl << "The password may be 'WATER'";
}
}
if ((toupper(two_one) == 'H') || (toupper(two_two) == 'H') || (toupper(two_three) == 'H') || (toupper(two_four) == 'H') || (toupper(two_five) == 'H') || (toupper(two_six) == 'H')) {
if ((toupper(three_one) == 'E') || (toupper(three_two) == 'E') || (toupper(three_three) == 'E') || (toupper(three_four) == 'E') || (toupper(three_five) == 'E') || (toupper(three_six) == 'E')) {
cout << endl << "The password may be 'WHERE'";
}
if ((toupper(three_one) == 'I') || (toupper(three_two) == 'I') || (toupper(three_three) == 'I') || (toupper(three_four) == 'I') || (toupper(three_five) == 'I') || (toupper(three_six) == 'I')) {
cout << endl << "The password may be 'WHICH'";
}
}
if ((toupper(two_one) == 'O') || (toupper(two_two) == 'O') || (toupper(two_three) == 'O') || (toupper(two_four) == 'O') || (toupper(two_five) == 'O') || (toupper(two_six) == 'O')) {
if ((toupper(three_one) == 'R') || (toupper(three_two) == 'R') || (toupper(three_three) == 'R') || (toupper(three_four) == 'R') || (toupper(three_five) == 'R') || (toupper(three_six) == 'R')) {
cout << endl << "The password may be 'WORLD'";
}
if ((toupper(three_one) == 'U') || (toupper(three_two) == 'U') || (toupper(three_three) == 'U') || (toupper(three_four) == 'U') || (toupper(three_five) == 'U') || (toupper(three_six) == 'U')) {
cout << endl << "The password may be 'WOULD'";
}
}
if ((toupper(two_one) == 'R') || (toupper(two_two) == 'R') || (toupper(two_three) == 'R') || (toupper(two_four) == 'R') || (toupper(two_five) == 'R') || (toupper(two_six) == 'R')) {
if ((toupper(three_one) == 'I') || (toupper(three_two) == 'I') || (toupper(three_three) == 'I') || (toupper(three_four) == 'I') || (toupper(three_five) == 'I') || (toupper(three_six) == 'I')) {
cout << endl << "The password may be 'WRITE'";
}
}
}
}
|
5dee6e38da84970f6b9e43a5b0b51bc94a786d8b
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
tyblocker/ktane
|
9ae65cde5f5e776b2bfaf1d048be831d17d55e0c
|
bfea4cfe339b9f971ef70553fab141248349600d
|
refs/heads/master
|
<repo_name>ludwigOleby/OOP_labb1<file_sep>/OOP_labb1/Program.cs
using System;
namespace OOP_labb1
{
class Program
{
static void Main(string[] args)
{
Circle c1 = new Circle(5);
Console.WriteLine("Cirkelns area:");
Console.WriteLine(c1.getArea());
Console.WriteLine("Cirkelns omkrets:");
Console.WriteLine(c1.getCircumference());
Console.WriteLine(" ");
Circle c2 = new Circle(6);
Console.WriteLine("Cirkelns area:");
Console.WriteLine(c2.getArea());
Console.WriteLine("Cirkelns omkrets:");
Console.WriteLine(c2.getCircumference());
}
}
public class Circle
{
public float _pi = 3.14f;
public int _radie;
public Circle(int r)
{
this._radie = r;
}
public double getArea()
{
float area = _radie * _radie * _pi;
return area;
}
public double getCircumference() //Extra utmaning omkrets
{
float diameter = _radie * 2;
float circumference = diameter * _pi;
return circumference;
}
}
}
|
fe4681fd07aa023315696770ebb5feb5efdfbf61
|
[
"C#"
] | 1
|
C#
|
ludwigOleby/OOP_labb1
|
4b53d18841c7b1d16ce80ce9d5dd5d30c3c8a642
|
da0778e4bcb4c11f6c74cef4b6d13befb73a9b48
|
refs/heads/master
|
<file_sep>package reet.fbk.eu.jmetal.stoppingCriteria;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.math3.stat.inference.KolmogorovSmirnovTest;
public class KSTest {
public KSTest() {
// TODO Auto-generated constructor stub
}
static double[] readFile() throws IOException{
BufferedReader br= new BufferedReader(new FileReader("test.txt"));
String str;
double [] arr=new double[300];
int i=0;
while( (str=br.readLine()) != null){
arr[i++]=Double.parseDouble(str);
}
return arr;
}
static void performTest(double [] array){
KolmogorovSmirnovTest kst = new KolmogorovSmirnovTest();
for(int i=35;i<300;i++){
double []x = Arrays.copyOfRange(array, (i-35), i-5);
double []y = Arrays.copyOfRange(array, i-5, i);
//System.out.println(Arrays.toString(x));
//System.out.println(Arrays.toString(y));
double pValue=kst.kolmogorovSmirnovTest(x, y);
System.out.println(i+" "+pValue);
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
double [] arr =readFile();
performTest(arr);
}
}
<file_sep>package reet.fbk.eu.jmetal.initialization.AnalysisResults;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import jmetal.experiments.Settings;
import jmetal.experiments.util.Statistics;
import jmetal.util.JMException;
public class LatexTable {
public String experimentName_;
public String[] algorithmNameList_; // List of the names of the algorithms to be executed
public String[] problemList_; // List of problems to be solved
//public String[] paretoFrontFile_; // List of the files containing the pareto fronts
// corresponding to the problems in problemList_
public String[] indicatorList_; // List of the quality indicators to be applied
public String experimentBaseDirectory_; // Directory to store the results
public String latexDirectory_; // Directory to store the latex files
//public String paretoFrontDirectory_; // Directory containing the Pareto front files
//public String outputParetoFrontFile_; // Name of the file containing the output
// Pareto front
//public String outputParetoSetFile_; // Name of the file containing the output
// Pareto set
//public int independentRuns_; // Number of independent runs per algorithm
//public Settings[] algorithmSettings_; // Paremeter experiments.settings of each algorithm
//Algorithm[] algorithm_; // jMetal algorithms to be executed
//HashMap<String, Object> map_; // Map used to send experiment parameters to threads
public HashMap<String, Boolean> indicatorMinimize_; // To indicate whether an indicator
LatexTable(){
experimentName_ = "noName";
algorithmNameList_ = null;
problemList_ = null;
indicatorList_ = null;
experimentBaseDirectory_ = "";
latexDirectory_ = "latex";
indicatorMinimize_ = new HashMap<String, Boolean>();
indicatorMinimize_.put("HV", false);
indicatorMinimize_.put("Epsilon", true);
indicatorMinimize_.put("Spread", true);
indicatorMinimize_.put("GD", true);
indicatorMinimize_.put("IGD", true);
}
public void generateLatexTables() throws FileNotFoundException, IOException {
latexDirectory_ = experimentBaseDirectory_ + "/" + latexDirectory_;
System.out.println("latex directory: " + latexDirectory_);
Vector[][][] data = new Vector[indicatorList_.length][][];
for (int indicator = 0; indicator < indicatorList_.length; indicator++) {
// A data vector per problem
data[indicator] = new Vector[problemList_.length][];
for (int problem = 0; problem < 1; problem++) {
data[indicator][problem] = new Vector[algorithmNameList_.length];
for (int algorithm = 0; algorithm < algorithmNameList_.length; algorithm++) {
data[indicator][problem][algorithm] = new Vector();
String directory = experimentBaseDirectory_;
//directory += "/data/";
directory += "/" + algorithmNameList_[algorithm];
//directory += "/" + problemList_[problem];
directory += "/" + indicatorList_[indicator];
// Read values from data files
FileInputStream fis = new FileInputStream(directory);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//System.out.println(directory);
String aux = br.readLine();
while (aux != null) {
data[indicator][problem][algorithm].add(Double.parseDouble(aux));
//System.out.println(Double.parseDouble(aux));
aux = br.readLine();
} // while
} // for
} // for
} // for
double[][][] mean;
double[][][] median;
double[][][] stdDeviation;
double[][][] iqr;
double[][][] max;
double[][][] min;
int[][][] numberOfValues;
Map<String, Double> statValues = new HashMap<String, Double>();
statValues.put("mean", 0.0);
statValues.put("median", 0.0);
statValues.put("stdDeviation", 0.0);
statValues.put("iqr", 0.0);
statValues.put("max", 0.0);
statValues.put("min", 0.0);
mean = new double[indicatorList_.length][][];
median = new double[indicatorList_.length][][];
stdDeviation = new double[indicatorList_.length][][];
iqr = new double[indicatorList_.length][][];
min = new double[indicatorList_.length][][];
max = new double[indicatorList_.length][][];
numberOfValues = new int[indicatorList_.length][][];
for (int indicator = 0; indicator < indicatorList_.length; indicator++) {
// A data vector per problem
mean[indicator] = new double[problemList_.length][];
median[indicator] = new double[problemList_.length][];
stdDeviation[indicator] = new double[problemList_.length][];
iqr[indicator] = new double[problemList_.length][];
min[indicator] = new double[problemList_.length][];
max[indicator] = new double[problemList_.length][];
numberOfValues[indicator] = new int[problemList_.length][];
for (int problem = 0; problem < 1; problem++) {
mean[indicator][problem] = new double[algorithmNameList_.length];
median[indicator][problem] = new double[algorithmNameList_.length];
stdDeviation[indicator][problem] = new double[algorithmNameList_.length];
iqr[indicator][problem] = new double[algorithmNameList_.length];
min[indicator][problem] = new double[algorithmNameList_.length];
max[indicator][problem] = new double[algorithmNameList_.length];
numberOfValues[indicator][problem] = new int[algorithmNameList_.length];
for (int algorithm = 0; algorithm < algorithmNameList_.length; algorithm++) {
Collections.sort(data[indicator][problem][algorithm]);
String directory = experimentBaseDirectory_;
directory += "/" + algorithmNameList_[algorithm];
//directory += "/" + problemList_[problem];
directory += "/" + indicatorList_[indicator];
//System.out.println("----" + directory + "-----");
//calculateStatistics(data[indicator][problem][algorithm], meanV, medianV, minV, maxV, stdDeviationV, iqrV) ;
calculateStatistics(data[indicator][problem][algorithm], statValues);
/*
System.out.println("Mean: " + statValues.get("mean"));
System.out.println("Median : " + statValues.get("median"));
System.out.println("Std : " + statValues.get("stdDeviation"));
System.out.println("IQR : " + statValues.get("iqr"));
System.out.println("Min : " + statValues.get("min"));
System.out.println("Max : " + statValues.get("max"));
System.out.println("N_values: " + data[indicator][problem][algorithm].size()) ;
*/
mean[indicator][problem][algorithm] = statValues.get("mean");
median[indicator][problem][algorithm] = statValues.get("median");
stdDeviation[indicator][problem][algorithm] = statValues.get("stdDeviation");
iqr[indicator][problem][algorithm] = statValues.get("iqr");
min[indicator][problem][algorithm] = statValues.get("min");
max[indicator][problem][algorithm] = statValues.get("max");
numberOfValues[indicator][problem][algorithm] = data[indicator][problem][algorithm].size();
}
}
}
File latexOutput;
latexOutput = new File(latexDirectory_);
if (!latexOutput.exists()) {
boolean result = new File(latexDirectory_).mkdirs();
System.out.println("Creating " + latexDirectory_ + " directory");
}
//System.out.println("Experiment name: " + experimentName_);
String latexFile = latexDirectory_ + "/" + "results" + ".tex";
printHeaderLatexCommands(latexFile);
for (int i = 0; i < indicatorList_.length; i++) {
printMeanStdDev(latexFile, i, mean, stdDeviation);
printMedianIQR(latexFile, i, median, iqr);
} // for
printEndLatexCommands(latexFile);
} // generateLatexTables
/**
* Calculates statistical values from a vector of Double objects
* @param vector
* @param values
*/
void calculateStatistics(Vector vector,
Map<String, Double> values) {
if (vector.size() > 0) {
double sum, minimum, maximum, sqsum, min, max, median, mean, iqr, stdDeviation;
sqsum = 0.0;
sum = 0.0;
min = 1E300;
max = -1E300;
median = 0;
for (int i = 0; i < vector.size(); i++) {
double val = (Double) vector.elementAt(i);
sqsum += val * val;
sum += val;
if (val < min) {
min = val;
}
if (val > max) {
max = val;
} // if
} // for
// Mean
mean = sum / vector.size();
// Standard deviation
if (sqsum / vector.size() - mean * mean < 0.0) {
stdDeviation = 0.0;
} else {
stdDeviation = Math.sqrt(sqsum / vector.size() - mean * mean);
} // if
// Median
if (vector.size() % 2 != 0) {
median = (Double) vector.elementAt(vector.size() / 2);
} else {
median = ((Double) vector.elementAt(vector.size() / 2 - 1) +
(Double) vector.elementAt(vector.size() / 2)) / 2.0;
} // if
values.put("mean", mean);
values.put("median", Statistics.calculateMedian(vector, 0, vector.size() - 1));
values.put("iqr", Statistics.calculateIQR(vector));
values.put("stdDeviation", stdDeviation);
values.put("min", (Double) min);
values.put("max", (Double) max);
} // if
else {
values.put("mean", Double.NaN);
values.put("median", Double.NaN);
values.put("iqr", Double.NaN);
values.put("stdDeviation", Double.NaN);
values.put("min", Double.NaN);
values.put("max", Double.NaN);
} // else
} // calculateStatistics
void printHeaderLatexCommands(String fileName) throws IOException {
FileWriter os = new FileWriter(fileName, false);
os.write("\\documentclass{article}" + "\n");
os.write("\\title{" + experimentName_ + "}" + "\n");
os.write("\\usepackage{colortbl}" + "\n");
os.write("\\usepackage[table*]{xcolor}" + "\n");
os.write("\\xdefinecolor{gray95}{gray}{0.65}" + "\n");
os.write("\\xdefinecolor{gray25}{gray}{0.8}" + "\n");
os.write("\\author{}" + "\n");
os.write("\\begin{document}" + "\n");
os.write("\\maketitle" + "\n");
os.write("\\section{Tables}" + "\n");
os.close();
}
void printEndLatexCommands(String fileName) throws IOException {
FileWriter os = new FileWriter(fileName, true);
os.write("\\end{document}" + "\n");
os.close();
} // printEndLatexCommands
void printMeanStdDev(String fileName, int indicator, double[][][] mean, double[][][] stdDev) throws IOException {
FileWriter os = new FileWriter(fileName, true);
os.write("\\" + "\n");
os.write("\\begin{table}" + "\n");
os.write("\\caption{" + indicatorList_[indicator] + ". Mean and standard deviation}" + "\n");
os.write("\\label{table:mean." + indicatorList_[indicator] + "}" + "\n");
os.write("\\centering" + "\n");
os.write("\\begin{scriptsize}" + "\n");
os.write("\\begin{tabular}{l");
// calculate the number of columns
for (String anAlgorithmNameList_ : algorithmNameList_) {
os.write("l");
}
os.write("}\n");
os.write("\\hline");
// write table head
for (int i = -1; i < algorithmNameList_.length; i++) {
if (i == -1) {
os.write(" & ");
} else if (i == (algorithmNameList_.length - 1)) {
os.write(" " + algorithmNameList_[i] + "\\\\" + "\n");
} else {
os.write("" + algorithmNameList_[i] + " & ");
}
}
os.write("\\hline" + "\n");
String m, s;
// write lines
for (int i = 0; i < problemList_.length; i++) {
// find the best value and second best value
double bestValue ;
double bestValueIQR ;
double secondBestValue ;
double secondBestValueIQR ;
int bestIndex = -1 ;
int secondBestIndex = -1 ;
if ((Boolean) indicatorMinimize_.get(indicatorList_[indicator])) {// minimize by default
bestValue = Double.MAX_VALUE;
bestValueIQR = Double.MAX_VALUE;
secondBestValue = Double.MAX_VALUE;
secondBestValueIQR = Double.MAX_VALUE;
for (int j = 0; j < (algorithmNameList_.length); j++) {
if ((mean[indicator][i][j] < bestValue) ||
((mean[indicator][i][j] == bestValue) && (stdDev[indicator][i][j] < bestValueIQR))) {
secondBestIndex = bestIndex ;
secondBestValue = bestValue ;
secondBestValueIQR = bestValueIQR ;
bestValue = mean[indicator][i][j];
bestValueIQR = stdDev[indicator][i][j];
bestIndex = j;
}
else if ((mean[indicator][i][j] < secondBestValue) ||
((mean[indicator][i][j] == secondBestValue) && (stdDev[indicator][i][j] < secondBestValueIQR))) {
secondBestIndex = j ;
secondBestValue = mean[indicator][i][j] ;
secondBestValueIQR = stdDev[indicator][i][j] ;
} // else if
}
} // if
else { // indicator to maximize e.g., the HV
bestValue = Double.MIN_VALUE;
bestValueIQR = Double.MIN_VALUE;
secondBestValue = Double.MIN_VALUE;
secondBestValueIQR = Double.MIN_VALUE;
for (int j = 0; j < (algorithmNameList_.length); j++) {
if ((mean[indicator][i][j] > bestValue) ||
((mean[indicator][i][j] == bestValue) && (stdDev[indicator][i][j] < bestValueIQR))) {
secondBestIndex = bestIndex ;
secondBestValue = bestValue ;
secondBestValueIQR = bestValueIQR ;
bestValue = mean[indicator][i][j];
bestValueIQR = stdDev[indicator][i][j];
bestIndex = j;
}
else if ((mean[indicator][i][j] > secondBestValue) ||
((mean[indicator][i][j] == secondBestValue) && (stdDev[indicator][i][j] < secondBestValueIQR))) {
secondBestIndex = j ;
secondBestValue = mean[indicator][i][j] ;
secondBestValueIQR = stdDev[indicator][i][j] ;
} // else if
} // for
} // else
os.write(problemList_[i].replace("_", "\\_") + " & ");
for (int j = 0; j <= (algorithmNameList_.length - 1); j++) {
if (j == bestIndex) {
os.write("\\cellcolor{gray95}");
}
if (j == secondBestIndex) {
os.write("\\cellcolor{gray25}");
}
m = String.format(Locale.ENGLISH, "%10.2e", mean[indicator][i][j]);
s = String.format(Locale.ENGLISH, "%8.1e", stdDev[indicator][i][j]);
//os.write("$" + m + "_{" + s + "}$ & ");
if(j==algorithmNameList_.length-1)
os.write("$" + m + "_{" + s + "}$ \\\\" + "\n");
else
os.write("$" + m + "_{" + s + "}$ & ");
}
/*if (bestIndex == (algorithmNameList_.length - 1)) {
os.write("\\cellcolor{gray95}");
}
m = String.format(Locale.ENGLISH, "%10.2e", mean[indicator][i][algorithmNameList_.length - 1]);
s = String.format(Locale.ENGLISH, "%8.1e", stdDev[indicator][i][algorithmNameList_.length - 1]);
os.write("$" + m + "_{" + s + "}$ \\\\" + "\n");*/
} // for
//os.write("" + mean[0][problemList_.length-1][algorithmNameList_.length-1] + "\\\\"+ "\n" ) ;
os.write("\\hline" + "\n");
os.write("\\end{tabular}" + "\n");
os.write("\\end{scriptsize}" + "\n");
os.write("\\end{table}" + "\n");
os.close();
} // printMeanStdDev
void printMedianIQR(String fileName, int indicator, double[][][] median, double[][][] IQR) throws IOException {
FileWriter os = new FileWriter(fileName, true);
os.write("\\" + "\n");
os.write("\\begin{table}" + "\n");
os.write("\\caption{" + indicatorList_[indicator] + ". Median and IQR}" + "\n");
os.write("\\label{table:median." + indicatorList_[indicator] + "}" + "\n");
os.write("\\begin{scriptsize}" + "\n");
os.write("\\centering" + "\n");
os.write("\\begin{tabular}{l");
// calculate the number of columns
for (String anAlgorithmNameList_ : algorithmNameList_) {
os.write("l");
}
os.write("}\n");
os.write("\\hline");
// write table head
for (int i = -1; i < algorithmNameList_.length; i++) {
if (i == -1) {
os.write(" & ");
} else if (i == (algorithmNameList_.length - 1)) {
os.write(" " + algorithmNameList_[i] + "\\\\" + "\n");
} else {
os.write("" + algorithmNameList_[i] + " & ");
}
}
os.write("\\hline" + "\n");
String m, s;
// write lines
for (int i = 0; i < problemList_.length; i++) {
// find the best value and second best value
double bestValue ;
double bestValueIQR ;
double secondBestValue ;
double secondBestValueIQR ;
int bestIndex = -1 ;
int secondBestIndex = -1 ;
if ((Boolean) indicatorMinimize_.get(indicatorList_[indicator])) {// minimize by default
bestValue = Double.MAX_VALUE;
bestValueIQR = Double.MAX_VALUE;
secondBestValue = Double.MAX_VALUE;
secondBestValueIQR = Double.MAX_VALUE;
for (int j = 0; j < (algorithmNameList_.length); j++) {
if ((median[indicator][i][j] < bestValue) ||
((median[indicator][i][j] == bestValue) && (IQR[indicator][i][j] < bestValueIQR))) {
secondBestIndex = bestIndex ;
secondBestValue = bestValue ;
secondBestValueIQR = bestValueIQR ;
bestValue = median[indicator][i][j];
bestValueIQR = IQR[indicator][i][j];
bestIndex = j;
}
else if ((median[indicator][i][j] < secondBestValue) ||
((median[indicator][i][j] == secondBestValue) && (IQR[indicator][i][j] < secondBestValueIQR))) {
secondBestIndex = j ;
secondBestValue = median[indicator][i][j] ;
secondBestValueIQR = IQR[indicator][i][j] ;
} // else if
} // for
} // if
else { // indicator to maximize e.g., the HV
bestValue = Double.MIN_VALUE;
bestValueIQR = Double.MIN_VALUE;
secondBestValue = Double.MIN_VALUE;
secondBestValueIQR = Double.MIN_VALUE;
for (int j = 0; j < (algorithmNameList_.length); j++) {
if ((median[indicator][i][j] > bestValue) ||
((median[indicator][i][j] == bestValue) && (IQR[indicator][i][j] < bestValueIQR))) {
secondBestIndex = bestIndex ;
secondBestValue = bestValue ;
secondBestValueIQR = bestValueIQR ;
bestValue = median[indicator][i][j];
bestValueIQR = IQR[indicator][i][j];
bestIndex = j;
}
else if ((median[indicator][i][j] > secondBestValue) ||
((median[indicator][i][j] == secondBestValue) && (IQR[indicator][i][j] < secondBestValueIQR))) {
secondBestIndex = j ;
secondBestValue = median[indicator][i][j] ;
secondBestValueIQR = IQR[indicator][i][j] ;
} // else if
} // for
} // else
os.write(problemList_[i].replace("_", "\\_") + " & ");
for (int j = 0; j <= (algorithmNameList_.length - 1); j++) {
if (j == bestIndex) {
os.write("\\cellcolor{gray95}");
}
if (j == secondBestIndex) {
os.write("\\cellcolor{gray25}");
}
m = String.format(Locale.ENGLISH, "%10.2e", median[indicator][i][j]);
s = String.format(Locale.ENGLISH, "%8.1e", IQR[indicator][i][j]);
//next line is original: disabled by shaikat
//os.write("$" + m + "_{" + s + "}$ & ");
if(j==algorithmNameList_.length-1)
os.write("$" + m + "_{" + s + "}$ \\\\" + "\n");
else
os.write("$" + m + "_{" + s + "}$ & ");
}
/*if (bestIndex == (algorithmNameList_.length - 1)) {
os.write("\\cellcolor{gray95}");
}
m = String.format(Locale.ENGLISH, "%10.2e", median[indicator][i][algorithmNameList_.length - 1]);
s = String.format(Locale.ENGLISH, "%8.1e", IQR[indicator][i][algorithmNameList_.length - 1]);
os.write("$" + m + "_{" + s + "}$ \\\\" + "\n");*/
} // for
//os.write("" + mean[0][problemList_.length-1][algorithmNameList_.length-1] + "\\\\"+ "\n" ) ;
os.write("\\hline" + "\n");
os.write("\\end{tabular}" + "\n");
os.write("\\end{scriptsize}" + "\n");
os.write("\\end{table}" + "\n");
os.close();
} // printMedianIQR
public static void main(String[] args) throws JMException {
LatexTable lt=new LatexTable();
lt.experimentName_ = "" ;
lt.algorithmNameList_ = new String[] {
"SPEA2WithoutTrack", "SPEA2WithoutTrackWithSI/WithoutRM"} ;
lt.problemList_ = new String[] {
""} ;
lt.indicatorList_ = new String[] {"HV", "Spread", "IGD", "Epsilon", "GD"} ;
int numberOfAlgorithms = lt.algorithmNameList_.length ;
lt.experimentBaseDirectory_ = "C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/InitializationResults" +
lt.experimentName_;
try {
lt.generateLatexTables();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII with domain-knowledge mutation for.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 10
Algorithm: NSGA-II
selection: Binary Tournament 2.
//run#1 to run# 10
seed [] = {545782, 455875, 547945, 458478, 981354, 652262, 562366, 365652, 456545, 549235 };
//2nd 10 runs with 10 new seeds (run # 11 to run #20)
long seed [] = {
161395,
276644,
309259,
370995,
468245,
515856,
668763,
698156,
756252,
930462
};
//3rd seed for nsgaii (run#21 to run#30)
long seed [] = {
170339,
259029,
288470,
353882,
626495,
683991,
714786,
989776,
992177,
999921
};
The seeds are same that is used in initilization experiment. It'll help to compare with typical NSGAII as two algorithms starts from same initialized individuals.
mergeFUN_NDK: merge all 30 runs fo NSGA-II with DK mutation<file_sep>This is the results (FUN and VAR) of 30 different runs with integrated NSGAII (Smart initialization + DK mutataion + Stopping criteria).
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 10
Algorithm: NSGAIIForDKandSCandSI (reet.fbk.eu.jmetal.metaheuristics.nsgaII)
selection: Binary Tournament 2.
Domain-knowledge (same used for Smart Initialization and DKMutataion):
Boolean favorGenesforRE[] = { true, true, true, true, true };
Boolean favorGenesforConventionalPP[] = { false, false, false,false, false };
Parameters for Stopping criteria:
nGenLT = 20
noGenUnCh = 5;
significanceValue = 0.05;
Output:
FUN*: Fun files for different run
VAR*: var files for diferent run
StoppingGen: stopping generation fr different run
mergeFuUN_NInt: merge all Pareto-front of 30 runs for NSGA-II integrated/combined approach<file_sep>package reet.fbk.eu.jmetal.operators.mutation.RE;
//BitFlipMutation.java
//
//Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
//Copyright (c) 2011 <NAME>, <NAME>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import jmetal.core.Solution;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
import reet.fbk.eu.jmetal.operators.mutation.DKRE.BitFlipMutationFavorMaximizationOfRes;
import reet.fbk.eu.jmetal.operators.mutation.DKRE.BitFlipMutationFavorMaximizationOfPP;
import jmetal.operators.mutation.*;
/**
* This class implements a bit flip mutation operator. NOTE: the operator is
* applied to binary or integer solutions, considering the whole solution as a
* single encodings.variable.
*/
public class GeneralBitFlipMutationForRes extends Mutation {
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays.asList(BinaryIntSolutionType.class, BinaryIntAndRealSolutionType.class);
private Double bitFlipMutationProbability_ = null;
private BitFlipMutationForRes bitFlipMutationForRes;
private BitFlipMutationFavorMaximizationOfRes bitFlipMutationFavorMaximizationOfRes;
private BitFlipMutationFavorMaximizationOfPP bitFlipMutationFavorMaximizationOfPP;
/**
* Constructor Creates a new instance of the Bit Flip mutation operator
*/
public GeneralBitFlipMutationForRes(HashMap<String, Object> parameters) {
super(parameters);
if (parameters.get("bitFlipMutationprobability") != null)
bitFlipMutationProbability_ = (Double) parameters.get("bitFlipMutationprobability");
bitFlipMutationForRes = new BitFlipMutationForRes(parameters);
bitFlipMutationFavorMaximizationOfRes = new BitFlipMutationFavorMaximizationOfRes(
parameters);
bitFlipMutationFavorMaximizationOfPP = new BitFlipMutationFavorMaximizationOfPP(
parameters);
} // BitFlipMutation
/**
* Perform the mutation operation
*
* @param probability
* Mutation probability
* @param solution
* The solution to mutate
* @throws JMException
*/
public void doMutation(double probability, Solution solution)
throws JMException {
try {
int random = PseudoRandom.randInt(0, 100);
if (random <= 15) {
bitFlipMutationFavorMaximizationOfRes.doMutation(
probability, solution);
} else if (random > 15 && random <= 30) {
bitFlipMutationFavorMaximizationOfPP.doMutation(
probability, solution);
} else {
bitFlipMutationForRes.doMutation(probability, solution);
}
} catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: "
+ "ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation*/
/**
* Executes the operation
*
* @param object
* An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_
.severe("BitFlipMutation.execute: the solution "
+ "is not of the right type. The type should be 'Binary', "
+ "'BinaryReal' or 'Int', but "
+ solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation(bitFlipMutationProbability_, solution);
return solution;
} // execute
} // BitFlipMutation
<file_sep>This is the initial individuals of 10 different runs with 10 different seeds.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution (modified to work without PP and boiler capacity, now, the number of decision variable is 5. The file will be found in initilization folder)
seed [] = {545454, 565656, 455885, 245454, 714451,752453,125742,455411, 447551, 844545 };
Boolean favorGenesforRE[] ={true, true, true, true, true};
Boolean favorGenesforConventionalPP[] ={false, false, false, false, false};
Parameters regarding smal initialization:
theta = 6.0
MaxDistributionIndex = 3
numberOfIndevPerCombination = 4
numberOfRandomIndividuals=200
//2nd seeding list
long seed[] = { 144759, 271439, 445964, 494817, 530563, 724859, 746153, 747584, 866309, 938562};
//3rd seeding list
long seed[] = {
172480,
242648,
268602,
272313,
412455,
441996,
633160,
814562,
822805,
843288
};
<file_sep>package reet.fbk.eu.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class EnergyPLANRunTimeTest {
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
public static void main(String[] args) throws IOException {
/*for(int i=0;i<100;i++) {
File source = new File("C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\spool\\Aalborg2050_vision.txt");
File dest = new File("C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\spool\\Aalborg2050_vision"+i+".txt");
dest.createNewFile();
copyFileUsingStream(source,dest);
}*/
int numberOfRun= 100;
String runSpoolEnergyPLAN = "C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\energyplan.exe -spool "+numberOfRun+ " ";
for(int i=0;i<numberOfRun;i++) {
runSpoolEnergyPLAN = runSpoolEnergyPLAN + "Aalborg2050_vision"+i+".txt ";
}
runSpoolEnergyPLAN = runSpoolEnergyPLAN + "-ascii run";
long initTime = System.currentTimeMillis();
try{
Process process = Runtime.getRuntime().exec(runSpoolEnergyPLAN);
process.waitFor();
process.destroy();
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
long estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("Energyplan spool: Total execution time: " + estimatedTime/1000.0 + "s");
initTime = System.currentTimeMillis();
for(int i = 0;i<numberOfRun; i++) {
String runSequentialEnergyplan = "C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\energyplan.exe -i "+
"C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\spool\\Aalborg2050_vision"+i+".txt -ascii result"+i+".txt";
try{
Process process = Runtime.getRuntime().exec(runSequentialEnergyplan);
process.waitFor();
process.destroy();
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
}
estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("EnergyPLAN sequential: Total execution time: " + estimatedTime/1000.0 + "s");
initTime = System.currentTimeMillis();
for(int i = 0;i<numberOfRun; i++) {
String runSequentialEnergyplan = "C:\\Users\\shaik\\eclipse-workspace\\EnergyPLANDomainKnowledgeEA\\EnergyPLAN_12.3_test\\energyplan.exe -i "+
"C:\\Users\\shaik\\Desktop\\EnergyPLAm15.1\\spool\\Aalborg2050_vision"+i+".txt -ascii result"+i+".txt";
try{
Process process = Runtime.getRuntime().exec(runSequentialEnergyplan);
process.waitFor();
process.destroy();
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
}
estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("EnergyPLAN12.3 sequential: Total execution time: " + estimatedTime/1000.0 + "s");
}
}
<file_sep>All the Pareto fronts found in 240 different runs are merged. And new Pareto front is built.
mergeFUN_N: all Pareto front from 30 runs with NSGAII with mutation probability 0.1
mergeFUN_NSI_WRM: all Pareto front from 30 runs with NSGAII with smart inililization without random individuals with mutation probability 0.1
mergeFUN_S: all Pareto front from 30 runs with SPEA2 with mutation probability 0.1
mergeFUN_SSI_WRM: all Pareto front from 30 runs with SPEA2 with smart inililization without random individuals with mutation probability 0.1
mergeFUN_NDK: all Pareto front from 30 runs with NSGAII with DK/smart mutation with mutation probability 0.1
mergeFUN_SDK: all Pareto front from 30 runs with SPEA2 with DK/smart mutation with mutation probability 0.1
mergeFUN_NInt_WRM_AllEvo: all Pareto front from 30 runs with NSGAII with integrated/combined approach without random individuals in initialization phase (With mutation probability 0.1) and all evaluations completed
mergeFUN_SInt_WRM_AllEvo: all Pareto front from 30 runs with SPEA2 with integrated/combined approach without random individuals in initialization phase (With mutation probability 0.1) and all evaluations completed
mergeFUN: merge mergeFUN_*
mergeFUN.pf: Pareto front after merging smart initializzation+ DK/smart mutation+integratedMOEA results
<file_sep>SPEA2 and SPEA2_SI forlder have the average of each indicator values with each generation of 30 runs. The used Pareto front is "InitializationResults\\ParetoFront\\WithoutRM\\With_mutation_pr_0.1\\mergeFUN.pf".
SPEA2 configuration:
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: SPEA2
selection: Binary Tournament 2.
archiveSize: 100
SPEA2 seeds:
126113,
148456,
154568,
212139,
274587,
289982,
368817,
387808,
418353,
430544,
434057,
447514,
458475,
467542,
471922,
500024,
585464,
596970,
622980,
632376,
686544,
712584,
784248,
808035,
833359,
879899,
888346,
953022,
975572,
983349
SPEA2_DK Configurations:
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution (modified to work without PP and boiler capacity, now, the number of decision variable is 5. The file will be found in initilization folder)
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForRes (DKMutation)
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm:SPEA2ForSI
selection: Binary Tournament 2.
seed:
126113,
148456,
154568,
212139,
274587,
289982,
368817,
387808,
418353,
430544,
434057,
447514,
458475,
467542,
471922,
500024,
585464,
596970,
622980,
632376,
686544,
712584,
784248,
808035,
833359,
879899,
888346,
953022,
975572,
983349
Results:
Comparison of SPEA2 with SPEA2_DK for each generation (on average).xlsx
<file_sep>package reet.fbk.eu.jmetal.operators.mutation.Real;
/*this class simplly implements mutation that favoring RE based on
* Normal distribution
*
*
*/
import jmetal.core.Solution;
import jmetal.core.SolutionType;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
import jmetal.operators.mutation.*;
import org.apache.commons.math3.distribution.NormalDistribution;
public class DKRealMutationFavorConventionalPP extends Mutation {
/**
* The array will keep track on which gene the mutation will be applied true
* means apply the mutation to increase and false means apply mutation to
* decrease and null means do nothing {Off-Shore wind, on-shore wind, Solar,
* PP, coal, oil, ngas}
*/
private static Boolean favorGenes[] = new Boolean[] { false, false, false,
null, true, null, false };
private Double bitFlipMutationProbability_ = null;
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays
.asList(RealSolutionType.class);
/**
* Constructor Creates a new instance of the Bit Flip mutation operator
*/
public DKRealMutationFavorConventionalPP(HashMap<String, Object> parameters) {
super(parameters);
/*
* if (parameters.get("bitFlipMutationProbability") != null)
* bitFlipMutationProbability_ = (Double) parameters
* .get("bitFlipMutationProbability");
*/
}
public static void main(String args[]) {
NormalDistribution nd = new NormalDistribution(0, 1);
System.out.println(nd.density(0.2));
}
/**
* Perform the mutation operation
*
* @param probability
* Mutation probability
* @param solution
* The solution to mutate
* @throws JMException
*/
public void doMutation(double probability, Solution solution)
throws JMException {
try {
if (solution.getType().getClass() == RealSolutionType.class) {
for (int i = 0; i < solution.getDecisionVariables().length; i++) {
// do mutation on all variables
// check if the probability is greater than a given
// probability
if (PseudoRandom.randDouble() < probability) {
try {
if (favorGenes[i] == true) {
double indvValue = solution
.getDecisionVariables()[i].getValue();
double newIndvValue = indvValue;
double distLowerBound = indvValue;
double distUpperBound = solution
.getDecisionVariables()[i]
.getUpperBound();
if((distUpperBound - indvValue)>0.0){
NormalDistribution nd = new NormalDistribution(
indvValue,
(distUpperBound - indvValue) / 3);
double rand = PseudoRandom.randDouble();
newIndvValue = nd
.inverseCumulativeProbability(nd
.cumulativeProbability(distLowerBound)
+ rand
* (nd.cumulativeProbability(distUpperBound) - nd
.cumulativeProbability(distLowerBound)));
}
solution.getDecisionVariables()[i]
.setValue(newIndvValue);
}
else {
double indvValue = solution
.getDecisionVariables()[i].getValue();
double newIndvValue = indvValue;
double distLowerBound = solution
.getDecisionVariables()[i]
.getLowerBound();
double distUpperBound = indvValue;
if ((indvValue - distLowerBound) > 0) {
NormalDistribution nd = new NormalDistribution(
indvValue,
(indvValue - distLowerBound) / 3);
double rand = PseudoRandom.randDouble();
newIndvValue = nd
.inverseCumulativeProbability(nd
.cumulativeProbability(distLowerBound)
+ rand
* (nd.cumulativeProbability(distUpperBound) - nd
.cumulativeProbability(distLowerBound)));
}
solution.getDecisionVariables()[i]
.setValue(newIndvValue);
}
} catch (NullPointerException e) {
continue;
}
} // if
}
}// else
} catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: "
+ "ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation
/**
* Executes the operation
*
* @param object
* An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_
.severe("BitFlipMutation.execute: the solution "
+ "is not of the right type. The type should be 'Binary', "
+ "'BinaryReal ' or 'Int', but "
+ solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation(bitFlipMutationProbability_, solution);
return solution;
} // execute
}<file_sep>#this scipt is used to generate a boxplot with four indicator (hypervolume, IGD, Epsilon, spead)
postscript("Compare_5Confs_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=6, width=8.5, pointsize=12)
#pdf("combined_comparison.pdf", onefile=FALSE, width=8.5, height = 6)
#jpeg(filename = "combined_comparison.jpeg", width = 8.5, height = 6, units = "in", pointsize = 10, res = 1000)
SPEA2resultDirectory<-"../"
SPEA2qIndicator <- function(indicator)
{
fileSPEA2<-paste(SPEA2resultDirectory, "SPEA2", sep="/")
fileSPEA2<-paste(fileSPEA2, indicator, sep="/")
SPEA2_results<-scan(fileSPEA2)
fileSPEA2si<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_SI", sep="/")
fileSPEA2si<-paste(fileSPEA2si, indicator, sep="/")
SPEA2si_results<-scan(fileSPEA2si)
#3rd algorithm (DivMa : conf 1)
fileSPEA2si_DivMax_conf1<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_DivMax_Conf1", sep="/")
fileSPEA2si_DivMax_conf1<-paste(fileSPEA2si_DivMax_conf1, indicator, sep="/")
SPEA2si_DivMax_conf1_results<-scan(fileSPEA2si_DivMax_conf1)
#4th algorithm (DivMax : conf 2)
fileSPEA2si_DivMax_conf2<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_DivMax_Conf2", sep="/")
fileSPEA2si_DivMax_conf2<-paste(fileSPEA2si_DivMax_conf2, indicator, sep="/")
SPEA2si_DivMax_conf2_results<-scan(fileSPEA2si_DivMax_conf2)
#5th algorithm (DivMax : conf 3)
fileSPEA2si_DivMax_conf3<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_DivMax_Conf3", sep="/")
fileSPEA2si_DivMax_conf3<-paste(fileSPEA2si_DivMax_conf3, indicator, sep="/")
SPEA2si_DivMax_conf3_results<-scan(fileSPEA2si_DivMax_conf3)
algs<-c("RI","SI", "DC1", "DC2", "DC3")
boxplot(SPEA2_results,SPEA2si_results,SPEA2si_DivMax_conf1_results, SPEA2si_DivMax_conf2_results, SPEA2si_DivMax_conf3_results, names=algs, notch = FALSE)
titulo <-paste(indicator, "SPEA2", sep=":")
title(main=titulo)
}
par(mfrow=c(2,2), cex.lab=2.5, cex.axis=1.5)
indicator<-"HV"
SPEA2qIndicator(indicator)
indicator<-"IGD"
SPEA2qIndicator(indicator)
indicator<-"Epsilon"
SPEA2qIndicator(indicator)
indicator<-"Spread"
SPEA2qIndicator(indicator)
dev.off()
<file_sep>package reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial;
/*this class simplly implements mutation that favoring RE based on
* Normal distribution
*
*
*/
import jmetal.core.Solution;
import jmetal.core.SolutionType;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.wrapper.XReal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
import jmetal.operators.mutation.*;
import org.apache.commons.math3.distribution.NormalDistribution;
public class ModifiedPolynomialMutationFavorConventionalPP extends PolynomialMutation {
/**
* The array will keep track on which gene the mutation will be applied true
* means apply the mutation to increase and false means apply mutation to
* decrease and null means do nothing {Off-Shore wind, on-shore wind, Solar,
* PP, coal, oil, ngas}
*/
/*this was used for 1st paper
* private static Boolean favorGenes[] = new Boolean[] { false, false, false,
null, true, null, false };*/
private Boolean favorGenes[];
//private Double bitFlipMutationProbability_ = null;
private static final double ETA_M_DEFAULT_ = 20.0;
private final double eta_m_ = ETA_M_DEFAULT_;
private Double mutationProbability_ = null;
private Double distributionIndex_ = eta_m_;
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays
.asList(RealSolutionType.class);
/**
* Constructor Creates a new instance of the Bit Flip mutation operator
*/
public ModifiedPolynomialMutationFavorConventionalPP(
HashMap<String, Object> parameters, Boolean favorGenes[]) {
super(parameters);
/*
* if (parameters.get("bitFlipMutationProbability") != null)
* bitFlipMutationProbability_ = (Double) parameters
* .get("bitFlipMutationProbability");
*/
this.favorGenes = favorGenes;
if (parameters.get("probability") != null)
mutationProbability_ = (Double) parameters.get("probability") ;
if (parameters.get("distributionIndex") != null)
distributionIndex_ = (Double) parameters.get("distributionIndex") ;
}
public static void main(String args[]) {
NormalDistribution nd = new NormalDistribution(0, 1);
System.out.println(nd.density(0.2));
}
/**
* Perform the mutation operation
*
* @param probability
* Mutation probability
* @param solution
* The solution to mutate
* @throws JMException
*/
public void doMutation(double probability, Solution solution)
throws JMException {
double rnd, deltaU, deltaL, mut_pow, deltaq;
double y, yl, yu, val, xy;
XReal x = new XReal(solution);
try {
if (solution.getType().getClass() == RealSolutionType.class) {
for (int i = 0; i < solution.getDecisionVariables().length; i++) {
// do mutation on all variables
// check if the probability is greater than a given
// probability
if (PseudoRandom.randDouble() < probability) {
y = x.getValue(i);
yl = x.getLowerBound(i);
yu = x.getUpperBound(i);
deltaL = (y - yl) / (yu - yl);
deltaU = (yu - y) / (yu - yl);
rnd = PseudoRandom.randDouble();
mut_pow = 1.0 / (distributionIndex_ + 1.0);
try {
if (favorGenes[i] == true) {
/*
* double indvValue = solution
* .getDecisionVariables()[i].getValue(); double
* newIndvValue = indvValue;
*
* double distLowerBound = indvValue; double
* distUpperBound = solution
* .getDecisionVariables()[i] .getUpperBound();
* if ((distUpperBound - indvValue) > 0.0) {
*
* NormalDistribution nd = new
* NormalDistribution( indvValue,
* (distUpperBound - indvValue) / 3);
*
* double rand = PseudoRandom.randDouble();
*
* newIndvValue = nd
* .inverseCumulativeProbability(nd
* .cumulativeProbability(distLowerBound) + rand
* (nd.cumulativeProbability(distUpperBound) -
* nd .cumulativeProbability(distLowerBound)));
* } solution.getDecisionVariables()[i]
* .setValue(newIndvValue);
*/
xy = 1.0 - deltaU;
val = 1
- rnd
+ rnd
* (Math.pow(xy,
(distributionIndex_ + 1.0)));
deltaq = 1 - java.lang.Math.pow(val, mut_pow);
y = y + deltaq * (yu - yl);
if (y < yl)
y = yl;
if (y > yu)
y = yu;
x.setValue(i, y);
}
else {
/*
* double indvValue = solution
* .getDecisionVariables()[i].getValue();
*
* double newIndvValue = indvValue;
*
* double distLowerBound = solution
* .getDecisionVariables()[i] .getLowerBound();
* double distUpperBound = indvValue; if
* ((indvValue - distLowerBound) > 0) {
* NormalDistribution nd = new
* NormalDistribution( indvValue, (indvValue -
* distLowerBound) / 3);
*
* double rand = PseudoRandom.randDouble();
*
* newIndvValue = nd
* .inverseCumulativeProbability(nd
* .cumulativeProbability(distLowerBound) + rand
* (nd.cumulativeProbability(distUpperBound) -
* nd .cumulativeProbability(distLowerBound)));
* } solution.getDecisionVariables()[i]
* .setValue(newIndvValue);
*/
xy = 1.0 - deltaL;
val = rnd
+ (1 - rnd)
* (Math.pow(xy,
(distributionIndex_ + 1.0)));
deltaq = java.lang.Math.pow(val, mut_pow) - 1;
y = y + deltaq * (yu - yl);
if (y < yl)
y = yl;
if (y > yu)
y = yu;
x.setValue(i, y);
}
} catch (NullPointerException e) {
continue;
}
} // if
}
}// else
} catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: "
+ "ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation
/**
* Executes the operation
*
* @param object
* An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_
.severe("BitFlipMutation.execute: the solution "
+ "is not of the right type. The type should be 'Binary', "
+ "'BinaryReal ' or 'Int', but "
+ solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation(mutationProbability_, solution);
return solution;
} // execute
}<file_sep>#This is a R file that generate a boxplot for six different problem for NSGA-II.
#There are 6 rows and three columns. Each row presents a problem and 1st column present stop generation, 2nd column presents HVd and third column presents epsd.
#Someone needs to select appropriate path to work with.
postscript("ALL_NSGAII.eps", horizontal=FALSE, onefile=FALSE, height=11, width=7, pointsize=10)
#pdf("All_NSGAII.pdf", width=7, height=11,pointsize=10)
#resultDirectory<-"C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC"
#path to NSGA-II result directory
resultDirectory<-"C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC"
#default number of generations for each problem
returnStdStGen <- function(problem)
{
if(problem =="ZDT1")
return (200)
else if(problem =="ZDT2")
return (200)
else if(problem =="ZDT3")
return (200)
else if(problem =="ZDT4")
return (200)
else if(problem =="DTLZ2")
return (300)
else if(problem =="DTLZ5")
return (200)
}
funStPlot <- function(problem)
{
#stGenHVdNew is the file that contains stopping generations for 30 runs when AHD+Div is used
StgenHVD<-paste(resultDirectory, problem, sep="/")
StgenHVD<-paste(StgenHVD, "StGenHVDNew", sep="/")
StgenHVD<-scan(StgenHVD)
#stGenAHDNew is the file that contains stopping generations for 30 runs when only AHD is used
StgenAHD<-paste(resultDirectory, problem, sep="/")
StgenAHD<-paste(StgenAHD, "StGenAHDNew", sep="/")
StgenAHD<-scan(StgenAHD)
#stGenDVNew is the file that contains stopping generations for 30 runs when only Div is used
StgenDV<-paste(resultDirectory, problem, sep="/")
StgenDV<-paste(StgenDV, "StGenDVNew", sep="/")
StgenDV<-scan(StgenDV)
#stopOCD is the file that contains stopping generations for 30 runs when OCD is used
StgenOCD<-paste(resultDirectory, problem, sep="/")
StgenOCD<-paste(StgenOCD, "StopOCD", sep="/")
StgenOCD<-scan(StgenOCD)
ind<-c("AHD+Div", "AHD", "Div", "OCD" )
line<-returnStdStGen(problem)
if(problem =="DTLZ2"){
#ylin provided the ylimit of boxplt
#for "DTLX2 it is necessary because ylimit is too low to get a horizontal line at default number of generation
boxplot(StgenHVD,StgenAHD,StgenDV,StgenOCD ,names=ind, notch = FALSE, outline=FALSE, ylim=c(0,310))
}
else{
boxplot(StgenHVD,StgenAHD,StgenDV,StgenOCD ,names=ind, notch = FALSE, outline=FALSE)
}
#boxplot(StgenHVD,StgenAHD,StgenDV,names=ind, notch = FALSE, outline=FALSE, ylim=c(0,line)
abline(h=line)
titulo <-paste(problem, "StopGen", sep=":")
title(font.main = 1, main=titulo)
}
funHVDPlot <- function(problem)
{
#HVDNew is the file that contains HVd for 30 runs when AHD+Div is used
HVD<-paste(resultDirectory, problem, sep="/")
HVD<-paste(HVD, "HVDNew", sep="/")
HVD<-scan(HVD)
#HVDAHDNew is the file that contains HVd for 30 runs when AHD is used
HVDAHD<-paste(resultDirectory, problem, sep="/")
HVDAHD<-paste(HVDAHD, "HVDAHDNew", sep="/")
HVDAHD<-scan(HVDAHD)
#HVDDVNew is the file that contains HVd for 30 runs when Div is used
HVDDV<-paste(resultDirectory, problem, sep="/")
HVDDV<-paste(HVDDV, "HVDDVNew", sep="/")
HVDDV<-scan(HVDDV)
#HVDOCD is the file that contains HVd for 30 runs when OCD is used
HVDOCD<-paste(resultDirectory, problem, sep="/")
HVDOCD<-paste(HVDOCD, "HVDOCD", sep="/")
HVDOCD<-scan(HVDOCD)
#ind<-c(expression('HVD'[all]), expression('HVD'[AHD]), expression('HVD'[DV]) )
ind<-c("AHD+Div", "AHD", "Div", "OCD" )
boxplot(HVD,HVDAHD,HVDDV,HVDOCD, names=ind, notch = FALSE, outline=FALSE)
abline(h=0.0)
#titulo<-paste(problem, expression('HV'[d]), sep=":")
title( main=substitute(problem*':HV'[d], list(problem = problem)))
}
funEpsDPlot <- function(problem)
{
#EpsDNew is the file that contains epsd for 30 runs when AHD+Div is used
EpsD<-paste(resultDirectory, problem, sep="/")
EpsD<-paste(EpsD, "EpsDNew", sep="/")
EpsD<-scan(EpsD)
#EpsDAHDNew is the file that contains epsd for 30 runs when AHD is used
EpsAHD<-paste(resultDirectory, problem, sep="/")
EpsAHD<-paste(EpsAHD, "EpsDAHDNew", sep="/")
EpsAHD<-scan(EpsAHD)
#EpsDDVNew is the file that contains epsd for 30 runs when Div is used
EpsDDV<-paste(resultDirectory, problem, sep="/")
EpsDDV<-paste(EpsDDV, "EpsDDVNew", sep="/")
EpsDDV<-scan(EpsDDV)
#EpsDOCD is the file that contains epsd for 30 runs when OCD is used
EpsDOCD<-paste(resultDirectory, problem, sep="/")
EpsDOCD<-paste(EpsDOCD, "EpsDOCD", sep="/")
EpsDOCD<-scan(EpsDOCD)
#ind<-c(expression('EpsD'[all]), expression('EpsD'[AHD]), expression('EpsD'[DV]) )
ind<-c("AHD+Div", "AHD", "Div", "OCD" )
boxplot(EpsD,EpsAHD,EpsDDV,EpsDOCD, names=ind, notch = FALSE, outline=FALSE)
abline(h=0.0)
#titulo <-paste(problem,expression('HV'[D]), sep=":")
title( main=substitute(problem*':eps'[d], list(problem = problem)))
}
par(mfrow = c(6,3), mar=c(2, 2, 2, 2) + 0.1)
#par(mfrow=c(6,3))
prob1<-"ZDT1"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
prob1<-"ZDT2"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
prob1<-"ZDT3"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
prob1<-"ZDT4"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
prob1<-"DTLZ2"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
prob1<-"DTLZ5"
funStPlot(prob1)
funHVDPlot(prob1)
funEpsDPlot(prob1)
dev.off()<file_sep>#this scipt is used to generate a boxplot with four indicator (hypervolume, IGD, Epsilon, spead)
#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
#pdf("combined_comparison.pdf", onefile=FALSE, width=8.5, height = 6)
jpeg(filename = "comNSGAII_SIandSPEA2_SI.jpeg", width = 8.5, height = 6.0, units = "in", pointsize = 10, res = 1000)
NSGAIIresultDirectory<-"."
SPEA2resultDirectory<-"."
NSGAIIqIndicator <- function(indicator)
{
fileNSGAIIsi<-paste(NSGAIIresultDirectory, "NSGAIIWithoutTrackWithSI", sep="/")
fileNSGAIIsi<-paste(fileNSGAIIsi, indicator, sep="/")
NSGAIIsi_results<-scan(fileNSGAIIsi)
fileSPEA2si<-paste(SPEA2resultDirectory, "SPEA2WithoutTrackWithSI", sep="/")
fileSPEA2si<-paste(fileSPEA2si, indicator, sep="/")
SPEA2si_results<-scan(fileSPEA2si)
algs<-c("NSGAII_SI","SPEA2_SI")
boxplot(NSGAIIsi_results,SPEA2si_results,names=algs, notch = FALSE)
titulo <-paste(indicator)
title(main=titulo)
}
par(mfrow=c(2,4))
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
dev.off()
<file_sep>This is the results (FUN and VAR) of 30 different runs with integrated SPEA2(Smart initialization + DK mutataion + Stopping criteria).
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
ArchiveSize: 100
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 10
Algorithm: SPEA2ForDKandSCandSI (reet.fbk.eu.jmetal.metaheuristics.spea2)
selection: Binary Tournament 2.
Domain-knowledge (same used for Smart Initialization and DKMutataion):
Boolean favorGenesforRE[] = { true, true, true, true, true };
Boolean favorGenesforConventionalPP[] = { false, false, false,false, false };
long seed[]={
116023,
122077,
148412,
229494,
234118,
250755,
289773,
315371,
366586,
386609,
403236,
529557,
542538,
544241,
625137,
629633,
630311,
668240,
686408,
701282,
710450,
736124,
758115,
811191,
861135,
889553,
922683,
929630,
943600,
983919
};
Parameters for Stopping criteria:
nGenLT = 20
noGenUnCh = 5;
significanceValue = 0.05;
initial population read from 'C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\InitIndividualWithSI\WithoutRM' folder. These population are generated without random individuals.
Output:
FUN*: Fun files for different run
VAR*: var files for diferent run
StoppingGen: stopping generation fr different run
mergeFUN_SInt_WRM: merge all Pareto-front for 30 runs with SPEA2 Integrated/combined approach<file_sep>// BitFlipMutation.java
//
// Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
// Copyright (c) 2011 <NAME>, <NAME>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package reet.fbk.eu.jmetal.operators.mutation.RE;
import jmetal.core.Solution;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.encodings.variable.Real;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.wrapper.XReal;
import jmetal.operators.mutation.Mutation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
/**
* This class implements a bit flip mutation operator.
* NOTE: the operator is applied to binary or integer solutions, considering the
* whole solution as a single encodings.variable.
*/
public class BitFlipAndPolynomialMutationForRes extends Mutation {
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays.asList( BinaryIntAndRealSolutionType.class) ;
private static final double ETA_M_DEFAULT_ = 20.0;
private final double eta_m_=ETA_M_DEFAULT_;
private double distributionIndex_ = eta_m_;
private Double bitFlipMutationProbability_ = null ;
private Double polynomialMutationProbability_ = null;
private BitFlipMutationForRes bitFlipMutation;
/**
* Constructor
* Creates a new instance of the Bit Flip mutation operator
*/
public BitFlipAndPolynomialMutationForRes(HashMap<String, Object> parameters) {
super(parameters) ;
if (parameters.get("bitFlipMutationProbability") != null)
bitFlipMutationProbability_ = (Double) parameters.get("bitFlipMutationProbability") ;
if (parameters.get("polynomialMutationProbability") != null)
polynomialMutationProbability_ = (Double) parameters.get("polynomialMutationProbability") ;
if (parameters.get("distributionIndex") != null)
distributionIndex_ = (Double) parameters.get("distributionIndex") ;
bitFlipMutation = new BitFlipMutationForRes(parameters);
} // BitFlipMutation
void doPolynomialMutation(double probability, Solution solution) throws JMException{
double rnd, delta1, delta2, mut_pow, deltaq;
double y, yl, yu, val, xy;
//XReal x = new XReal(solution) ;
// Polynomial mutation applied to the array real
for (int var=0; var < solution.getDecisionVariables().length; var++) {
if(solution.getDecisionVariables()[var].getClass() == Real.class){
if (PseudoRandom.randDouble() <= polynomialMutationProbability_) {
y = solution.getDecisionVariables()[var].getValue();
yl = solution.getDecisionVariables()[var].getLowerBound();
yu = solution.getDecisionVariables()[var].getUpperBound();
delta1 = (y-yl)/(yu-yl);
delta2 = (yu-y)/(yu-yl);
rnd = PseudoRandom.randDouble();
mut_pow = 1.0/(eta_m_+1.0);
if (rnd <= 0.5)
{
xy = 1.0-delta1;
val = 2.0*rnd+(1.0-2.0*rnd)*(Math.pow(xy,(distributionIndex_+1.0)));
deltaq = java.lang.Math.pow(val,mut_pow) - 1.0;
}
else
{
xy = 1.0-delta2;
val = 2.0*(1.0-rnd)+2.0*(rnd-0.5)*(java.lang.Math.pow(xy,(distributionIndex_+1.0)));
deltaq = 1.0 - (java.lang.Math.pow(val,mut_pow));
}
y = y + deltaq*(yu-yl);
if (y<yl)
y = yl;
if (y>yu)
y = yu;
//x.setValue(var, y);
solution.getDecisionVariables()[var].setValue(y);
} // if
}
} // for
}
/**
* Perform the mutation operation
* @param probability Mutation probability
* @param solution The solution to mutate
* @throws JMException
*/
public void doMutation( Solution solution) throws JMException {
try {
//do general bit flip mutation
bitFlipMutation.doMutation(bitFlipMutationProbability_, solution);
//do polynomial mutation
doPolynomialMutation(polynomialMutationProbability_,solution);
} // if
catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: " +
"ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation
/**
* Executes the operation
* @param object An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_.severe("BitFlipMutation.execute: the solution " +
"is not of the right type. The type should be 'Binary', " +
"'BinaryReal' or 'Int', but " + solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation( solution);
return solution;
} // execute
} // BitFlipMutation
<file_sep>package reet.fbk.eu.jmetal.initialization.AnalysisResults;
import java.io.FilenameFilter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import reet.fbk.eu.OptimizeEnergyPLANWithAccuracy.problem.EnergyPLANProblemStep1;
import reet.fbk.eu.jmetal.initialization.EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import jmetal.qualityIndicator.*;
public class CalculateAllQualityIndicatorValues {
SolutionSet trueParetoFront_;
double trueParetoFrontHypervolume_;
Problem problem_;
jmetal.qualityIndicator.util.MetricsUtil utilities_;
int noOfFiles;
File fs[];
File fileHV, fileGD, fileIGD, fileSpread, fileEpsilon, fileGenSpread;
FileWriter fwHV, fwGD, fwIGD, fwSpread, fwEpsilon, fwGenSpread;;
BufferedWriter bwHV, bwGD, bwIGD, bwSpread, bwEpsilon, bwGenSpread;;
/**
* Constructor
*
* @param problem
* The problem
* @param paretoFrontFile
* Pareto front file
*/
public CalculateAllQualityIndicatorValues(Problem problem,
String folderName, String paretoFrontFile) {
problem_ = problem;
utilities_ = new jmetal.qualityIndicator.util.MetricsUtil();
trueParetoFront_ = utilities_
.readNonDominatedSolutionSet(paretoFrontFile);
fs = new File(folderName).listFiles(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.startsWith("FUN");
}
});
noOfFiles = fs.length;
fileHV = new File(folderName+"\\HV");
fileGD = new File(folderName+"\\GD");
fileIGD = new File(folderName+"\\IGD");
fileSpread = new File(folderName+"\\Spread");
fileEpsilon = new File(folderName+"\\Epsilon");
fileGenSpread = new File(folderName+"\\GenSpread");
try {
if (!fileHV.exists()) {
fileHV.createNewFile();
fileGD.createNewFile();
fileIGD.createNewFile();
fileSpread.createNewFile();
fileEpsilon.createNewFile();
fileGenSpread.createNewFile();
}
fwHV = new FileWriter(fileHV.getAbsoluteFile());
fwGD = new FileWriter(fileGD.getAbsoluteFile());
fwIGD = new FileWriter(fileIGD.getAbsoluteFile());
fwSpread = new FileWriter(fileSpread.getAbsoluteFile());
fwEpsilon = new FileWriter(fileEpsilon.getAbsoluteFile());
fwGenSpread = new FileWriter(fileGenSpread.getAbsoluteFile());
bwHV = new BufferedWriter(fwHV);
bwGD = new BufferedWriter(fwGD);
bwIGD = new BufferedWriter(fwIGD);
bwSpread = new BufferedWriter(fwSpread);
bwEpsilon = new BufferedWriter(fwEpsilon);
bwGenSpread = new BufferedWriter(fwGenSpread);
} catch (IOException e) {
e.printStackTrace();
}
} // Constructor
public void doCalcutation() throws IOException {
double HV, IGD, GD, Spread, Epsilon, GS;
for (int i = 0; i < noOfFiles; i++) {
SolutionSet solutionParetoFront = utilities_
.readNonDominatedSolutionSet(fs[i].getPath());
System.out.println(i + " " + fs[i].getName());
HV=new Hypervolume().hypervolume(
solutionParetoFront.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("HyperVolume: "+HV);
bwHV.write(HV + "\n");
IGD=new InvertedGenerationalDistance()
.invertedGenerationalDistance(solutionParetoFront
.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("InvertedGenerationalDistance: "
+ IGD);
bwIGD.write(IGD+"\n");
GD=new GenerationalDistance().generationalDistance(
solutionParetoFront.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("GenerationalDistance: "+GD);
bwGD.write(GD+"\n");
Spread = new Spread().spread(
solutionParetoFront.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("Spread: "+Spread);
bwSpread.write(Spread+"\n");
Epsilon = new Epsilon().epsilon(
solutionParetoFront.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("Epsilon: "+Epsilon);
bwEpsilon.write(Epsilon+"\n");
GS=new GeneralizedSpread().generalizedSpread(
solutionParetoFront.writeObjectivesToMatrix(),
trueParetoFront_.writeObjectivesToMatrix(),
problem_.getNumberOfObjectives());
System.out.println("Generalized Spread: "+GS);
bwGenSpread.write(GS+"\n");
System.out.println();
}
bwHV.close();
bwIGD.close();
bwGD.close();
bwEpsilon.close();
bwSpread.close();
bwGenSpread.close();
}
/**
* @param args
* [0] absolute path of a folder that contain all the FUN files
* for different runs
* @param args
* [1] absolute path of the true Pareto front
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Problem problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
CalculateAllQualityIndicatorValues calqI = new CalculateAllQualityIndicatorValues(
problem, args[0], args[1]);
try {
calqI.doCalcutation();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>The 4 results are produced by NSGAIIForDK for Aalborg data.
There are 6 decision variable (CHP group 3, HP for group 3, PP, wind, offshore wind, PV).
There are two objectives (CO2 emssion and annual cost).
There are three constraints.
1. Maximumimport <=160
2. minimum grid stablization factor >=100
3. Annual heat balance <=0
NSGAIIForDK parameters:
population: 100
max evaluation: 10000
Crossover: SBXCrossover, probability: 0.9, distribution index: 10
Mutation: GeneralModifiedPolynomialMutationForRes, Probability: 1.0/problem.getNumberOfVariables(), distribution index: 10
selection: binary tournament
Domain Knowledge:
Boolean favorGenesforRE[] ={true, true, null, true, true, true, null};
Boolean favorGenesforConventionalPP[] ={false, false, null, false, false, false, null};
order: chp3, HP, PP, wind, offshore, PV, boiler
PP and boiler capacity is allocsted deterministically.
Number of runs: 4
<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with SPEA2 with domain-knowledge mutation.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: SPEA2
selection: Binary Tournament 2.
archiveSize: 100
long seed [] = {
126113,
148456,
154568,
212139,
274587,
289982,
368817,
387808,
418353,
430544,
434057,
447514,
458475,
467542,
471922,
500024,
585464,
596970,
622980,
632376,
686544,
712584,
784248,
808035,
833359,
879899,
888346,
953022,
975572,
983349
};
The seeds are same that is used in initilization experiment. It'll help to compare with typical SPEA2 as two algorithms starts from same initialized individuals.
mergeFUN_SDK: merge all 30 runs for SPEA2 with DK mutation
N.B.: These results are reported in ASOC paper<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII with smart initilization for building true Pareto front.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution (modified to work without PP and boiler capacity, now, the number of decision variable is 5. The file will be found in initilization folder)
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm:NSGAIIForSI
selection: Binary Tournament 2.
long seed [] = {343434, 551254, 145845, 555541, 551641,625882,985312,458745, 228424, 7811554 };
//2nd seed for NSGAII (run # 11 to run # 20)
long seed [] = {
251843,
351008,
427848,
434479,
607483,
618448,
685039,
764699,
765255,
915076
};
//3rd seed for NSGAII (run # 21 to run # 30)
long seed [] = {
198045,
210901,
447778,
613516,
619821,
702847,
741577,
747201,
789666,
830237
};
read initial population from "C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\InitIndividualWithSI" folder
mergeFUN_NSI: all Pareto front from 30 runs with NSGAII with smart inililization<file_sep>package reet.fbk.eu.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public class ExtrectParetoFrontAndDecisionVariables {
String FUNFileName_;
String VARFileName_;
int dimensions_;
int numberOfDecisionVariables_;
List<Point> points_ = new LinkedList<Point>();
private class Point {
double[] vector_;
double[] decisionVector_;
public Point(double[] vector, double[] decisionVector) {
vector_ = vector;
decisionVector_ = decisionVector;
}
/*
* public Point (int size) { vector_ = new double[size]; for (int i = 0;
* i < size; i++) vector_[i] = 0.0f; }
*/
}
/**
* @author <NAME> Creates a new instance
* @param name
* : the name of the file
*/
public ExtrectParetoFrontAndDecisionVariables(String FUNFileName,
String VARFileName, int dimensions, int numberOfDecisionVariables) {
FUNFileName_ = FUNFileName;
VARFileName_ = VARFileName;
dimensions_ = dimensions;
numberOfDecisionVariables_ = numberOfDecisionVariables;
loadInstance();
} // ReadInstance
/**
* Read the points instance from file
*/
public void loadInstance() {
try {
// read the objetives values
File archivo = new File(FUNFileName_);
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(archivo);
br = new BufferedReader(fr);
// read the corresponding decision variable
File dcFile = new File(VARFileName_);
FileReader dcfr = null;
BufferedReader dcbr = null;
dcfr = new FileReader(dcFile);
dcbr = new BufferedReader(dcfr);
// File reading
String line;
int lineCnt = 0;
line = br.readLine(); // reading the first line (special case)
String lineDecicionVarible = dcbr.readLine();
while (line != null) {
double objectiveValues[] = new double[dimensions_];
double decisionVariables[] = new double[numberOfDecisionVariables_];
StringTokenizer stobj = new StringTokenizer(line);
StringTokenizer stdec = new StringTokenizer(lineDecicionVarible);
try {
for (int i = 0; i < dimensions_; i++) {
objectiveValues[i] = new Double(stobj.nextToken());
}
for (int i = 0; i < numberOfDecisionVariables_; i++) {
decisionVariables[i] = new Double(stdec.nextToken());
}
Point auxPoint = new Point(objectiveValues,
decisionVariables);
add(auxPoint);
line = br.readLine();
lineDecicionVarible = dcbr.readLine();
lineCnt++;
} catch (NumberFormatException e) {
System.err.println("Number in a wrong format in line "
+ lineCnt);
System.err.println(line);
line = br.readLine();
lineCnt++;
} catch (NoSuchElementException e2) {
System.err.println("Line " + lineCnt
+ " does not have the right number of objectives");
System.err.println(line);
line = br.readLine();
lineCnt++;
}
}
br.close();
dcbr.close();
} catch (FileNotFoundException e3) {
System.err.println("The file " + FUNFileName_ + " or " + VARFileName_
+ " has not been found in your file system");
} catch (IOException e3) {
System.err.println("The file " + FUNFileName_
+ " has not been found in your file system");
}
} // loadInstance
public void add(Point point) {
Iterator<Point> iterator = points_.iterator();
while (iterator.hasNext()) {
Point auxPoint = iterator.next();
int flag = compare(point, auxPoint);
if (flag == -1) { // A solution in the list is dominated by the new
// one
iterator.remove();
} else if (flag == 1) { // The solution is dominated
return;
}
} // while
points_.add(point);
} // add
public int compare(Point one, Point two) {
int flag1 = 0, flag2 = 0;
for (int i = 0; i < dimensions_; i++) {
if (one.vector_[i] < two.vector_[i])
flag1 = 1;
if (one.vector_[i] > two.vector_[i])
flag2 = 1;
}
if (flag1 > flag2) // one dominates
return -1;
if (flag2 > flag1) // two dominates
return 1;
return 0; // both are non dominated
}
public void writeParetoFront() {
try {
/* Open the objective output file */
FileOutputStream fosObj = new FileOutputStream(FUNFileName_ + ".pf");
OutputStreamWriter oswObj = new OutputStreamWriter(fosObj);
BufferedWriter bwObj = new BufferedWriter(oswObj);
/* Open the decision variables output file */
FileOutputStream fosDC = new FileOutputStream(VARFileName_ + ".pf");
OutputStreamWriter oswDC = new OutputStreamWriter(fosDC);
BufferedWriter bwDC = new BufferedWriter(oswDC);
for (Point auxPoint : points_) {
String auxObj = "";
String auxDC = "";
for (int i = 0; i < auxPoint.vector_.length; i++) {
auxObj += auxPoint.vector_[i] + " ";
}
bwObj.write(auxObj);
bwObj.newLine();
for (int i = 0; i < auxPoint.decisionVector_.length; i++) {
auxDC += auxPoint.decisionVector_[i] + " ";
}
bwDC.write(auxDC);
bwDC.newLine();
}
/* Close the file */
bwObj.close();
bwDC.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("Wrong number of arguments: ");
System.out
.println("Sintex: java ExtractParetoFront <FUNfile> <VARfile> <dimensions> <numberOfDecicionVariables>");
System.out
.println("\t<FUNfile> is a file containing all objective values");
System.out
.println("\t<VARfile> is a file containing all corresponding decision variable values");
System.out
.println("\t<dimensions> represents the number of dimensions of the problem");
System.out
.println("\t<numberOfDecicionVariables> represents the number of decision varibales of the problem");
System.exit(-1);
}
ExtrectParetoFrontAndDecisionVariables epf = new ExtrectParetoFrontAndDecisionVariables(
args[0], args[1], new Integer(args[2]), new Integer(args[3]));
epf.writeParetoFront();
}
}
<file_sep>#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
#pdf("indicators_NSGAII_NSGAII_DKM.pdf", onefile=FALSE, width=10)
postscript("NSGAII_SPEA2_Int_test.eps", horizontal=FALSE, onefile=FALSE, height=6, width=8.5, pointsize=11)
NSGAIIresultDirectory<-"."
NSGAIIqIndicator <- function(indicator)
{
fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAII", sep="/")
#fileNSGAII<-paste(fileNSGAII,"With_mutation_pr_0.2", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
fileNSGAII<-paste(fileNSGAII, indicator, sep="/")
NSGAII_results<-scan(fileNSGAII)
fileNSGAII_Int<-paste(NSGAIIresultDirectory, "NSGAII_int", sep="/")
fileNSGAII_Int<-paste(fileNSGAII_Int, "WithoutRM", sep="/")
fileNSGAII_Int<-paste(fileNSGAII_Int, "With_mutation_pr_0.1", sep="/")
fileNSGAII_Int<-paste(fileNSGAII_Int, "Criteria1", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileNSGAII_Int<-paste(fileNSGAII_Int, indicator, sep="/")
NSGAII_Int_results<-scan(fileNSGAII_Int)
algs<-c("NSGAII","NSGAII_Int")
boxplot(NSGAII_results,NSGAII_Int_results,names=algs, notch = FALSE)
titulo <-indicator
title(main=titulo, cex.main=1.5)
}
SPEA2resultDirectory<-"."
SPEA2qIndicator <- function(indicator)
{
fileSPEA2<-paste(SPEA2resultDirectory, "SPEA2", sep="/")
#fileSPEA2<-paste(fileSPEA2, "With_mutation_pr_0.2", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
fileSPEA2<-paste(fileSPEA2, indicator, sep="/")
SPEA2_results<-scan(fileSPEA2)
fileSPEA2_Int<-paste(SPEA2resultDirectory, "SPEA2_Int", sep="/")
fileSPEA2_Int<-paste(fileSPEA2_Int, "WithoutRM", sep="/")
fileSPEA2_Int<-paste(fileSPEA2_Int, "With_mutation_pr_0.1", sep="/")
fileSPEA2_Int<-paste(fileSPEA2_Int, "Criteria1", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileSPEA2_Int<-paste(fileSPEA2_Int, indicator, sep="/")
SPEA2_Int_results<-scan(fileSPEA2_Int)
algs<-c("SPEA2","SPEA2_Int")
boxplot(SPEA2_results,SPEA2_Int_results,names=algs, notch = FALSE)
titulo <-indicator
title(main=titulo, cex.main=1.5)
}
#SPEA2resultDirectory<-"./MutationStudySPEA2/data/"
#SPEA2qIndicator <- function(indicator, problem)
#{
#filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
#PolynomialMutation<-scan(filePolynomialMutation)
#fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
#fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
#DKMutation<-scan(fileDKMutation)
#algs<-c("Polynomial","DKMutation")
#boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
#titulo <-paste(indicator, "SPEA2", sep=":")
#title(main=titulo)
#}
par(mfrow=c(2,4), cex.axis=1.0, cex.lab=2.0)
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
indicator<-"HV"
SPEA2qIndicator(indicator)
indicator<-"IGD"
SPEA2qIndicator(indicator)
indicator<-"Epsilon"
SPEA2qIndicator(indicator)
indicator<-"Spread"
SPEA2qIndicator(indicator)
#indicator<-"HV"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"IGD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"GD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"Epsilon"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
dev.off()
<file_sep>package reet.fbk.eu.jmetal.initialization;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.FileHandler;
import jmetal.core.Algorithm;
import jmetal.core.Operator;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import reet.fbk.eu.jmetal.initialization.metaheuristics.nsgaII.NSGAIIForSI;
import reet.fbk.eu.jmetal.initialization.metaheuristics.spea2.SPEA2ForSI;
import jmetal.operators.crossover.CrossoverFactory;
import jmetal.operators.selection.SelectionFactory;
import jmetal.qualityIndicator.QualityIndicator;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.RandomGenerator;
//import reet.fbk.eu.jmetal.operators.mutation.MutationFactory;
import jmetal.operators.mutation.MutationFactory;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* The class is main class where the class can execute algorithm from the command line
* argument. The class only run the algorithm with smart initialization technique.
*
*/
class NSGAII_SI_Run{
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
public void run(int populationSize, int maxEvaluations) throws SecurityException, IOException, JMException, ClassNotFoundException{
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
int numberOfRun=30;
//seed for NSGAII
//long seed [] = {343434, 551254, 145845, 555541, 551641,625882,985312,458745, 228424, 7811554 };
//2nd seed for NSGAII
/*long seed [] = {
251843,
351008,
427848,
434479,
607483,
618448,
685039,
764699,
765255,
915076
};*/
//3rd seed for NSGAII
/* long seed [] = {
198045,
210901,
447778,
613516,
619821,
702847,
741577,
747201,
789666,
830237
};*/
long seed[] ={
145845,
198045,
210901,
228424,
251843,
343434,
351008,
427848,
434479,
447778,
458745,
551254,
551641,
555541,
607483,
613516,
618448,
619821,
625882,
685039,
702847,
741577,
747201,
764699,
765255,
789666,
830237,
915076,
985312,
7811554
};
/*File folder = new File("InitializationResults/InitIndividualWithSI");
File[] listOfFiles = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("Init");
}
});*/
File[] listOfFiles = new File[numberOfRun] ;
/*long initSeed[] = { 144759,
271439,
445964,
494817,
530563,
724859,
746153,
747584,
866309,
938562};*/
/*long initSeed[] = {
172480,
242648,
268602,
272313,
412455,
441996,
633160,
814562,
822805,
843288
};*/
long initSeed[]={
125742,
144759,
172480,
242648,
245454,
268602,
271439,
272313,
412455,
441996,
445964,
447551,
455411,
455885,
494817,
530563,
545454,
565656,
633160,
714451,
724859,
746153,
747584,
752453,
814562,
822805,
843288,
844545,
866309,
938562
};
for(int i=0;i<numberOfRun;i++){
listOfFiles[i] = new File("InitializationResults/InitIndividualWithSI/WithoutRM/InitIndv_seed_"+initSeed[i]);
}
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(seed[i]));
indicators = null;
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
//algorithm = new NSGAIITrackIndicators(problem, seed[i], "SBX_DKMutation");
Boolean favorGenesforRE[] ={true, true, true, true, true};
Boolean favorGenesforConventionalPP[] ={false, false, false, false, false};
parameters = new HashMap();
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForCon", favorGenesforConventionalPP);
parameters.put("InitialPopulationFile", listOfFiles[i].getAbsolutePath());
algorithm = new NSGAIIForSI(problem, parameters);
// Algorithm parameters
algorithm.setInputParameter("populationSize", populationSize);
algorithm.setInputParameter("maxEvaluations", maxEvaluations);
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover",
parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation",
parameters);
//mutation = MutationFactory.getMutationOperator("GeneralRealMutationForRes",
//. parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator("BinaryTournament2",
parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile("InitializationResults\\NSGAIIWithoutTrackWithSI\\VAR_Init_"+listOfFiles[i].getName().substring(14)+"_seed_"+seed[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile("InitializationResults\\NSGAIIWithoutTrackWithSI\\FUN_Init_"+listOfFiles[i].getName().substring(14)+"_seed_"+seed[i]);
}
}
}
class SPEA2_SI_Run{
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
public void run(int populationSize, int maxEvaluations) throws SecurityException, IOException, JMException, ClassNotFoundException{
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
//seed for spea2
//long seed [] = {857578, 647647, 647848, 891747, 957363, 538947, 425374, 637384, 125386, 243858 };
//2nd seed for spea2
/*long seed [] = {
145295,
378578,
384873,
437331,
461628,
544774,
631545,
712308,
733779,
878532
};*/
//3rd seed for spea2
/* long seed [] = {
158570,
207621,
227297,
354528,
356090,
764889,
866208,
867882,
917083,
919749
};*/
int numberOfRun=30;
long seed[]={
125386,
145295,
158570,
207621,
227297,
243858,
354528,
356090,
378578,
384873,
425374,
437331,
461628,
538947,
544774,
631545,
637384,
647647,
647848,
712308,
733779,
764889,
857578,
866208,
867882,
878532,
891747,
917083,
919749,
957363
};
/*File folder = new File("InitializationResults/InitIndividualWithSI");
File[] listOfFiles = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("Init");
}
});*/
File[] listOfFiles = new File[numberOfRun] ;
/*long initSeed[] = { 144759,
271439,
445964,
494817,
530563,
724859,
746153,
747584,
866309,
938562};
*/
/*long initSeed[] = {
172480,
242648,
268602,
272313,
412455,
441996,
633160,
814562,
822805,
843288
};*/
long initSeed[]={
125742,
144759,
172480,
242648,
245454,
268602,
271439,
272313,
412455,
441996,
445964,
447551,
455411,
455885,
494817,
530563,
545454,
565656,
633160,
714451,
724859,
746153,
747584,
752453,
814562,
822805,
843288,
844545,
866309,
938562
};
for(int i=0;i<numberOfRun;i++){
listOfFiles[i] = new File("InitializationResults/InitIndividualWithSI/WithoutRM/InitIndv_seed_"+initSeed[i]);
}
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(seed[i]));
indicators = null;
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
//algorithm = new NSGAIITrackIndicators(problem, seed[i], "SBX_DKMutation");
Boolean favorGenesforRE[] ={true, true, true, true, true};
Boolean favorGenesforConventionalPP[] ={false, false, false, false, false};
parameters = new HashMap();
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForCon", favorGenesforConventionalPP);
parameters.put("InitialPopulationFile", listOfFiles[i].getAbsolutePath());
algorithm = new SPEA2ForSI(problem, parameters);
// algorithm = new ssNSGAII(problem);
//indicators = new QualityIndicator(problem, "C:\\Users\\Nusrat\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\Results\\truePf\\mergefun.pf") ;
// Algorithm parameters
algorithm.setInputParameter("populationSize", populationSize);
algorithm.setInputParameter("maxEvaluations", maxEvaluations);
//for spea2
algorithm.setInputParameter("archiveSize", populationSize);
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover",
parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation",
parameters);
//mutation = MutationFactory.getMutationOperator("GeneralRealMutationForRes",
//. parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator("BinaryTournament2",
parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile("InitializationResults\\SPEA2WithoutTrackWithSI\\VAR_Init_"+listOfFiles[i].getName().substring(14)+"_seed_"+seed[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile("InitializationResults\\SPEA2WithoutTrackWithSI\\FUN_Init_"+listOfFiles[i].getName().substring(14)+"_seed_"+seed[i]);
}
}
}
public class AalborgProblemWithSmartInitilizationMain {
public static void main(String[] args) throws JMException,
SecurityException, IOException, ClassNotFoundException {
if(args[0].equals("NSGAII_SI")){
NSGAII_SI_Run nsgaii_si = new NSGAII_SI_Run();
nsgaii_si.run(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}else if(args[0].equals("SPEA2_SI")){
SPEA2_SI_Run spea2_si = new SPEA2_SI_Run();
spea2_si.run(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}
}
}
<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with SPEA2 for building true Pareto front.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: SPEA2
selection: Binary Tournament 2.
archiveSize: 100
run# 1 to run# 10
long seed [] = {154568, 148456, 447514, 458475, 274587, 712584, 975572, 585464, 467542, 686544 };
2nd 10 runs with 10 new seeds (run # 11 to run # 20)
long seed [] = {
212139,
368817,
418353,
471922,
500024,
596970,
784248,
808035,
953022,
983349
};
//3rd seed for spea2 (run # 21 to run # 30)
long seed [] = {
126113,
289982,
387808,
430544,
434057,
622980,
632376,
833359,
879899,
888346
};
mergeFUN_S: all Pareto front from 30 runs with SPEA2
N.B: these results are reported in ASOC paper
<file_sep>package reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.crossover.RE;
//SinglePointCrossover.java
//
//Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
//Copyright (c) 2011 <NAME>, <NAME>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import jmetal.core.Solution;
import jmetal.core.SolutionType;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.encodings.variable.Real;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.wrapper.XReal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.encodings.variable.BinaryInt;
import jmetal.operators.crossover.*;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.crossover.SinglePointCrossover;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.crossover.DKRE.SinglePointCrossoverFavorMaximizationOfPP;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.crossover.DKRE.SinglePointCrossoverFavorMaximizationOfRes;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
/**
* This class allows to apply a Single Point crossover operator using two parent
* solutions.
*/
/*
* this class is the main class for the crossover. This class makes three
* different instance of crossover (single-point crossover, Single point
* crossover favor RE and Single point crossover favor PP) Accoring to the
* probability one of the above crossover will be called. 50 percencent of the
* times normal single point crossover will be called. Another 25% times
* favoring RE and favoring PP will be called.
*/
public class SinglePointAndSBXCrossoverForResWithDK extends Crossover {
private static final double EPS = 1.0e-14;
private static final double ETA_C_DEFAULT_ = 20.0;
private double distributionIndex_ = ETA_C_DEFAULT_;
private Double SBXCrossoverProbability_ = null;
private Double singlePointCrossoverProbability_ = null;
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays
.asList(BinaryIntAndRealSolutionType.class);
private GeneralSinglePointCrossoverForRes generalSinglePointCrossoverForRes;
/**
* Constructor Creates a new instance of the single point crossover operator
*/
public SinglePointAndSBXCrossoverForResWithDK(HashMap<String, Object> parameters) {
super(parameters);
generalSinglePointCrossoverForRes = new GeneralSinglePointCrossoverForRes(
parameters);
if (parameters.get("SBXCrossoverProbability") != null)
SBXCrossoverProbability_ = (Double) parameters
.get("SBXCrossoverProbability");
if (parameters.get("singlePointCrossoverProbability") != null)
singlePointCrossoverProbability_ = (Double) parameters
.get("singlePointCrossoverProbability");
} // SinglePointCrossover
/**
* Constructor Creates a new instance of the single point crossover operator
*/
// public SinglePointCrossover(Properties properties) {
// this();
// } // SinglePointCrossover
Solution[] doSBXCrossover(double realProbability, Solution parent1,
Solution parent2) throws JMException {
Solution[] offSpring = new Solution[2];
offSpring[0] = new Solution(parent1);
offSpring[1] = new Solution(parent2);
// SBX crossover
double rand;
double y1, y2, yL, yu;
double c1, c2;
double alpha, beta, betaq;
double valueX1, valueX2;
/*
* XReal x1 = new XReal(parent1); XReal x2 = new XReal(parent2); XReal
* offs1 = new XReal(offSpring[0]); XReal offs2 = new
* XReal(offSpring[1]);
*/
int numberOfVariables = parent1.getDecisionVariables().length;
if (PseudoRandom.randDouble() <= realProbability) {
for (int i = 0; i < numberOfVariables; i++) {
if (parent1.getDecisionVariables()[i].getClass() == Real.class) {
valueX1 = parent1.getDecisionVariables()[i].getValue();
valueX2 = parent2.getDecisionVariables()[i].getValue();
if (PseudoRandom.randDouble() <= 0.5) {
if (java.lang.Math.abs(valueX1 - valueX2) > EPS) {
if (valueX1 < valueX2) {
y1 = valueX1;
y2 = valueX2;
} else {
y1 = valueX2;
y2 = valueX1;
} // if
yL = parent1.getDecisionVariables()[i]
.getLowerBound();
yu = parent1.getDecisionVariables()[i]
.getUpperBound();
rand = PseudoRandom.randDouble();
beta = 1.0 + (2.0 * (y1 - yL) / (y2 - y1));
alpha = 2.0 - java.lang.Math.pow(beta,
-(distributionIndex_ + 1.0));
if (rand <= (1.0 / alpha)) {
betaq = java.lang.Math.pow((rand * alpha),
(1.0 / (distributionIndex_ + 1.0)));
} else {
betaq = java.lang.Math.pow((1.0 / (2.0 - rand
* alpha)),
(1.0 / (distributionIndex_ + 1.0)));
} // if
c1 = 0.5 * ((y1 + y2) - betaq * (y2 - y1));
beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1));
alpha = 2.0 - java.lang.Math.pow(beta,
-(distributionIndex_ + 1.0));
if (rand <= (1.0 / alpha)) {
betaq = java.lang.Math.pow((rand * alpha),
(1.0 / (distributionIndex_ + 1.0)));
} else {
betaq = java.lang.Math.pow((1.0 / (2.0 - rand
* alpha)),
(1.0 / (distributionIndex_ + 1.0)));
} // if
c2 = 0.5 * ((y1 + y2) + betaq * (y2 - y1));
if (c1 < yL)
c1 = yL;
if (c2 < yL)
c2 = yL;
if (c1 > yu)
c1 = yu;
if (c2 > yu)
c2 = yu;
if (PseudoRandom.randDouble() <= 0.5) {
// offs1.setValue(i, c2);
offSpring[0].getDecisionVariables()[i]
.setValue(c2);
// offs2.setValue(i, c1);
offSpring[1].getDecisionVariables()[i]
.setValue(c1);
} else {
// offs1.setValue(i, c1);
offSpring[0].getDecisionVariables()[i]
.setValue(c1);
// offs2.setValue(i, c2);
offSpring[1].getDecisionVariables()[i]
.setValue(c2);
} // if
} // if
else {
// offs1.setValue(i, valueX1);
offSpring[0].getDecisionVariables()[i]
.setValue(valueX1);
// offs2.setValue(i, valueX2);
offSpring[1].getDecisionVariables()[i]
.setValue(valueX2);
} // if
} // if
else {
// offs1.setValue(i, valueX2);
offSpring[0].getDecisionVariables()[i]
.setValue(valueX2);
// offs2.setValue(i, valueX1);
offSpring[1].getDecisionVariables()[i]
.setValue(valueX1);
} // else
} // for
} // if
}
return offSpring;
}
/**
* Perform the crossover operation.
*
* @param probability
* Crossover probability
* @param parent1
* The first parent
* @param parent2
* The second parent
* @return An array containig the two offsprings
* @throws JMException
*/
public Solution[] doCrossover( Solution parent1,
Solution parent2) throws JMException {
Solution[] offSpring;
// do generalized single-point crossover on parents
Solution[] binaryIntOffSpring;
binaryIntOffSpring = generalSinglePointCrossoverForRes.doCrossover(
singlePointCrossoverProbability_, parent1, parent2);
// do SBX crossover on real part on parents
offSpring = doSBXCrossover(SBXCrossoverProbability_,
binaryIntOffSpring[0], binaryIntOffSpring[1]);
return offSpring;
}// doCrossover
/**
* Executes the operation
*
* @param object
* An object containing an array of two solutions
* @return An object containing an array with the offSprings
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution[] parents = (Solution[]) object;
if (!(VALID_TYPES.contains(parents[0].getType().getClass()) && VALID_TYPES
.contains(parents[1].getType().getClass()))) {
Configuration.logger_
.severe("SinglePointCrossover.execute: the solutions "
+ "are not of the right type. The type should be 'Binary' or 'Int', but "
+ parents[0].getType() + " and "
+ parents[1].getType() + " are obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
if (parents.length < 2) {
Configuration.logger_
.severe("SinglePointCrossover.execute: operator "
+ "needs two parents");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
}
Solution[] offSpring;
// offSpring = doCrossover(crossoverProbability_, parents[0],
// parents[1]);
offSpring = doCrossover( parents[0], parents[1]);
// -> Update the offSpring solutions
for (int i = 0; i < offSpring.length; i++) {
offSpring[i].setCrowdingDistance(0.0);
offSpring[i].setRank(0);
}
return offSpring;
} // execute
} // SinglePointCrossover
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANVdN.problem;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.util.JMException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator;
import reet.fbk.eu.OptimizeEnergyPLANCIVIS.ParseFile.*;
import reet.fbk.eu.OptimizeEnergyPLANVdN.parseFile.EnergyPLANFileParseForVdN;
/*
* This is a problem file that is dealing with VdN (mainly introduction of electric cars)
*/
public class EnergyPLANProblemVdN2DWithH2VehicleModifiedCO2___ extends Problem {
MultiMap energyplanmMap;
/*
* VdN data
*/
//common data for all scenarios
//CO2 content related data
public static final double co2Coal=95.0; //unit: kg/GJ
public static final double co2Oil=74.0;
public static final double co2NGas = 56.7;
public static final int averageKMPerYearPerCar = 12900;
//public static final double maxH2DemandInDistribution = 1.0;
//public static final double sumH2DemandInDistribution = 2928.0;
//Demands: 2020
//transport
public static final int totalKMRunByCars = 250000000;
/*//2020 scenario: 2DS (for 4DS, we need to change additional prices)
// Heat
public static final double totalHeatDemand = 253.70; // in GWh
public static final double efficiencyConCar = 0.607; // KWh/km
public static final double efficiencyEVCar = 0.169; // KWh/km
public static final double efficiencyFCEVCar = 0.334; // KWh/km
public static final double efficiencyBiomassCHP = 0.66;
// H2
public static final double efficiencyElectrolyzerTrans = 0.74;
public static final double oilBoilerEfficiency = 0.85;
public static final double nGasBoilerEfficiency = 0.95;
public static final double biomassBoilerEfficiency = 0.80;
public static final double COP = 4.54;
//Fuel distribution related data
//2020 scenario
public static final double coalShare=14.0;
public static final double oilShare=5.6;
public static final double nGasShare=45.0;
// additional cost (2DS)
public static final double addtionalCostPerGWhinKEuro = 136.36;*/
//2030 scenario: 2DS (for 4DS, we need to change additional prices)
// Heat
public static final double totalHeatDemand = 249.84; // in GWh
//cars
public static final double efficiencyConCar = 0.549; // KWh/km
public static final double efficiencyEVCar = 0.145; // KWh/km
public static final double efficiencyFCEVCar = 0.267; // KWh/km
public static final double efficiencyBiomassCHP = 0.66;
// H2
public static final double efficiencyElectrolyzerTrans = 0.75;
public static final double oilBoilerEfficiency = 0.87;
public static final double nGasBoilerEfficiency = 0.97;
public static final double biomassBoilerEfficiency = 0.82;
public static final double COP = 5.07;
public static final double coalShare=10.4;
public static final double oilShare=4.1;
public static final double nGasShare=33.4;
// additional cost
public static final double addtionalCostPerGWhinKEuro = 144.33;
/*//2050 scenario: 2DS (for 4DS, we need to change additional prices)
// Heat
public static final double totalHeatDemand = 256.11; // in GWh
//cars
public static final double efficiencyConCar = 0.497; // KWh/km
public static final double efficiencyEVCar = 0.117; // KWh/km
public static final double efficiencyFCEVCar = 0.200; // KWh/km
public static final double efficiencyBiomassCHP = 0.66;
// H2
public static final double efficiencyElectrolyzerTrans = 0.78;
public static final double oilBoilerEfficiency = 0.89;
public static final double nGasBoilerEfficiency = 0.99;
public static final double biomassBoilerEfficiency = 0.84;
public static final double COP = 5.46;
public static final double coalShare=3.3;
public static final double oilShare=1.3;
public static final double nGasShare=10.5;
// additional cost
public static final double addtionalCostPerGWhinKEuro = 158.37;
*/
/**
* Creates a new instance of problem ZDT1.
*
* @param numberOfVariables
* Number of variables.
* @param solutionType
* The solution type must "Real", "BinaryReal, and "ArrayReal".
*/
public EnergyPLANProblemVdN2DWithH2VehicleModifiedCO2(String solutionType) {
numberOfVariables_ = 11;
numberOfObjectives_ = 2;
numberOfConstraints_ = 1;
problemName_ = "OptimizeEnergyPLANVdN";
upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];
// Establishes upper and lower limits for the variables
int var;
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// index - 5 -> electric car percentage
// index -6 -> solar thermal percentage in oil boiler
// index -7 -> solar thermal percentage in nGas boiler
// index -8 -> solar thermal percentage in biomass boiler
// index -9 -> solar thermal percentage in biomass CHP
// index -10 -> solar thermal percentage in HP
// PV upper and lower limit
lowerLimit_[0] = 936.0;
upperLimit_[0] = 40000.0;
// other are the percentage from limit [0,1]
for (var = 1; var < numberOfVariables_; var++) {
lowerLimit_[var] = 0.0;
upperLimit_[var] = 1.0;
} // for
if (solutionType.compareTo("Real") == 0)
solutionType_ = new RealSolutionType(this);
else {
System.out.println("Error: solution type " + solutionType
+ " invalid");
System.exit(-1);
}
} // constructor end
/**
* Evaluates a solution.
*
* @param solution
* The solution to evaluate.
* @throws JMException
*/
@SuppressWarnings("unchecked")
public void evaluate(Solution solution) throws JMException {
// PV
double pv = solution.getDecisionVariables()[0].getValue();
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// index - 5 -> electric car percentage
// index -6 -> solar thermal percentage in oil boiler
// index -7 -> solar thermal percentage in nGas boiler
// index -8 -> solar thermal percentage in biomass boiler
// index -9 -> solar thermal percentage in biomass CHP
// index -10 -> solar thermal percentage in HP
double heatPercentages[] = new double[4];
for (int i = 0; i < 4; i++) {
heatPercentages[i] = solution.getDecisionVariables()[i + 1]
.getValue();
}
Arrays.sort(heatPercentages);
for (int i = 1; i < 5; i++) {
solution.getDecisionVariables()[i].setValue(heatPercentages[i - 1]);
}
// oil-boiler percentage
double oilBoilerHeatPercentage = heatPercentages[0];
// Ngas-boiler heat percentage
double nGasBoilerHeatPercentage = heatPercentages[1]
- heatPercentages[0];
// biomass-boiler heat percentage
double biomassBoilerHeatPercentage = heatPercentages[2]
- heatPercentages[1];
// ngas chp heat percentage
double biomassCHPHeatPercentage = heatPercentages[3]
- heatPercentages[2];
// heat pump heat percentage
double hpHeatPercentage = 1.0 - heatPercentages[3];
// cars' percentages
double EVCarPercentage = solution.getDecisionVariables()[5].getValue();
double conCarPercentage = 1- EVCarPercentage;
double totalKMRunByConCar = (int) totalKMRunByCars * conCarPercentage;
double totalKMRunByEVCar = (int) totalKMRunByCars * EVCarPercentage;
//double totalKMRunByFCEVCar = (int) totalKMRunByCars * FCEVCarPercentage;
double totalDieselDemandInGWhForTrns = totalKMRunByConCar
* efficiencyConCar / Math.pow(10, 6);
double totalElecDemandInGWhForTrns = totalKMRunByEVCar
* efficiencyEVCar / Math.pow(10, 6);
//double totalH2DemandInGWhForTrns = totalKMRunByFCEVCar
//* efficiencyFCEVCar / Math.pow(10, 6);
// solar thermal percentage
double oilSolarPercentage = solution.getDecisionVariables()[6]
.getValue();
double nGasSolarPercentage = solution.getDecisionVariables()[7]
.getValue();
double biomassBoilerSolarPercentage = solution.getDecisionVariables()[8]
.getValue();
double biomassCHPSolarPercentage = solution.getDecisionVariables()[9]
.getValue();
double hpSolarPercentage = solution.getDecisionVariables()[10]
.getValue();
try{
writeIntoInputFile(pv, oilBoilerHeatPercentage,
nGasBoilerHeatPercentage, biomassBoilerHeatPercentage,
biomassCHPHeatPercentage, hpHeatPercentage,
totalDieselDemandInGWhForTrns, totalElecDemandInGWhForTrns,
/*totalH2DemandInGWhForTrns,*/ oilSolarPercentage,
nGasSolarPercentage, biomassBoilerSolarPercentage,
biomassCHPSolarPercentage, hpSolarPercentage);
}catch(IOException e){
System.out.print("Pobrlem writting in modified Input file");
}
String energyPLANrunCommand = ".\\EnergyPLAN_12.3\\EnergyPLAN.exe -i "
+ "\".\\modifiedInput.txt\" "
+ "-ascii \"result.txt\" ";
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParseForVdN epfp = new EnergyPLANFileParseForVdN(
".\\result.txt");
energyplanmMap = epfp.parseFile();
Iterator it;
Collection<String> col;
// objective # 1
col = (Collection<String>) energyplanmMap
.get("CO2-emission (total)");
it = col.iterator();
double localCO2emission = Double.parseDouble(it.next().toString());
//extract import
col = (Collection<String>) energyplanmMap
.get("AnnualImportElectr.");
it = col.iterator();
double elecImport = Double.parseDouble(it.next().toString());
double co2InImportedEleCoal =( (elecImport*coalShare/100.0) * co2Coal *3600.0 )/ 1000000.0; //1GWh = 3600 GJ
double co2InImportedEleOil =( (elecImport*oilShare/100.0) * co2Oil *3600.0 )/ 1000000.0; //1GWh = 3600 GJ
double co2InImportedEleNGas =( (elecImport*nGasShare/100.0) * co2NGas *3600.0 )/ 1000000.0; //1GWh = 3600 GJ
localCO2emission = localCO2emission + co2InImportedEleCoal + co2InImportedEleOil + co2InImportedEleNGas;
solution.setObjective(0,localCO2emission);
// objective # 2
col = (Collection<String>) energyplanmMap.get("Variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanmMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
col = (Collection<String>) energyplanmMap.get("AnnualHydroElectr.");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract anual PV production
col = (Collection<String>) energyplanmMap.get("AnnualPVElectr.");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
// extract annual import
col = (Collection<String>) energyplanmMap
.get("AnnualImportElectr.");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanmMap
.get("AnnualExportElectr.");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
// extract biomass CHP electricity production
col = (Collection<String>) energyplanmMap
.get("AnnualHH-CHPElectr.");
it = col.iterator();
double biomassCHPElecProduction = Double.parseDouble(it.next()
.toString());
// calculate additional cost
// (hydroProduction+PVproduction+Import-Export)*average additional
// cost (85.74)
double totalAdditionalCost = Math
.round((hydroPowerProduction + PVproduction + Import
- Export + biomassCHPElecProduction)
* addtionalCostPerGWhinKEuro);
// extract
col = (Collection<String>) energyplanmMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
double investmentCost = Double.parseDouble(invest);
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ investmentCost + totalAdditionalCost;
solution.setObjective(1, actualAnnualCost);
/*// 3rd objective
// Trasportation
col = (Collection<String>) energyplanmMap
.get("AnnualFlexibleElectr.");
it = col.iterator();
double transportElecDemand = Double.parseDouble(it.next()
.toString());
col = (Collection<String>) energyplanmMap
.get("AnnualElectr.Demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
// Individual house HP electric demand
col = (Collection<String>) energyplanmMap.get("AnnualHH-HPElectr.");
it = col.iterator();
double annualHPdemand = Double.parseDouble(it.next().toString());
solution.setObjective(2, (Import + Export)
/ (annualElecDemand + transportElecDemand + annualHPdemand));*/
/*col = (Collection<String>) energyplanmMap.get("Ngas Consumption");
it = col.iterator();
double nGasConsumption = Double.parseDouble(it.next().toString());
// extract oil consumption
col = (Collection<String>) energyplanmMap.get("Oil Consumption");
it = col.iterator();
double oilConsumption = Double.parseDouble(it.next().toString());
// extract biomass consupmtion
col = (Collection<String>) energyplanmMap
.get("Biomass Consumption");
it = col.iterator();
double BiomassConsumption = Double
.parseDouble(it.next().toString());
// extract solar thermal heat
col = (Collection<String>) energyplanmMap.get("AnnualHH SolarHeat");
it = col.iterator();
double solaThermal = Double.parseDouble(it.next().toString());
double PVPEF = 1.0;
double HYPEF = 1.0;
double BiomassPEF = 1 / 0.17;
double PEFImport = 2.17;
double totalPEForElecrcity = PVproduction * PVPEF
+ hydroPowerProduction * HYPEF + biomassCHPElecProduction
* BiomassPEF;
double totalLocalElecProduction = PVproduction
+ hydroPowerProduction + biomassCHPElecProduction;
double PEFLocalElec = totalPEForElecrcity
/ totalLocalElecProduction;
double totalPEConsumtion = (totalLocalElecProduction - Export)
* PEFLocalElec
+ Import
* PEFImport
+ BiomassConsumption
+ oilConsumption
+ nGasConsumption
+ (totalHeatDemand * hpHeatPercentage - totalHeatDemand
* hpHeatPercentage / COP) + solaThermal;
double ESD = (Import * PEFImport + oilConsumption + nGasConsumption)
/ totalPEConsumtion;
solution.setObjective(2, ESD);*/
// check warning
col = (Collection<String>) energyplanmMap.get("WARNING");
if (col != null) {
/*
* System.out.println("No warning"); } else {
*/
@SuppressWarnings("rawtypes")
Iterator it3 = col.iterator();
String warning = it3.next().toString();
if (!warning.equals("PP too small. Critical import is needed")
&& !warning
.equals("Grid Stabilisation requierments are NOT fullfilled")
&& !warning
.equals("Critical Excess Electricity Production"))
throw new IOException("warning!!" + warning);
// System.out.println("Warning " + it3.next().toString());
}
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
}
@SuppressWarnings("unchecked")
public void evaluateConstraints(Solution solution) throws JMException {
Iterator it;
Collection<String> col;
// constraints about heat3-balance: balance<=0
col = (Collection<String>) energyplanmMap.get("Biomass Consumption");
it = col.iterator();
double annualBiomassConsumption = Double.parseDouble(it.next()
.toString());
double constraints[] = new double[numberOfConstraints_];
constraints[0] = 98.84 - annualBiomassConsumption;
double totalViolation = 0.0;
int numberOfViolation = 0;
for (int i = 0; i < numberOfConstraints_; i++) {
if (constraints[i] < 0.0) {
totalViolation += constraints[0];
numberOfViolation++;
}
}
solution.setOverallConstraintViolation(totalViolation);
solution.setNumberOfViolatedConstraint(numberOfViolation);
}
void writeModificationFile(double pv, double oilBoilerHeatPercentage,
double nGasBoilerHeatPercentage,
double biomassBoilerHeatPercentage,
double biomassCHPHeatPercentage, double hpHeatPercentage,
double totalDieselDemandInGWhForTrns,
double totalElecDemandInGWhForTrns,
double totalH2DemandInGWhForTrns, double oilSolarPercentage,
double nGasSolarPercentage, double biomassBoilerSolarPercentage,
double biomassCHPSolarPercentage, double hpSolarPercentage)
throws JMException {
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) Math.round(pv);
bw.write(str);
bw.newLine();
// oil boiler fuel demand
str = "input_fuel_Households[2]=";
bw.write(str);
bw.newLine();
double oilBoilerFuelDemand = oilBoilerHeatPercentage
* totalHeatDemand / oilBoilerEfficiency;
str = "" + oilBoilerFuelDemand;
bw.write(str);
bw.newLine();
// Related solar thermal
str = "input_HH_oilboiler_Solar=";
bw.write(str);
bw.newLine();
str = "" + oilBoilerFuelDemand * oilSolarPercentage;
bw.write(str);
bw.newLine();
// Ngas boiler fuel demand
str = "input_fuel_Households[3]=";
bw.write(str);
bw.newLine();
double ngasBoilerFuelDemand = nGasBoilerHeatPercentage
* totalHeatDemand / nGasBoilerEfficiency;
str = "" + ngasBoilerFuelDemand;
bw.write(str);
bw.newLine();
// Related solar thermal
str = "input_HH_ngasboiler_Solar=";
bw.write(str);
bw.newLine();
str = "" + ngasBoilerFuelDemand * nGasSolarPercentage;
bw.write(str);
bw.newLine();
// biomass boiler fuel demand
str = "input_fuel_Households[4]=";
bw.write(str);
bw.newLine();
double biomassBoilerFuelDemand = biomassBoilerHeatPercentage
* totalHeatDemand / biomassBoilerEfficiency;
str = "" + biomassBoilerFuelDemand;
bw.write(str);
bw.newLine();
// Related solar thermal
str = "input_HH_bioboiler_Solar=";
bw.write(str);
bw.newLine();
str = "" + biomassBoilerFuelDemand * biomassBoilerSolarPercentage;
bw.write(str);
bw.newLine();
// biomass micro chp heat demand
str = "input_HH_BioCHP_heat=";
bw.write(str);
bw.newLine();
str = "" + biomassCHPHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
// Related solar thermal
str = "input_HH_bioCHP_solar=";
bw.write(str);
bw.newLine();
str = "" + biomassCHPHeatPercentage * totalHeatDemand
* biomassCHPSolarPercentage;
bw.write(str);
bw.newLine();
// heat pump heat demand
str = "input_HH_HP_heat=";
bw.write(str);
bw.newLine();
str = "" + hpHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
// Related solar thermal
str = "input_HH_HP_Solar=";
bw.write(str);
bw.newLine();
str = "" + hpHeatPercentage * totalHeatDemand * hpSolarPercentage;
bw.write(str);
bw.newLine();
// to handle scintific number
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(2);
// Diesel demand
str = "input_fuel_Transport[2]=";
bw.write(str);
bw.newLine();
str = "" + df.format(totalDieselDemandInGWhForTrns);
bw.write(str);
bw.newLine();
// number of convensional cars
double numberOfConCars = (totalDieselDemandInGWhForTrns * Math.pow(
10, 6))
/ (efficiencyConCar * averageKMPerYearPerCar * Math.pow(10,
3));
str = "Input_Size_transport_conventional_cars=";
bw.write(str);
bw.newLine();
str = "" + numberOfConCars;
bw.write(str);
bw.newLine();
// Electric car electricity demand
str = "input_transport_TWh=";
bw.write(str);
bw.newLine();
str = "" + totalElecDemandInGWhForTrns;
bw.write(str);
bw.newLine();
// number of electric car
double numberOfEVCars = totalElecDemandInGWhForTrns
* Math.pow(10, 6)
/ (efficiencyEVCar * averageKMPerYearPerCar * Math.pow(10,
3));
str = "Input_Size_transport_electric_cars=";
bw.write(str);
bw.newLine();
str = "" + numberOfEVCars;
bw.write(str);
bw.newLine();
/*// hydrogen demand for Transport
str = "input_fuel_Transport[6]=";
bw.write(str);
bw.newLine();
str = "" + df.format(totalH2DemandInGWhForTrns);
bw.write(str);
bw.newLine();
// number of FCEV car
double numberOfFCEVCars = totalH2DemandInGWhForTrns
* Math.pow(10, 6)
/ (efficiencyFCEVCar * averageKMPerYearPerCar * Math.pow(
10, 3));
str = "Input_Size_transport_other_vehicles1=";
bw.write(str);
bw.newLine();
str = "" + numberOfFCEVCars;
bw.write(str);
bw.newLine();
// corresponding eletrolyzer capacity
int electrolyzerCapacity = (int) Math
.floor(maxH2DemandInDistribution
* totalH2DemandInGWhForTrns
* Math.pow(10, 6)
/ (efficiencyElectrolyzerTrans * sumH2DemandInDistribution));
str = "input_cap_ELTtrans_el=";
bw.write(str);
bw.newLine();
str = "" + electrolyzerCapacity;
bw.write(str);
bw.newLine();*/
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
void writeIntoInputFile(double pv, double oilBoilerHeatPercentage,
double nGasBoilerHeatPercentage,
double biomassBoilerHeatPercentage,
double biomassCHPHeatPercentage, double hpHeatPercentage,
double totalDieselDemandInGWhForTrns,
double totalElecDemandInGWhForTrns,
/*double totalH2DemandInGWhForTrns,*/ double oilSolarPercentage,
double nGasSolarPercentage, double biomassBoilerSolarPercentage,
double biomassCHPSolarPercentage, double hpSolarPercentage)
throws IOException {
String modifiedParameters[] = { "input_RES1_capacity=", // pv (0)
"input_fuel_Households[2]=", // oil boiler (1)
"input_HH_oilboiler_Solar=", // oil Solar Thermal (2)
"input_fuel_Households[3]=", // nGas boiler (3)
"input_HH_ngasboiler_Solar=", // nGas Solar Thermal (4)
"input_fuel_Households[4]=", // bioMass boiler (5)
"input_HH_bioboiler_Solar=", // biomas Solar thermal (6)
"input_HH_BioCHP_heat=", // biomass CHP (7)
"input_HH_BioCHP_solar=", // biomass CHP Solar thermal (8)
"input_HH_HP_heat=", // HP (9)
"input_HH_HP_solar=", // HP Solar thermal (10)
"input_fuel_Transport[5]=", // Petrol demand (11)
"Input_Size_transport_conventional_cars=", // number of
// convensional cars
// (12)
"input_transport_TWh=", // EV car electricity demand (13)
"Input_Size_transport_electric_cars=", // number of electric car
// (14)
/*"input_fuel_Transport[6]=", // hydrogen demand for Transport
// (15)
"Input_Size_transport_other_vehicles1=", // number of FCEV car
// (16)
"input_cap_ELTtrans_el=" // //corresponding eletrolyzer capacity
// (17)*/
};
String cooresPondingValues[] = new String[modifiedParameters.length];
File modifiedInput = new File("modifiedInput.txt");
if (modifiedInput.exists()) {
modifiedInput.delete();
}
modifiedInput.createNewFile();
FileWriter fw = new FileWriter(modifiedInput.getAbsoluteFile());
BufferedWriter modifiedInputbw = new BufferedWriter(fw);
String path ="C:\\Users\\mahbub\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\EnergyPLAN_12.3\\energyPlan Data\\Data\\VdN SH Eleboration\\VdN_SH_2030_Opt_Scenario_2DS_El_mob.txt";
BufferedReader mainInputbr = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"));
cooresPondingValues[0] = "" + pv;
double oilBoilerFuelDemand = oilBoilerHeatPercentage * totalHeatDemand
/ oilBoilerEfficiency;
cooresPondingValues[1] = "" + oilBoilerFuelDemand;
double oilSolarThermal = oilBoilerFuelDemand * oilSolarPercentage;
cooresPondingValues[2] = "" + oilSolarThermal;
double ngasBoilerFuelDemand = nGasBoilerHeatPercentage
* totalHeatDemand / nGasBoilerEfficiency;
cooresPondingValues[3] = "" + ngasBoilerFuelDemand;
double nGasSolarThermal = ngasBoilerFuelDemand * nGasSolarPercentage;
cooresPondingValues[4] = "" + nGasSolarThermal;
double biomassBoilerFuelDemand = biomassBoilerHeatPercentage
* totalHeatDemand / biomassBoilerEfficiency;
cooresPondingValues[5] = "" + biomassBoilerFuelDemand;
double biomassBoilerSolarThermal = biomassBoilerFuelDemand
* biomassBoilerSolarPercentage;
cooresPondingValues[6] = "" + biomassBoilerSolarThermal;
double baiomassCHPHeatDemand = biomassCHPHeatPercentage
* totalHeatDemand;
cooresPondingValues[7] = "" + baiomassCHPHeatDemand;
double biomassCHPSolarThermal = baiomassCHPHeatDemand * efficiencyBiomassCHP *
biomassCHPSolarPercentage;
cooresPondingValues[8] = "" + biomassCHPSolarThermal;
double hpHEatDemand = hpHeatPercentage * totalHeatDemand;
cooresPondingValues[9] = "" + hpHEatDemand;
double hpSolarThermal = hpHeatPercentage * totalHeatDemand
* hpSolarPercentage;
cooresPondingValues[10] = "" + hpSolarThermal;
cooresPondingValues[11] = "" + totalDieselDemandInGWhForTrns;
double numberOfConCars = (totalDieselDemandInGWhForTrns * Math.pow(10,
6))
/ (efficiencyConCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[12] = "" + numberOfConCars;
cooresPondingValues[13] = "" + totalElecDemandInGWhForTrns;
double numberOfEVCars = totalElecDemandInGWhForTrns * Math.pow(10, 6)
/ (efficiencyEVCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[14] = "" + numberOfEVCars;
/*cooresPondingValues[15] = "" + totalH2DemandInGWhForTrns;
double numberOfFCEVCars = totalH2DemandInGWhForTrns
* Math.pow(10, 6)
/ (efficiencyFCEVCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[16] = "" + numberOfFCEVCars;
int electrolyzerCapacity = (int) Math.floor(maxH2DemandInDistribution
* totalH2DemandInGWhForTrns * Math.pow(10, 6)
/ (efficiencyElectrolyzerTrans * sumH2DemandInDistribution))+1;
cooresPondingValues[17] = "" + electrolyzerCapacity;*/
String line;
while ((line = mainInputbr.readLine()) != null) {
line.trim();
boolean trackBreak=false;
for (int i = 0; i < modifiedParameters.length; i++) {
if (line.startsWith(modifiedParameters[i]) || line.endsWith(modifiedParameters[i])) {
modifiedInputbw.write(line+"\n" );
line = mainInputbr.readLine();
line=line.replace(line, cooresPondingValues[i]);
modifiedInputbw.write(line+"\n");
trackBreak=true;
break;
}
}
if(trackBreak)
continue;
else
modifiedInputbw.write(line+"\n");
}
modifiedInputbw.close();
mainInputbr.close();
}
}
<file_sep>package reet.fbk.eu.OprimizeEnergyPLAN.problem;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.FileHandler;
import jmetal.core.Algorithm;
import jmetal.core.Operator;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import jmetal.metaheuristics.nsgaII.NSGAII;
import jmetal.operators.selection.SelectionFactory;
import jmetal.qualityIndicator.QualityIndicator;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.RandomGenerator;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.crossover.CrossoverFactory;
import reet.fbk.eu.OprimizeEnergyPLAN.jmetal.operators.mutation.MutationFactory;
public class EnergyPLANProblemStep1Main {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
public static void main(String[] args) throws JMException,
SecurityException, IOException, ClassNotFoundException {
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
indicators = null;
int noOfBinaryIntVariable = 4;
int noOfRealVariable = 3;
long seed = 2121979;
PseudoRandom.setRandomGenerator(new RandomGenerator(seed));
problem = new EnergyPLANProblemStep1("BinaryIntAndReal",
noOfBinaryIntVariable, noOfRealVariable);
indicators = new QualityIndicator(problem, "truePf");
algorithm = new NSGAII(problem);
// algorithm = new ssNSGAII(problem);
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 500);
// Mutation and Crossover for Binary codification
parameters = new HashMap();
parameters.put("singlePointCrossoverProbability", 0.9);
parameters.put("SBXCrossoverProbability", 0.9);
parameters.put("distributionIndex", 20.0);
crossover = CrossoverFactory.getCrossoverOperator(
"SinglePointAndSBXCrossoverForRes", parameters);
parameters = new HashMap();
parameters.put("bitFlipMutationProbability",
1 / (double) noOfRealVariable);
parameters.put("polynomialMutationProbability",
1 / (double) noOfRealVariable);
parameters.put("distributionIndex", 20.0);
mutation = MutationFactory.getMutationOperator(
"BitFlipAndPolynomialMutationForRes", parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator("BinaryTournament2",
parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
int numberOfRun = 1;
for (int i = 0; i < numberOfRun; i++) {
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile("run_" + i + "_VAR");
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile("run_" + i + "_FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: "
+ indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : "
+ indicators.getEpsilon(population));
int evaluations = ((Integer) algorithm
.getOutputParameter("evaluations")).intValue();
logger_.info("Speed : " + evaluations + " evaluations");
} // if
}
}
}
<file_sep>talking the resulted Pareto-front reported in ASOS paper (C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\ParetoFront\WithoutRM\With_mutation_pr_0.1) and add all other results get from 3 configuration Diversity maximization experiments:
1. C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrackWithSI\WithoutRM\DivMax
2. C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrackWithSI\WithoutRM\DivMax
mergeFUN_ASOC: Pareto-front from ASOC papar
mergeFUN_DivMax_NSGAII_Con1: mergeFUN for DivMAX NSGAII configuration 1
mergeFUN_DivMax_NSGAII_Con2: mergeFUN for DivMAX NSGAII configuration 2
mergeFUN_DivMax_NSGAII_Con3: mergeFUN for DivMAX NSGAII configuration 3
mergeFUN_DivMax_SPEA2_Con1: mergeFUN for DivMAX SPEA2 configuration 1
mergeFUN_DivMax_SPEA2_Con2: mergeFUN for DivMAX SPEA2 configuration 2
mergeFUN_DivMax_SPEA2_Con3: mergeFUN for DivMAX SPEA2 configuration 3
mergeFUN: mergeFUN for all mergeFUN*
mergeFUN.pf: pareto-front
<file_sep>In this result all boiler parameters are free. They can be choose any way. Unlikely other simulation where the HP replace oil boiler and then Ngas boiler.<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII with smart initilization.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution (modified to work without PP and boiler capacity, now, the number of decision variable is 5. The file will be found in initilization folder)
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm:SPEA2ForSI
selection: Binary Tournament 2.
long seed[]={
125386,
145295,
158570,
207621,
227297,
243858,
354528,
356090,
378578,
384873,
425374,
437331,
461628,
538947,
544774,
631545,
637384,
647647,
647848,
712308,
733779,
764889,
857578,
866208,
867882,
878532,
891747,
917083,
919749,
957363
};
read initial population from "C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\InitIndividualWithSI\WithoutRM" folder. These population are withour ramdom inidividuals.
mergeFUN_SSI_WSI: all Pareto front from 30 runs with SPEA2 with smart inililization
N.B: These results are reported in ASOC paper<file_sep>#this scipt is used to generate a boxplot with four indicator (hypervolume, IGD, Epsilon, spead)
postscript("indicators_NSGAII_SPEA2_test.eps", horizontal=FALSE, onefile=FALSE, height=6, width=8.5, pointsize=12)
#pdf("combined_comparison.pdf", onefile=FALSE, width=8.5, height = 6)
#jpeg(filename = "combined_comparison.jpeg", width = 8.5, height = 6, units = "in", pointsize = 10, res = 1000)
NSGAIIresultDirectory<-"."
NSGAIIqIndicator <- function(indicator)
{
fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAIIWithoutTrack", sep="/")
#fileNSGAII<-paste(fileNSGAII,"With_mutation_pr_0.2", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
fileNSGAII<-paste(fileNSGAII, indicator, sep="/")
NSGAII_results<-scan(fileNSGAII)
fileNSGAIIsi<-paste(NSGAIIresultDirectory, "NSGAIIWithoutTrackWithSI", sep="/")
fileNSGAIIsi<-paste(fileNSGAIIsi, "WithoutRM", sep="/")
#fileNSGAIIsi<-paste(fileNSGAIIsi, "With_mutation_pr_0.2", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileNSGAIIsi<-paste(fileNSGAIIsi, indicator, sep="/")
NSGAIIsi_results<-scan(fileNSGAIIsi)
#3rd algorithm
fileNSGAIIsi_DivMax<-paste(NSGAIIresultDirectory, "NSGAIIWithoutTrackWithSI", sep="/")
fileNSGAIIsi_DivMax<-paste(fileNSGAIIsi_DivMax, "WithoutRM", sep="/")
fileNSGAIIsi_DivMax<-paste(fileNSGAIIsi_DivMax, "DivMax", sep="/")
fileNSGAIIsi_DivMax<-paste(fileNSGAIIsi_DivMax, "Configuration 2", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileNSGAIIsi_DivMax<-paste(fileNSGAIIsi_DivMax, indicator, sep="/")
NSGAIIsi_DivMax_results<-scan(fileNSGAIIsi_DivMax)
algs<-c("RI","SI", "SIDivMax")
boxplot(NSGAII_results,NSGAIIsi_results,NSGAIIsi_DivMax_results, names=algs, notch = FALSE)
titulo <-paste(indicator, "NSGAII", sep=":")
title(main=titulo)
}
SPEA2resultDirectory<-"."
SPEA2qIndicator <- function(indicator)
{
fileSPEA2<-paste(SPEA2resultDirectory, "SPEA2WithoutTrack", sep="/")
#fileSPEA2<-paste(fileSPEA2, "With_mutation_pr_0.2", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
fileSPEA2<-paste(fileSPEA2, indicator, sep="/")
SPEA2_results<-scan(fileSPEA2)
fileSPEA2si<-paste(SPEA2resultDirectory, "SPEA2WithoutTrackWithSI", sep="/")
fileSPEA2si<-paste(fileSPEA2si, "WithoutRM", sep="/")
#fileSPEA2si<-paste(fileSPEA2si, "With_mutation_pr_0.2", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileSPEA2si<-paste(fileSPEA2si, indicator, sep="/")
SPEA2si_results<-scan(fileSPEA2si)
#3rd algo (DivMax)
fileSPEA2si_DivMax<-paste(SPEA2resultDirectory, "SPEA2WithoutTrackWithSI", sep="/")
fileSPEA2si_DivMax<-paste(fileSPEA2si_DivMax, "WithoutRM", sep="/")
fileSPEA2si_DivMax<-paste(fileSPEA2si_DivMax, "DivMax", sep="/")
fileSPEA2si_DivMax<-paste(fileSPEA2si_DivMax, "Configuration 2", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileSPEA2si_DivMax<-paste(fileSPEA2si_DivMax, indicator, sep="/")
SPEA2si_DivMax_results<-scan(fileSPEA2si_DivMax)
algs<-c("RI","SI", "SIDivMax")
boxplot(SPEA2_results,SPEA2si_results,SPEA2si_DivMax_results, names=algs, notch = FALSE)
titulo <-paste(indicator, "SPEA2", sep=":")
title(main=titulo)
}
#SPEA2resultDirectory<-"./MutationStudySPEA2/data/"
#SPEA2qIndicator <- function(indicator, problem)
#{
#filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
#PolynomialMutation<-scan(filePolynomialMutation)
#fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
#fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
#DKMutation<-scan(fileDKMutation)
#algs<-c("Polynomial","DKMutation")
#boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
#titulo <-paste(indicator, "SPEA2", sep=":")
#title(main=titulo)
#}
par(mfrow=c(2,4), cex.lab=2.5, cex.axis=1.5)
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
indicator<-"HV"
SPEA2qIndicator(indicator)
indicator<-"IGD"
SPEA2qIndicator(indicator)
indicator<-"Epsilon"
SPEA2qIndicator(indicator)
indicator<-"Spread"
SPEA2qIndicator(indicator)
#indicator<-"HV"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"IGD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"GD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"Epsilon"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
dev.off()
<file_sep>The true Paretofrot is the merge of two separate run.
1. SBX_Poly
2. SBX_DKMutation probability 0.4
3. SBX_DKMutation probability 0.2<file_sep>#this scipt is used to generate a boxplot with four indicator (hypervolume, IGD, Epsilon, spead)
postscript("compare_NSGAII_Int_SPEA2_Int.eps", horizontal=FALSE, onefile=FALSE, height=6, width=8.5, pointsize=10)
#pdf("combined_comparison.pdf", onefile=FALSE, width=8.5, height = 6)
#jpeg(filename = "comNSGAII_SIandSPEA2_SI.jpeg", width = 8.5, height = 6.0, units = "in", pointsize = 10, res = 1000)
NSGAIIresultDirectory<-"."
SPEA2resultDirectory<-"."
NSGAIIqIndicator <- function(indicator)
{
fileNSGAII_Int<-paste(NSGAIIresultDirectory, "NSGAII_Int", sep="/")
fileNSGAII_Int<-paste(fileNSGAII_Int, indicator, sep="/")
NSGAII_Int_results<-scan(fileNSGAII_Int)
fileSPEA2_Int<-paste(SPEA2resultDirectory, "SPEA2_Int", sep="/")
fileSPEA2_Int<-paste(fileSPEA2_Int, indicator, sep="/")
SPEA2_Int_results<-scan(fileSPEA2_Int)
algs<-c("NSGAII_Int","SPEA2_Int")
boxplot(NSGAII_Int_results,SPEA2_Int_results,names=algs, notch = FALSE)
titulo <-paste(indicator)
title(main=titulo)
}
par(mfrow=c(2,4))
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
dev.off()
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANCIVIS.CEIS.Problem;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.util.JMException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.MultiMap;
import reet.fbk.eu.OptimizeEnergyPLANCIVIS.ParseFile.*;
/*
* This is a problem file that is dealing with Transport (mainly introduction of electric cars)
*/
public class EnergyPLANProblemCivisCEIS4DWithTransport extends Problem {
MultiMap energyplanmMap;
public static final double PVInvestmentCostInKEuro = 2.6;
public static final double hydroInvestmentCostInKEuro = 1.9;
public static final double individualBoilerInvestmentCostInKEuro = 0.588;
public static final double BiogasInvestmentCostInKEuro = 4.0;
public static final double interest = 0.04;
public static final double currentPVCapacity = 7514;
public static final double currentHydroCapacity = 4000;
public static final double currentBiogasCapacity = 500;
public static final double currentIndvBiomassBoilerCapacity = 14306;
public static final double currentIndvOilBoilerCapacity = 9155;
public static final double currentIndvLPGBoilerCapacity = 3431;
public static final double totalHeatDemand = 55.82;
public static final double boilerLifeTime = 15;
public static final double PVLifeTime = 30;
public static final double HydroLifeTime = 50;
public static final double BiogasLifeTime = 20;
public static final double geoBoreHoleLifeTime = 100;
public static final double COP = 3.2;
public static final double maxHeatDemandInDistribution = 1.0;
public static final double sumOfAllHeatDistributions = 3112.94;
public static final double geoBoreholeCostInKWe = 3.2;
public static final double oilBoilerEfficiency = 0.80;
public static final double ngasBoilerEfficiency = 0.90;
public static final double biomassBoilerEfficiency = 0.75;
public static final double addtionalCostPerGWhinKEuro = 106.27;
//Transport related data
public static final int currentNumberOfPertrolCars = 2762;
public static final int currentNumberOfDieselCars = 2094;
public static final int averageKMPerYearForPetrolCar = 7250;
public static final int averageKMPerYearForDieselCar = 13400;
// lower calorific value (LCV): KWh/l (ref: http://www.withouthotair.com/c3/page_31.shtml) check with Diego
public static final double LCVPetrol = 8.86;
public static final double LCVDiesel = 10.12;
public static final double KWhPerKMElecCar = 0.168;
public static final double petrolCarRunsKMperL = 15.5;
public static final double DieselCarRunsKMperL = 18.2;
public static final int totalKMRunByCars = 48084100;
public static final double costOfElectricCarInKeuro = 18.690;
public static final int electricCarLifeTime = 15;
public static final double electricCarOperationalAndMaintanenceCost = 0.055; //5.5 percent of Investment cost (costOfElectricCarInKeuro)
/**
* Creates a new instance of problem ZDT1.
*
* @param numberOfVariables
* Number of variables.
* @param solutionType
* The solution type must "Real", "BinaryReal, and "ArrayReal".
*/
public EnergyPLANProblemCivisCEIS4DWithTransport(String solutionType) {
numberOfVariables_ = 6;
numberOfObjectives_ = 4;
numberOfConstraints_ = 1;
/*
* at this moment, there are two objectives, 0 -> PV 1 -> Heat pump
*/
// numberOfConstraints_ = 3;
problemName_ = "OptimizeEnergyPLANCivisCeDis";
upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];
// Establishes upper and lower limits for the variables
int var;
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> LPG boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// index - 5 -> electric car percentage
// PV upper and lower limit
lowerLimit_[0] = 5000.0;
upperLimit_[0] = 42000.0;
// other are the percentage from limit [0,1]
for (var = 1; var < numberOfVariables_; var++) {
lowerLimit_[var] = 0.0;
upperLimit_[var] = 1.0;
} // for
if (solutionType.compareTo("Real") == 0)
solutionType_ = new RealSolutionType(this);
else {
System.out.println("Error: solution type " + solutionType
+ " invalid");
System.exit(-1);
}
} // constructor end
/**
* Evaluates a solution.
*
* @param solution
* The solution to evaluate.
* @throws JMException
*/
@SuppressWarnings("unchecked")
public void evaluate(Solution solution) throws JMException {
// PV
double pv = solution.getDecisionVariables()[0].getValue();
// index - 1 -> oil boiler heat percentage
// index - 2 -> LPG boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// Oil-boiler heat percentage
// index - 5 -> electric car percentage
double percentages[] = new double[4];
for (int i = 0; i < 4; i++) {
percentages[i] = solution.getDecisionVariables()[i + 1].getValue();
}
Arrays.sort(percentages);
for (int i = 1; i < numberOfVariables_-1; i++) {
solution.getDecisionVariables()[i].setValue(percentages[i - 1]);
}
// oil-boiler percentage
double oilBoilerHeatPercentage = percentages[0];
// Ngas-boiler heat percentage
double LPGBoilerHeatPercentage = percentages[1] - percentages[0];
// biomass-boiler heat percentage
double biomassBoilerHeatPercentage = percentages[2] - percentages[1];
// ngas chp heat percentage
double biomassCHPHeatPercentage = percentages[3] - percentages[2];
// heat pump heat percentage
double hpHeatPercentage = 1.0 - percentages[3];
//electric car percentage
double electricCarPercentage = solution.getDecisionVariables()[5].getValue();
int reducedNumberOfPetrolCars = (int) Math.round(currentNumberOfPertrolCars - currentNumberOfPertrolCars * electricCarPercentage);
int reducedNumberOfDieselCars = (int) Math.round(currentNumberOfDieselCars - currentNumberOfDieselCars * electricCarPercentage);
double reducedPetrolDemandInGWh = reducedNumberOfPetrolCars * averageKMPerYearForPetrolCar * LCVPetrol / (petrolCarRunsKMperL*1000000);
double reducedDieselDemandInGWh = reducedNumberOfDieselCars * averageKMPerYearForDieselCar * LCVDiesel / (DieselCarRunsKMperL*1000000);
int elecCarRunKM = totalKMRunByCars - (reducedNumberOfPetrolCars * averageKMPerYearForPetrolCar) - (reducedNumberOfDieselCars * averageKMPerYearForDieselCar);
double elecCarElectricityDemandInGWh = elecCarRunKM * KWhPerKMElecCar / 1000000;
double totalNumberOfElectricCars = (int) Math.round(currentNumberOfPertrolCars + currentNumberOfDieselCars - reducedNumberOfPetrolCars - reducedNumberOfDieselCars);
writeModificationFile(pv, oilBoilerHeatPercentage,
LPGBoilerHeatPercentage, biomassBoilerHeatPercentage,
biomassCHPHeatPercentage, hpHeatPercentage, reducedPetrolDemandInGWh, reducedDieselDemandInGWh, elecCarElectricityDemandInGWh, "NC");
String energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i "
+ "\".\\src\\reet\\fbk\\eu\\OptimizeEnergyPLANCIVIS\\CEIS\\data\\CEIS_Complete_Current.txt\" "
+ "-m \"modification.txt\" -ascii \"result.txt\" ";
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParseForCivis epfp = new EnergyPLANFileParseForCivis(
".\\result.txt");
energyplanmMap = epfp.parseFile();
Iterator it;
Collection<String> col;
// objective # 1
col = (Collection<String>) energyplanmMap
.get("CO2-emission (corrected)");
it = col.iterator();
solution.setObjective(0, Double.parseDouble(it.next().toString()));
// objective # 2
col = (Collection<String>) energyplanmMap
.get("Total variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
totalVariableCostStr = totalVariableCostStr.substring(0,
totalVariableCostStr.lastIndexOf("1000"));
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanmMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
fixedOperationalCostStr = fixedOperationalCostStr.substring(0,
fixedOperationalCostStr.lastIndexOf("1000"));
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
col = (Collection<String>) energyplanmMap.get("AnnualHydropower");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract anual PV production
col = (Collection<String>) energyplanmMap.get("AnnualPV");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
//extract biogas production (it is named as wave power)
col = (Collection<String>) energyplanmMap.get("AnnualWavepower");
it = col.iterator();
double BiogasElecProduction = Double.parseDouble(it.next()
.toString());
// extract annual import
col = (Collection<String>) energyplanmMap.get("Annualimport");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanmMap.get("Annualexport");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
//extract biomass CHP electricity production
col = (Collection<String>) energyplanmMap.get("AnnualHH-elec.CHP");
it = col.iterator();
double biomassCHPElecProduction = Double.parseDouble(it.next().toString());
// calculate additional cost
// (hydroProduction+PVproduction+Import-Export)*average additional
// cost (85.74)
double totalAdditionalCost = Math.round((hydroPowerProduction
+ PVproduction + Import - Export + biomassCHPElecProduction)
* addtionalCostPerGWhinKEuro);
// new capacity of individual boilers
/*
* double newHeatdemandForBoilers = (totalHeatDemand *
* oilBoilerHeatPercentage + totalHeatDemand *
* ngasBoilerHeatPercentage + totalHeatDemand *
* biomassBoilerHeatPercentage); double
* capacityOfBoilerforNewHeatDemand =
* Math.round(maxHeatDemandInDistribution *
* newHeatdemandForBoilers*Math.pow(10,
* 6)*1.5/sumOfAllHeatDistributions);
*/
double capacityOfHeatPump = Math.round((maxHeatDemandInDistribution
* hpHeatPercentage * totalHeatDemand * Math.pow(10, 6))
/ (COP * sumOfAllHeatDistributions));
double geoBoreHoleInvestmentCost = (capacityOfHeatPump
* geoBoreholeCostInKWe * interest)
/ (1 - Math.pow((1 + interest), -geoBoreHoleLifeTime));
// see annual investment cost formula in EnergyPLAN manual
double newCapacityBiomassBoiler = Math
.round((totalHeatDemand * biomassBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionBiomassBoiler = 0.0;
if (newCapacityBiomassBoiler > currentIndvBiomassBoilerCapacity) {
investmentCostReductionBiomassBoiler = (currentIndvBiomassBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionBiomassBoiler = (newCapacityBiomassBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityOilBoiler = Math
.round((totalHeatDemand * oilBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionOilBoiler = 0.0;
if (newCapacityOilBoiler > currentIndvOilBoilerCapacity) {
investmentCostReductionOilBoiler = (currentIndvOilBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionOilBoiler = (newCapacityOilBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityLPGBoiler = Math
.round((totalHeatDemand * LPGBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionLPGBoiler = 0.0;
if (newCapacityLPGBoiler > currentIndvLPGBoilerCapacity) {
investmentCostReductionLPGBoiler = (currentIndvLPGBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionLPGBoiler = (newCapacityLPGBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double reductionInvestmentCost = (currentPVCapacity
* PVInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -PVLifeTime))
+ (currentHydroCapacity * hydroInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -HydroLifeTime))
+ (currentBiogasCapacity * BiogasInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -BiogasLifeTime))
+ investmentCostReductionBiomassBoiler
+ investmentCostReductionOilBoiler
+ investmentCostReductionLPGBoiler;
// extract
col = (Collection<String>) energyplanmMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
String investmentCostStr = invest.substring(0,
invest.lastIndexOf("1000"));
double investmentCost = Double.parseDouble(investmentCostStr);
double realInvestmentCost = investmentCost
- reductionInvestmentCost + geoBoreHoleInvestmentCost;
//Electric car related cost
double totalInvestmentCostOfElectricCars = (totalNumberOfElectricCars * costOfElectricCarInKeuro * interest)/ (1 - Math.pow((1 + interest), -electricCarLifeTime));
double totalFixOperationalAndInvestmentCostOfElectricCars = totalNumberOfElectricCars * costOfElectricCarInKeuro * electricCarOperationalAndMaintanenceCost ;
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ realInvestmentCost + totalAdditionalCost + totalInvestmentCostOfElectricCars + totalFixOperationalAndInvestmentCostOfElectricCars;
solution.setObjective(1, actualAnnualCost);
//3rd objective
//Trasportation
col = (Collection<String>) energyplanmMap
.get("Annualflexibleeldemand");
it = col.iterator();
double transportElecDemand = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("Annualelec.demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
//Individual house HP electric demand
col = (Collection<String>) energyplanmMap.get("AnnualHH-elec.HP");
it = col.iterator();
double annualHPdemand = Double.parseDouble(it.next().toString());
solution.setObjective(2, (Import + Export) / (annualElecDemand+transportElecDemand +annualHPdemand) );
//extract ngas consuption
col = (Collection<String>) energyplanmMap
.get("Ngas Consumption");
it = col.iterator();
double nGasConsumption = Double.parseDouble(it.next().toString());
//extract oil consumption
col = (Collection<String>) energyplanmMap
.get("Oil Consumption");
it = col.iterator();
double oilConsumption = Double.parseDouble(it.next().toString());
//extract biomass consupmtion
col = (Collection<String>) energyplanmMap.get("Biomass Consumption");
it = col.iterator();
double BiomassConsumption = Double.parseDouble(it.next().toString());
double PVPEF = 1.0;
double HYPEF = 1.0;
double BioGasPEF = 1/0.262;
double BiomassPEF = 1/0.18;
double PEFImport = 2.17;
double totalPEForElecrcity = PVproduction * PVPEF + hydroPowerProduction * HYPEF + BiogasElecProduction*BioGasPEF + biomassCHPElecProduction * BiomassPEF;
double totalLocalElecProduction = PVproduction + hydroPowerProduction + BiogasElecProduction+biomassCHPElecProduction;
double PEFLocalElec = totalPEForElecrcity/ totalLocalElecProduction;
double totalPEConsumtion = (totalLocalElecProduction - Export) * PEFLocalElec + Import * PEFImport + BiomassConsumption + oilConsumption + nGasConsumption
+ (totalHeatDemand* hpHeatPercentage - totalHeatDemand* hpHeatPercentage/COP);
double ESD = (Import * PEFImport + oilConsumption + nGasConsumption)/totalPEConsumtion;
solution.setObjective(3, ESD);
// check warning
col = (Collection<String>) energyplanmMap.get("WARNING");
if (col != null) {
/*
* System.out.println("No warning"); } else {
*/
@SuppressWarnings("rawtypes")
Iterator it3 = col.iterator();
String warning = it3.next().toString();
if (!warning.equals("PP too small. Critical import is needed")
&& !warning
.equals("Grid Stabilisation requierments are NOT fullfilled")
&& !warning
.equals("Critical Excess Electricity Production"))
throw new IOException("warning!!" + warning);
// System.out.println("Warning " + it3.next().toString());
}
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
}
@SuppressWarnings("unchecked")
public void evaluateConstraints(Solution solution) throws JMException {
Iterator it;
Collection<String> col;
// constraints about heat3-balance: balance<=0
col = (Collection<String>) energyplanmMap.get("Biomass Consumption");
it = col.iterator();
double annualBiomassConsumption = Double.parseDouble(it.next()
.toString());
double constraints[] = new double[numberOfConstraints_];
constraints[0] = 56.87 - annualBiomassConsumption;
double totalViolation = 0.0;
int numberOfViolation = 0;
for (int i = 0; i < numberOfConstraints_; i++) {
if (constraints[i] < 0.0) {
totalViolation += constraints[0];
numberOfViolation++;
}
}
solution.setOverallConstraintViolation(totalViolation);
solution.setNumberOfViolatedConstraint(numberOfViolation);
}
void writeModificationFile(double pv, double oilBoilerHeatPercentage,
double LPGBoilerHeatPercentage,
double biomassBoilerHeatPercentage, double biomassCHPHeatPercentage,
double hpHeatPercentage, double reducedPetrolDemand, double reducedDieselDemand, double elecCarDemand, String elecChangeProfile) throws JMException {
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) Math.round(pv);
bw.write(str);
bw.newLine();
// oil boiler fuel demand
str = "input_fuel_Households[2]=";
bw.write(str);
bw.newLine();
double oilBoilerFuelDemand = oilBoilerHeatPercentage
* totalHeatDemand / oilBoilerEfficiency;
str = "" + oilBoilerFuelDemand;
bw.write(str);
bw.newLine();
// Ngas boiler fuel demand
str = "input_fuel_Households[3]=";
bw.write(str);
bw.newLine();
double ngasBoilerFuelDemand = LPGBoilerHeatPercentage
* totalHeatDemand / ngasBoilerEfficiency;
str = "" + ngasBoilerFuelDemand;
bw.write(str);
bw.newLine();
// biomass boiler fuel demand
str = "input_fuel_Households[4]=";
bw.write(str);
bw.newLine();
double biomassBoilerFuelDemand = biomassBoilerHeatPercentage
* totalHeatDemand / biomassBoilerEfficiency;
str = "" + biomassBoilerFuelDemand;
bw.write(str);
bw.newLine();
// biomass micro chp heat demand
str = "input_HH_BioCHP_heat=";
bw.write(str);
bw.newLine();
str = "" + biomassCHPHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
// heat pump heat demand
str = "input_HH_HP_heat=";
bw.write(str);
bw.newLine();
str = "" + hpHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
//Electric car electricity demand
str = "input_transport_TWh=";
bw.write(str);
bw.newLine();
str = "" + elecCarDemand;
bw.write(str);
bw.newLine();
//to handle scintific number
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(2);
//Reduced Diesel demand
str = "input_fuel_Transport[2]=";
bw.write(str);
bw.newLine();
str = "" + df.format(reducedDieselDemand);
bw.write(str);
bw.newLine();
//reduced petrol demand
str = "input_fuel_Transport[5]=";
bw.write(str);
bw.newLine();
str = "" + df.format(reducedPetrolDemand);
bw.write(str);
bw.newLine();
if(elecChangeProfile.equals("DC")){
// day charge profile
str = "Filnavn_transport=";
bw.write(str);
bw.newLine();
str = "CIVIS_Transport_DC.txt";
bw.write(str);
bw.newLine();
}
else if(elecChangeProfile.equals("NC")){
// day charge profile
str = "Filnavn_transport=";
bw.write(str);
bw.newLine();
str = "CIVIS_Transport_NC.txt";
bw.write(str);
bw.newLine();
}else{
throw new JMException("chrging profile not given");
}
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>import java.util.Random;
import jmetal.util.*;
public class TestRandom {
public static void main(String args[]){
PseudoRandom.setRandomGenerator(new RandomGenerator(1500));
Random rm=new Random();
System.out.println(PseudoRandom.randInt());
System.out.println(PseudoRandom.randDouble());
System.out.println(rm.nextInt(100));
System.out.println(PseudoRandom.randInt());
System.out.println(PseudoRandom.randDouble());
}
}
<file_sep>All the Pareto fronts found in 240 different runs are merged. And new Pareto front is built.
mergeFUN_N: all Pareto front from 30 runs with NSGAII
mergeFUN_NSI_WRM: all Pareto front from 30 runs with NSGAII with smart inililization without random individuals
mergeFUN_S: all Pareto front from 30 runs with SPEA2
mergeFUN_SSI_WRM: all Pareto front from 30 runs with SPEA2 with smart inililization without random individuals
mergeFUN_NDK: all Pareto front from 30 runs with NSGAII with DK/smart mutation
mergeFUN_SDK: all Pareto front from 30 runs with SPEA2 with DK/smart mutation
mergeFUN_NInt_WRM: all Pareto front from 30 runs with NSGAII with integrated/combined approach without random individuals in initialization phase
mergeFUN_SInt_WRM: all Pareto front from 30 runs with SPEA2 with integrated/combined approach without random individuals in initialization phase
mergeFUN: merge mergeFUN_*
mergeFUN.pf: Pareto front after merging smart initializzation+ DK/smart mutation+integratedMOEA results
<file_sep>This folder contains the results of our proposed stopping criteria (ADV+DIV) applied on Aalborg problem (reet.fbk.eu.OptimizeEnergyPLANAalborg.problem.EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution).
populationSize: 100
MaxEvaluation: 10000
Crossover: SBX
Crossover probability: 0.9
Mutation: GeneralModifiedPolynomialMutationForEnergySystems
Mutation probability: 1/numberOfDecisionVariables
Boolean favorGenesforRE[] ={true, true, null, true, true, true, null};
Boolean favorGenesforConventionalPP[] ={false, false, null, false, false, false, null};
Algotithm: NSGAII (NSGAIIForDKandSC; reet.fbk.eu.jmetal.metaheuristics.nsgaII.NSGAIIForDKandSC )
Stopping Criteria parameters:
nGenLT = 20
noGenUnCh = 5;
significanceValue = 0.05;
maxEvalution=10000<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII for building true Pareto front.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.2 (Mutation probability is increaded to match with DKMutation)
Distribution index: 10
Algorithm: NSGA-II
selection: Binary Tournament 2.
long seed[] =
{
161395,
170339,
259029,
276644,
288470,
309259,
353882,
365652,
370995,
455875,
456545,
458478,
468245,
515856,
545782,
547945,
549235,
562366,
626495,
652262,
668763,
683991,
698156,
714786,
756252,
930462,
981354,
989776,
992177,
999921
};
mergeFUN_N: all Pareto front from 30 runs with NSGAII<file_sep>All the Pareto fronts found in 240 different runs are merged. And new Pareto front is built.
mergeFUN_N: all Pareto front from 30 runs with NSGAII
mergeFUN_NSI: all Pareto front from 30 runs with NSGAII with smart inililization
mergeFUN_S: all Pareto front from 30 runs with SPEA2
mergeFUN_SSI: all Pareto front from 30 runs with SPEA2 with smart inililization
mergeFUN_NDK: all Pareto front from 30 runs with NSGAII with DK/smart mutation
mergeFUN_SDK: all Pareto front from 30 runs with SPEA2 with DK/smart mutation
mergeFUN_NInt: all Pareto front from 30 runs with NSGAII with integrated/combined approach
mergeFUN_SInt: all Pareto front from 30 runs with SPEA2 with integrated/combined approach
mergeFUN: merge mergeFUN_*
mergeFUN.pf: Pareto front after merging smart initializzation+ DK/smart mutation+integratedMOEA results
<file_sep>This is the results of 10 different runs with 10 different seed.
Here mutation based on domain knowledge (modified polynomial mutation) is applies with SBX crossover.
It mutation is designed to work in 3 stages.
mutation probability of applying different types of mutation (RE favor, CE favor, generic mutataion) depends of generation. In the early generation, two favor mutation is moslt applied, after some generation the probability goes down and the probability of applying generic mutation goes up.
Population: 100
Evolution: 5000
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 4
Algorithm: NSGA-II
selection: Binary Tournament 2.
seed [] = {545782, 455875, 547945, 458478, 981354, 652262, 562366, 365652, 456545, 549235 };
<file_sep>package reet.fbk.eu.OptimizedEnergyPLANFelicetti.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.MultiMap;
public class WriteDataToFile {
static String inputs[] = { "PV_Cap", "WavePower_Cap", /*"Biomass_CHP_Cap", "NGas_CHP_Cap", "HP_Cap",
"Oil_boiler_Cap", "NGas_boiler_Cap", "Biomass_boiler_Cap", "SolarThermal", */
"NumberOfDieselCars", "NumberOfPetrolCars", "NumberOfEVCars", "IndvEloctrolyzer_Cap",
"H2FeedStock", "FeedStockElectrolyzer_Cap", "FeedStockH2(imp)",
"ElecStorage_Turbine_Cap","ElecStorage_Pump_Cap", "ElecStorage_Storage_Cap" };
static String outputsinEnergyPLANMap[] = { "AnnualPVElectr.", "AnnualHH-CHPElectr.",
"AnnualHH-HPElectr.", "AnnualFlexibleElectr.", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualHH SolarHeat",
"AnnualImportElectr.", "AnnualExportElectr.", "Oil Consumption",
"Biomass Consumption", "Ngas Consumption",
/*"Gasoil/Diesel",
"Biomass",*/ "Bottleneck", "Electricity exchange",
"Variable costs", "Fixed operation costs", "AdditionalCost",
//"ConCarInvestmentCost","EVCarInvestmentCost","FCEVCarInvestmentCost",
"Annual Investment costs", "CO2Emission", "AnnualCost",
"oilBoilerFuelDemand", "ngasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualH2mCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualHH SolarHeat",
"transOilDemand",
"OilBoilerSolarInput", "NGasBoilerSolarInput","NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput", "H2CHPSolarInput",
"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization",
"Annual MaximumImportElectr.", "Annual MaximumExportElectr."};
static String outputsinFile[] = { "AnnualPV", "AnnualCHPelec",
"AnnualHPelec", "AnnualElecCar", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermalheat",
"AnnualImport", "AnnualExport", "OilConsumption",
"BiomassConsumption", "NGasConsuption",
/*"PetrolCost",
"BiomassCost",*/ "Bottleneck", "TotalElectricityExchangeCost",
"TotalVariableCost", "FixedOperationCosts", "AdditionalCost",
//"ConCarInvestmentCost","EVCarInvestmentCost","FCEVInvestmentCost",
"InvestmentCost","CO2-Emission", "AnnualCost",
"oilBoilerFuelDemand", "NGasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualH2mCHPheat","AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermal",
"transOilDemand",
"OilBoilerSolarInput", "NGasBoilerSolarInput", "NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput","H2CHPSolarInput",
"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization",
"Annual MaximumImportElectr.", "Annual MaximumExportElectr."
};
static String inputUnits[] = { "MWe", "MWe", /*"MWe", "MWe", "MWth", "MWth", "MWth", "TWh",*/ "1000 units", "1000 units", "1000 units", "MWe", "MWh","MWe", "MWh", "MW", "MW", "GWh" };
static String outputUnits[] = { "TWh", "TWh", // "AnnualPV", "AnnualCHPelec",
"TWh", "TWh", "TWh", "TWh", "TWh", //"AnnualHPelec", "AnnualElecCar", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"TWh", "TWh", "TWh","TWh", "TWh", "TWh", //"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermalheat",
"TWh", "TWh", "TWh", //"AnnualImport", "AnnualExport", "OilConsumption",
"TWh", "TWh", //"BiomassConsumption", "NGasConsuption",
/*"MEuro", //"DieselCost",
"MEuro",*/ "MEuro", //"BiomassCost", "TotalElectricityExchangeCost",
"MEuro", "MEuro", "MEuro", //"TotalVariableCost", "FixedOperationCosts", "AdditionalCost",
//"KEuro", "KEuro", "KEuro", //"ConCarInvestmentCost","EVCarInvestmentCost","FCEVInvestmentCost",
"MEuro", "Mt", "MEuro", //"InvestmentCost","CO2-Emission", "Total Local System Emission", "AnnualCost",
"TWh","TWh","TWh","TWh","TWh","TWh","TWh", //"oilBoilerFuelDemand", "NGasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat, "AnnualHPheat", "AnnualSolarThermal",
"TWh", //"transOilDemand"
"TWh","TWh","TWh", "TWh","TWh","TWh", "TWh", //"OilBoilerSolatInput", "NGasBoilerSolarInput","NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput"
"TWh","TWh","TWh", "TWh","TWh", //"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization"
"MW", "MW"
};
static public void WriteEnergyPLANParametersToFile(MultiMap energyPLANMap, File filePath)
throws IOException {
Iterator it;
Collection<String> col;
// if file doesnt exists, then create it
if (!filePath.exists()) {
filePath.createNewFile();
// create header of the file
FileWriter fw = new FileWriter(filePath.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
/*
* bw.write(
* "PV_C HP_Heat_P OilBoilerHeat NgasBoilerHeat BiomassBoilerHeat "
* +
* "AnlPV_P AnlImport AnlExport AnlOilBoilerFuel AnlNgasBoilerFuel "
* +
* "AnlBiomassBoilerFuel AnlOilCost AnlLPGCost AnlBiomassCost AnlElecExchage TotalVariableCost FixedOperationalCost "
* +
* "AdditionalCost InvestmentCost CO2Emission AnnualCost LoadFollowingCapacity"
* );
*/
String headings = "";
for (int i = 0; i < inputs.length; i++) {
headings += inputs[i] + ";";
}
for (int i = 0; i < outputsinFile.length; i++) {
headings += outputsinFile[i] + ";";
}
bw.write(headings);
bw.newLine();
String units = "";
for (int i = 0; i < inputUnits.length; i++) {
units += inputUnits[i] + ";";
}
for (int i = 0; i < outputUnits.length; i++) {
units += outputUnits[i] + ";";
}
bw.write(units);
/*
* bw.write(
* "(KW) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) " +
* "(GWh) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) "
* + "(Mt) (KEuro)");
*/
bw.newLine();
bw.close();
}
FileWriter fw = new FileWriter(filePath.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
String input = "", output = "";
for (int i = 0; i < inputs.length; i++) {
col = (Collection<String>) energyPLANMap.get(inputs[i]);
try{
it = col.iterator();
}catch(NullPointerException e) {
input = input + ";";
continue;
}
input = input + it.next() + ";";
}
for (int i = 0; i < outputsinEnergyPLANMap.length; i++) {
try{
col = (Collection<String>) energyPLANMap
.get(outputsinEnergyPLANMap[i]);
it = col.iterator();
String str = it.next().toString();
if(str.equals("1000"))
System.out.println("la la");
if (!str.equals("1000") && str.endsWith("1000")) {
str = str.substring(0, str.lastIndexOf("1000"));
str = Double.parseDouble(str) + "";
}
output = output + str + ";";
}
catch(NullPointerException e){
output = output + ";";
System.out.println(i);
continue;
}
}
bw.write(input + output);
bw.newLine();
bw.close();
}
}
<file_sep>#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
pdf("indicators_NSGAII_NSGAII_DKM.pdf", onefile=FALSE, width=10)
NSGAIIresultDirectory<-"."
NSGAIIqIndicator <- function(indicator)
{
fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAII", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
fileNSGAII<-paste(fileNSGAII, indicator, sep="/")
NSGAII_results<-scan(fileNSGAII)
fileNSGAIIDKM<-paste(NSGAIIresultDirectory, "NSGAIIWithDKMutation", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileNSGAIIDKM<-paste(fileNSGAIIDKM, indicator, sep="/")
NSGAIIDKM_results<-scan(fileNSGAIIDKM)
algs<-c("NSGAII","NSGAIIDKM")
boxplot(NSGAII_results,NSGAIIDKM_results,names=algs, notch = FALSE)
titulo <-paste(indicator)
title(main=titulo)
}
#SPEA2resultDirectory<-"./MutationStudySPEA2/data/"
#SPEA2qIndicator <- function(indicator, problem)
#{
#filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
#PolynomialMutation<-scan(filePolynomialMutation)
#fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
#fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
#DKMutation<-scan(fileDKMutation)
#algs<-c("Polynomial","DKMutation")
#boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
#titulo <-paste(indicator, "SPEA2", sep=":")
#title(main=titulo)
#}
par(mfrow=c(2,3))
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"GD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
#indicator<-"HV"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"IGD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"GD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"Epsilon"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
<file_sep>package reet.fbk.eu.jmetal.operators.mutation;
//MutationFactory.java
//
//Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
//Copyright (c) 2011 <NAME>, <NAME>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import jmetal.util.Configuration;
import jmetal.util.JMException;
import java.util.HashMap;
import jmetal.operators.mutation.Mutation;
import reet.fbk.eu.jmetal.operators.mutation.RE.BitFlipAndPolynomialMutationForRes;
import reet.fbk.eu.jmetal.operators.mutation.RE.BitFlipAndPolynomialMutationForResWithDK;
import reet.fbk.eu.jmetal.operators.mutation.Real.GeneralRealMutationForRes;
import reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial.GeneralModifiedPolynomialMutationForEnergySystems;
/**
* Class implementing a factory for Mutation objects.
*/
public class MutationFactory {
/**
* Gets a crossover operator through its name.
* @param name of the operator
* @return the operator
* @throws JMException
*/
public static Mutation getMutationOperator(String name, HashMap parameters) throws JMException{
/*if (name.equalsIgnoreCase("PolynomialMutation"))
return new PolynomialMutation(parameters);
else if (name.equalsIgnoreCase("BitFlipMutation"))
return new BitFlipMutation(parameters);
else if (name.equalsIgnoreCase("NonUniformMutation"))
return new NonUniformMutation(parameters);
else if (name.equalsIgnoreCase("SwapMutation"))
return new SwapMutation(parameters);*/
if (name.equalsIgnoreCase("BitFlipAndPolynomialMutationForRes"))
return new BitFlipAndPolynomialMutationForRes(parameters);
else if (name.equalsIgnoreCase("BitFlipAndPolynomialMutationForResWithDK"))
return new BitFlipAndPolynomialMutationForResWithDK(parameters);
else if (name.equalsIgnoreCase("GeneralRealMutationForRes"))
return new GeneralRealMutationForRes(parameters);
else if (name.equalsIgnoreCase("GeneralModifiedPolynomialMutationForEnergySystems"))
return new GeneralModifiedPolynomialMutationForEnergySystems(parameters);
/*else if(name.equalsIgnoreCase("BitFlipMutationFavorMaximizationOfRes"))
return new BitFlipMutationFavorMaximizationOfRes(parameters);
else if(name.equalsIgnoreCase("MutationForRes"))
return new MutationForRes(parameters);*/
else
{
Configuration.logger_.severe("Operator '" + name + "' not found ");
Class cls = java.lang.String.class;
String name2 = cls.getName() ;
throw new JMException("Exception in " + name2 + ".getMutationOperator()") ;
}
} // getMutationOperator
} // MutationFactory
<file_sep>[DocHistory]
FileCount=77
File0=C:\Users\shaik\eclipse-workspace\EnergyPLANDomainKnowledgeEA\src\reet\fbk\eu\OptimizeEnergyPLANCIVIS\CEIS\data\CEIS_Complete_Current.txt
File1=C:\Users\shaik\eclipse-workspace\EnergyPLANDomainKnowledgeEA\EnergyPLAN15.1\energyPlan Data\Data\SRI_2025_V3.txt
File2=energyPlan Data\Data\SRI_2025_V3.txt
File3=energyPlan Data\Data\modifiedInput0
File4=energyPlan Data\Data\Test Solar Utilization.txt
File5=energyPlan Data\Data\Test.txt
File6=energyPlan Data\Data\Felicetti_baseline2018_IH_v2.txt
File7=C:\Users\shaik\eclipse-workspace\EnergyPLANDomainKnowledgeEA\modifiedInput.txt
File8=energyPlan Data\Data\Felicetti_Trentino_OPT_2025_IH_v3_3.txt
File9=energyPlan Data\Data\SRI_2025.txt
File10=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v10.txt
File11=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v10_opt.txt
File12=C:\Users\shaik\Downloads\PEAP_PAT_LC_2050_DH_v10.txt
File13=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v10.txt
File14=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v10_opt.txt
File15=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v10_opt.txt
File16=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v10.txt
File17=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v9_opt.txt
File18=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v9.txt
File19=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v9_opt.txt
File20=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v9.txt
File21=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v9_opt.txt
File22=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v9.txt
File23=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v8_opt.txt
File24=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v8_opt.txt
File25=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v8_opt.txt
File26=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v8.txt
File27=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v8.txt
File28=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v8.txt
File29=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v7_opt.txt
File30=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v7.txt
File31=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v7_opt.txt
File32=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v7.txt
File33=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v6_opt.txt
File34=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v7_opt.txt
File35=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v7.txt
File36=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v6_opt.txt
File37=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v6.txt
File38=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v5_opt.txt
File39=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2025_DH_v5.txt
File40=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v5_opt.txt
File41=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v5.txt
File42=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v5_opt.txt
File43=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2050_DH_v5.txt
File44=energyPlan Data\Data\PEAP\PEAP_PAT_LC_2030_DH_v4.txt
File45=C:\Users\mahbub\Documents\energyplan test\test.txt
File46=energyPlan Data\Data\Denmark2030Reference.txt
File47=energyPlan Data\Data\VdN_2030.txt
File48=energyPlan Data\Cost\IDA2030_cost2009.txt
File49=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2020_reference_Scenario.txt
File50=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2030_reference_Scenario.txt
File51=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2050_Opt_Scenario_2DS_El_mob.txt
File52=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2030_Opt_Scenario_2DS_El_mob.txt
File53=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2020_Opt_Scenario_2DS_El_mob.txt
File54=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2050_reference_Scenario.txt
File55=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2008.txt
File56=C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\modifiedInput.txt
File57=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2050_Opt_Scenario_4DS_H2_mob.txt
File58=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2050_Opt_Scenario_4DS_El_mob.txt
File59=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2030_Opt_Scenario_4DS_H2_mob.txt
File60=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2030_Opt_Scenario_4DS_El_mob.txt
File61=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2020_Opt_Scenario_4DS_H2_mob.txt
File62=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2020_Opt_Scenario_4DS_El_mob.txt
File63=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2050_Opt_Scenario_2DS_H2_mob.txt
File64=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2030_Opt_Scenario_2DS_H2_mob.txt
File65=energyPlan Data\Data\VdN SH Eleboration\VdN_SH_2020_Opt_Scenario_2DS_H2_mob.txt
File66=energyPlan Data\Data\VdN_2020.txt
File67=energyPlan Data\Data\VdN_SH_2008.txt
File68=energyPlan Data\Data\VdN_SH_2020_2DS.txt
File69=energyPlan Data\Data\VdN_SH_2020.txt
File70=energyPlan Data\Data\VdN_2008_final.txt
File71=energyPlan Data\Data\VdN_2008.txt
File72=energyPlan Data\Data\VdN_2020_DH.txt
File73=energyPlan Data\Data\VdN_2050.txt
File74=energyPlan Data\Data\VdN_2020_test.txt
File75=energyPlan Data\Data\VdN.txt
File76=C:\Users\mahbub\Dropbox\fbk\projects\val de non\val de non.txt
<file_sep>package reet.fbk.eu.jmetal.initialization;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import reet.fbk.eu.OptimizeEnergyPLANWithStep.EnergyPLANProblemWithStep;
import sun.util.locale.StringTokenIterator;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.core.SolutionSet;
import jmetal.problems.ZDT.ZDT1;
import jmetal.util.Distance;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import Jama.Matrix;
/*
* This class is responsible for doing Domain-knowledge initialization
*/
public class DKInitializationInJAVA {
ArrayList<Solution> initialSolutions;
Problem problem_;
Boolean REFavorGenes[], ConFavorGene[], LFCFavorGenes[];
Random rm;
int populationSize, numberOfIndevPerCombination, numberOfRandomSolutions;
double theta;
int maxDistributionIndex;
public DKInitializationInJAVA(Problem problem_, Boolean REFavorGenes[],
Boolean ConFavorGene[], Boolean LFCFavorGenes[],
int populationSize, double theta, int maxDistributionIndex,
int numberOfIndevPerCombination, int numberOfRandomSolutions) {
this.REFavorGenes = REFavorGenes;
this.ConFavorGene = ConFavorGene;
this.LFCFavorGenes = LFCFavorGenes;
this.populationSize = populationSize;
this.theta = theta;
this.maxDistributionIndex = maxDistributionIndex;
this.numberOfIndevPerCombination = numberOfIndevPerCombination;
this.numberOfRandomSolutions = numberOfRandomSolutions;
this.problem_ = problem_;
rm = new Random();
initialSolutions = new ArrayList<Solution>();
}
public DKInitializationInJAVA(Problem problem_, Boolean REFavorGenes[],
Boolean ConFavorGene[], int populationSize, double theta,
int maxDistributionIndex, int numberOfIndevPerCombination,
int numberOfRandomSolutions)
{
this.REFavorGenes = REFavorGenes;
this.ConFavorGene = ConFavorGene;
this.populationSize = populationSize;
this.theta = theta;
this.maxDistributionIndex = maxDistributionIndex;
this.numberOfIndevPerCombination = numberOfIndevPerCombination;
this.numberOfRandomSolutions = numberOfRandomSolutions;
this.problem_ = problem_;
rm = new Random();
initialSolutions = new ArrayList<Solution>();
}
public void generateInitialSolutions() {
}
public void generateInitialSolutionFavorRE() throws ClassNotFoundException,
JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (REFavorGenes[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (REFavorGenes[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateInitialSolutionFavorCon()
throws ClassNotFoundException, JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (ConFavorGene[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (ConFavorGene[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateRandomInitialSolutionWithoutFovor(
int numberOfRandomIndividuals) throws ClassNotFoundException,
JMException {
for (int no = 0; no < numberOfRandomIndividuals; no++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
initialSolutions.add(sol);
}
}
public Integer[] TransformArray(Integer[] aCombination) {
Integer[] combination = new Integer[REFavorGenes.length];
int j = 0;
for (int i = 0; i < REFavorGenes.length; i++) {
try {
if (REFavorGenes[i] == true || REFavorGenes[i] == false) {
combination[i] = aCombination[j++];
}
} catch (NullPointerException e) {
combination[i] = -1;
}
}
return combination;
}
/*
*
*/
public double createGeneWithIncreasedCapacity(int n, double lowerBound,
double upperBound) {
double r = rm.nextDouble();
double delta = Math.pow(r, (1 / ((double) n + 1)));
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
/*
*
*/
public double createGeneWithDecreasedCapacity(int n, double lowerBound,
double upperBound) {
double r = rm.nextDouble();
double delta = 1 - Math.pow((1 - r), (1 / ((double) n + 1)));
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
public double createGeneWithoutAnything(double lowerBound, double upperBound) {
double r = rm.nextDouble();
double delta = r;
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
public SolutionSet doDKInitialization()
throws ClassNotFoundException, JMException
{
/*
* generate all combinations
*/
// int maxDistributionIndex = 3;
initializeLengthAndCounter(maxDistributionIndex, REFavorGenes);
nestedLoopOperation(counters, length, 0);
/*
* generate two kinds of individuals by favoring RES and conventional
* energy
*/
generateInitialSolutionFavorRE();
generateInitialSolutionFavorCon();
// generate some random solution
generateRandomInitialSolutionWithoutFovor(numberOfRandomSolutions);
ArrayList <Solution> temporarySolutionSet = preProcessingIndividuals();
ArrayList<Solution> finalSolutionsList = calculateMaximumDiversityInJava(temporarySolutionSet);
SolutionSet finalSolutionSet = postProcessingIndividuals(finalSolutionsList);
return finalSolutionSet;
}
public ArrayList<Solution> preProcessingIndividuals()throws JMException {
ArrayList<Solution> temporarySolutionSet = new ArrayList<Solution>();
for (int i = 0; i < initialSolutions.size(); i++) {
Solution s= initialSolutions.get(i);
for (int j = 0; j < problem_.getNumberOfVariables(); j++) {
// normalized to 0-1 range
double oldMax = problem_.getUpperLimit(j);
double oldMin = problem_.getLowerLimit(j);
double newMax = 1.0;
double newMin = 0.0;
double oldRange = (oldMax - oldMin) ;
double newRange = (newMax - newMin); //normalized to 0 - 1
double oldValue = s.getDecisionVariables()[j].getValue();
double newValue = (((oldValue - oldMin) * newRange) / oldRange) + newMin;
s.getDecisionVariables()[j].setValue(newValue);
}
temporarySolutionSet.add(s);
}
return temporarySolutionSet;
}
public ArrayList<Solution> calculateMaximumDiversityInJava(ArrayList<Solution> temp) throws JMException{
ArrayList<Solution> S= new ArrayList<Solution>();
int index=rm.nextInt(temp.size());
Solution randomSolution = temp.get(index);
//Add to S
S.add(randomSolution);
//remove from temp
temp.remove(index);
for(int i=1;i<populationSize;i++){
Matrix A = new Matrix(i,i);
A=constructA(A,S);
Matrix AInv=A.inverse();
double maxContribution = Double.MIN_VALUE;
int trackIndexToRemove=-1;
for(int j=0;j<temp.size();j++){
Matrix b = new Matrix(S.size(), 1);
b=calculateDistanceFromSToTempJ(S, temp.get(j));
Matrix d = AInv.times(b);
double alpha = sumOfAllElementOfAMatrix(d);
Matrix k;
Matrix tmp = new Matrix(1,1); tmp.set(0,0, 1.0);
k=tmp.minus (b.transpose().times(d));
double contribution = (alpha-1)*(alpha-1)/k.get(0, 0);
if(contribution>maxContribution){
maxContribution=contribution;
trackIndexToRemove=j;
}
}
System.out.println("i="+i +" index: "+trackIndexToRemove+" contribution: "+maxContribution);
S.add(temp.get(trackIndexToRemove));
temp.remove(trackIndexToRemove);
}
return S;
}
SolutionSet postProcessingIndividuals(ArrayList<Solution> S) throws JMException{
SolutionSet solutionSetToReturn = new SolutionSet(populationSize);
for(int i=0;i<populationSize;i++){
solutionSetToReturn.add(S.get(i));
}
for (int j = 0; j < populationSize; j++) {
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
// get back to original limit
double oldMax = problem_.getUpperLimit(i);
double oldMin = problem_.getLowerLimit(i);
double newMax = 1.0;
double newMin = 0.0;
double oldRange = (oldMax - oldMin) ;
double newRange = (newMax - newMin); //normalized to 0 - 1
double newValue = solutionSetToReturn.get(j).getDecisionVariables()[i].getValue();
double oldValue = oldMin + ((newValue - newMin) * oldRange)/newRange;
solutionSetToReturn.get(j).getDecisionVariables()[i].setValue(oldValue);
}
}
return solutionSetToReturn;
}
double sumOfAllElementOfAMatrix(Matrix A){
double sum=0.0;
for(int i=0;i<A.getRowDimension();i++){
for(int j=0; j<A.getColumnDimension();j++){
sum+=A.get(i, j);
}
}
return sum;
}
Matrix calculateDistanceFromSToTempJ(ArrayList<Solution> S, Solution TempJ) throws JMException{
Matrix b=new Matrix(S.size(), 1);
Distance d=new Distance();
for(int i=0;i<S.size();i++){
double dis = d.distanceBetweenSolutions(S.get(i), TempJ);
double normalizedDistance = Math.exp(-theta * dis);
b.set(i,0,normalizedDistance);
}
return b;
}
Matrix constructA(Matrix A, ArrayList<Solution> S) throws JMException{
Distance d=new Distance();
for(int i=0;i<S.size();i++){
for(int j=0;j<S.size();j++){
double dis = d.distanceBetweenSolutions(S.get(i), S.get(j));
double normalizedDistance = Math.exp(-theta * dis);
A.set(i,j,normalizedDistance);
}
}
return A;
}
/*
* 486 code for generate all combinations
*/
int[] length;
int[] counters;
ArrayList<Integer[]> combinationsArray = new ArrayList<Integer[]>();
/*
* n: is the maximum value of the combinations
*/
void initializeLengthAndCounter(int n, Boolean[] favorGenes) {
combinationsArray.clear();
int combinationSize = 0;
for (int i = 0; i < favorGenes.length; i++) {
try {
if (favorGenes[i] == true || favorGenes[i] == false)
combinationSize++;
} catch (NullPointerException e) {
continue;
}
}
length = new int[combinationSize];
counters = new int[combinationSize];
for (int i = 0; i < combinationSize; i++) {
length[i] = n;
counters[i] = 0;
}
}
void nestedLoopOperation(int[] counters, int[] length, int level) {
if (level == counters.length)
performOperation(counters);
else {
for (counters[level] = 0; counters[level] < length[level]; counters[level]++)
nestedLoopOperation(counters, length, level + 1);
}
}
void performOperation(int[] counters) {
Integer[] counterAsString = new Integer[counters.length];
for (int level = 0; level < counters.length; level++) {
counterAsString[level] = counters[level];
// if(level < counters.length-1) counterAsString = counterAsString +
// ",";
}
//System.out.println(Arrays.toString(counterAsString));
combinationsArray.add(counterAsString);
}
double calculateDiversityOfAPopulation(String fileName) throws JMException{
//1. read from file
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while( (line = br.readLine()) != null){
Solution s = new Solution(problem_);
StringTokenizer st = new StringTokenizer (line);
int i=0;
while (st.hasMoreElements()) {
double value = Double.parseDouble((String) st.nextElement());
s.getDecisionVariables()[i].setValue(value);
i++;
}
initialSolutions.add(s);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (JMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2. preprocessing the data
ArrayList <Solution> temporarySolutionSet = preProcessingIndividuals();
//3. calculate diversity
Matrix A = new Matrix(initialSolutions.size(), initialSolutions.size());
A=constructA(A,temporarySolutionSet);
Matrix AInv=A.inverse();
double diversity = sumOfAllElementOfAMatrix(AInv);
return diversity;
}
public double calculateDiversityOfAPopulation(SolutionSet S) throws JMException{
initialSolutions.clear();
//make a copy
/*SolutionSet TempS = new SolutionSet(S.size());
for(int i=0;i<S.size();i++){
TempS.add(S.get(i));
}*/
for(int i=0;i<S.size();i++){
Solution s = new Solution(S.get(i));
initialSolutions.add(s);
}
//2. preprocessing the data
ArrayList <Solution> temporarySolutionSet = preProcessingIndividuals();
//3. calculate diversity
Matrix A = new Matrix(initialSolutions.size(), initialSolutions.size());
A=constructA(A,temporarySolutionSet);
Matrix AInv=A.inverse();
double diversity = sumOfAllElementOfAMatrix(AInv);
return diversity;
}
/*
* generate all combination: End
*/
/*
* test purpose
*/
public static void main(String args[]) throws ClassNotFoundException,
JMException {
/*Problem problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
Boolean REFavorGenes[] = new Boolean[] { true, true, true, null, false,
null, true };
Boolean ConFavorGenes[] = new Boolean[] { false, false, false, null,
true, null, false };
DKInitializationInJAVA dkini = new DKInitializationInJAVA(problem, REFavorGenes,
ConFavorGenes, 100, 6.0, 8, 5, 100);
@SuppressWarnings("unused")
long initTime = System.currentTimeMillis();
SolutionSet p = dkini.doDKInitialization();
long estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("Total execution time: " + estimatedTime + "ms");*/
Problem problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
Boolean favorGenesforRE[] = { true, true, true, true, true };
Boolean favorGenesforConventionalPP[] = { false, false, false,
false, false };
int populationSize = 100;
/*File folder = new File("C:\\Users\\mahbub\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\InitializationResults\\InitIndividualWithSI\\WithoutRM\\DivMax\\Configuration 3\\");
File[] listOfFiles = folder.listFiles();
int i=0;
for (File file : listOfFiles) {
if (file.isFile()) {
//System.out.println(file.getName());
DKInitializationInJAVA dkini = new DKInitializationInJAVA(problem,
favorGenesforRE, favorGenesforConventionalPP,
populationSize, 6.0, 5, 10, 0);
double diversity = dkini.calculateDiversityOfAPopulation(file.getAbsolutePath());
System.out.println(i+" "+diversity);
i++;
}
}*/
DKInitializationInJAVA dkini = new DKInitializationInJAVA(problem, REFavorGenes,
favorGenesforConventionalPP, 100, 6.0, 5, 3, 0, proxy);
@SuppressWarnings("unused")
long initTime = System.currentTimeMillis();
SolutionSet p = dkini.doDKInitialization();
long estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("Total execution time: " + estimatedTime + "ms");
}
}
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANWithAccuracy.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import jmetal.core.Variable;
import jmetal.util.JMException;
/*
* This class implement the repair method for the decision variable genes
* The class will take a gene at a time and map the gene closest to the multiple of
* the stepsize
*
*/
public class RepairDVGene {
int stepSize;
public RepairDVGene(int stepSize) {
this.stepSize = stepSize;
}
public Variable doRepair(Variable gene)
{
try {
Double geneOriginalValue = gene.getValue();
Double geneTmpValue = new BigDecimal(geneOriginalValue.toString()).setScale(0, RoundingMode.HALF_UP).doubleValue();
Double geneRepairValue = ((geneTmpValue%this.stepSize)>= stepSize/2 ?
(geneTmpValue + (stepSize - geneTmpValue% stepSize)): (geneTmpValue- (geneTmpValue%stepSize)));
gene.setValue(geneRepairValue);
} catch (JMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return gene;
}
}
<file_sep>#this scipt is used to generate a boxplot with four indicator (hypervolume, IGD, Epsilon, spead)
postscript("Compare_SI_DivMax_2Conf.eps", horizontal=FALSE, onefile=FALSE, height=6, width=8.5, pointsize=12)
#pdf("combined_comparison.pdf", onefile=FALSE, width=8.5, height = 6)
#jpeg(filename = "combined_comparison.jpeg", width = 8.5, height = 6, units = "in", pointsize = 10, res = 1000)
NSGAIIresultDirectory<-"../"
NSGAIIqIndicator <- function(indicator)
{
#fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAII", sep="/")
#fileNSGAII<-paste(fileNSGAII, indicator, sep="/")
#NSGAII_results<-scan(fileNSGAII)
fileNSGAIIsi<-paste(NSGAIIresultDirectory, "NSGAII_WithoutRM_SI", sep="/")
fileNSGAIIsi<-paste(fileNSGAIIsi, indicator, sep="/")
NSGAIIsi_results<-scan(fileNSGAIIsi)
#3rd algorithm (DivMa : conf 1)
fileNSGAIIsi_DivMax_conf1<-paste(NSGAIIresultDirectory, "NSGAII_WithoutRM_DivMax_Conf1", sep="/")
fileNSGAIIsi_DivMax_conf1<-paste(fileNSGAIIsi_DivMax_conf1, indicator, sep="/")
NSGAIIsi_DivMax_conf1_results<-scan(fileNSGAIIsi_DivMax_conf1)
#4th algorithm (DivMax : conf 2)
#fileNSGAIIsi_DivMax_conf2<-paste(NSGAIIresultDirectory, "NSGAII_WithoutRM_DivMax_Conf2", sep="/")
#fileNSGAIIsi_DivMax_conf2<-paste(fileNSGAIIsi_DivMax_conf2, indicator, sep="/")
#NSGAIIsi_DivMax_conf2_results<-scan(fileNSGAIIsi_DivMax_conf2)
#5th algorithm (DivMax : conf 3)
fileNSGAIIsi_DivMax_conf3<-paste(NSGAIIresultDirectory, "NSGAII_WithoutRM_DivMax_Conf3", sep="/")
fileNSGAIIsi_DivMax_conf3<-paste(fileNSGAIIsi_DivMax_conf3, indicator, sep="/")
NSGAIIsi_DivMax_conf3_results<-scan(fileNSGAIIsi_DivMax_conf3)
algs<-c(expression("SI"[d], "SI"[A1],"SI"[A2]))
boxplot(NSGAIIsi_results,NSGAIIsi_DivMax_conf1_results, NSGAIIsi_DivMax_conf3_results, names=algs, notch = FALSE)
titulo <-paste(indicator, "NSGAII", sep=":")
title(main=titulo)
}
SPEA2resultDirectory<-"../"
SPEA2qIndicator <- function(indicator)
{
fileSPEA2si<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_SI", sep="/")
fileSPEA2si<-paste(fileSPEA2si, indicator, sep="/")
SPEA2si_results<-scan(fileSPEA2si)
#3rd algorithm (DivMa : conf 1)
fileSPEA2si_DivMax_conf1<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_DivMax_Conf1", sep="/")
fileSPEA2si_DivMax_conf1<-paste(fileSPEA2si_DivMax_conf1, indicator, sep="/")
SPEA2si_DivMax_conf1_results<-scan(fileSPEA2si_DivMax_conf1)
#3rd algorithm (DivMa : conf 3)
fileSPEA2si_DivMax_conf3<-paste(SPEA2resultDirectory, "SPEA2_WithoutRM_DivMax_Conf3", sep="/")
fileSPEA2si_DivMax_conf3<-paste(fileSPEA2si_DivMax_conf3, indicator, sep="/")
SPEA2si_DivMax_conf3_results<-scan(fileSPEA2si_DivMax_conf3)
algs<-c(expression("SI"[d], "SI"[A1],"SI"[A2]))
boxplot(SPEA2si_results,SPEA2si_DivMax_conf1_results,SPEA2si_DivMax_conf3_results, names=algs, notch = FALSE)
titulo <-paste(indicator, "SPEA2", sep=":")
title(main=titulo)
}
#SPEA2resultDirectory<-"./MutationStudySPEA2/data/"
#SPEA2qIndicator <- function(indicator, problem)
#{
#filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
#PolynomialMutation<-scan(filePolynomialMutation)
#fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
#fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
#DKMutation<-scan(fileDKMutation)
#algs<-c("Polynomial","DKMutation")
#boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
#titulo <-paste(indicator, "SPEA2", sep=":")
#title(main=titulo)
#}
par(mfrow=c(2,4), cex.lab=2.5, cex.axis=1.5)
indicator<-"HV"
NSGAIIqIndicator(indicator)
indicator<-"IGD"
NSGAIIqIndicator(indicator)
indicator<-"Epsilon"
NSGAIIqIndicator(indicator)
indicator<-"Spread"
NSGAIIqIndicator(indicator)
indicator<-"HV"
SPEA2qIndicator(indicator)
indicator<-"IGD"
SPEA2qIndicator(indicator)
indicator<-"Epsilon"
SPEA2qIndicator(indicator)
indicator<-"Spread"
SPEA2qIndicator(indicator)
#indicator<-"HV"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"IGD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"GD"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
#indicator<-"Epsilon"
#SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
dev.off()
<file_sep>package reet.fbk.eu.jmetal.operators.mutation.Real;
//BitFlipMutation.java
//
//Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
//Copyright (c) 2011 <NAME>, <NAME>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.core.Variable;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.encodings.variable.Real;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
import reet.fbk.eu.jmetal.operators.mutation.DKRE.BitFlipMutationFavorMaximizationOfRes;
import reet.fbk.eu.jmetal.operators.mutation.DKRE.BitFlipMutationFavorMaximizationOfPP;
import jmetal.operators.mutation.*;
import jmetal.problems.singleObjective.Sphere;
/**
* This class implements a bit flip mutation operator. NOTE: the operator is
* applied to binary or integer solutions, considering the whole solution as a
* single encodings.variable.
*/
public class GeneralRealMutationForRes extends Mutation {
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays.asList(RealSolutionType.class);
private Double mutationProbability_ = null;
private PolynomialMutation polynomialMutation;
private DKRealMutationFavorRE dkRealMutationFavorRE;
private DKRealMutationFavorConventionalPP dkRealMutationFavorConventionalPP;
Random rm;
/**
* Constructor Creates a new instance of the Bit Flip mutation operator
*/
public GeneralRealMutationForRes(HashMap<String, Object> parameters) {
super(parameters);
if (parameters.get("probability") != null)
mutationProbability_ = (Double) parameters.get("probability");
polynomialMutation = new PolynomialMutation(parameters);
dkRealMutationFavorRE = new DKRealMutationFavorRE(
parameters);
dkRealMutationFavorConventionalPP = new DKRealMutationFavorConventionalPP(
parameters);
rm=new Random();
} // BitFlipMutation
/**
* Perform the mutation operation
*
* @param probability
* Mutation probability
* @param solution
* The solution to mutate
* @throws JMException
*/
public void doMutation(double probability, Solution solution)
throws JMException {
try {
//int random = rm.nextInt(100);
int random=PseudoRandom.randInt(0,100);
if (random < 25) {
dkRealMutationFavorRE.doMutation(
probability, solution);
} else if (random >= 25 && random < 50) {
dkRealMutationFavorConventionalPP.doMutation(
probability, solution);
} else {
polynomialMutation.doMutation(probability, solution);
}
} catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: "
+ "ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation*/
/**
* Executes the operation
*
* @param object
* An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_
.severe("BitFlipMutation.execute: the solution "
+ "is not of the right type. The type should be 'Binary', "
+ "'BinaryReal' or 'Int', but "
+ solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation(mutationProbability_, solution);
return solution;
} // execute
public static void main(String args[]) throws JMException{
HashMap hm = new HashMap();
double distributionIndex = 20.0;
hm.put("probability", 1.0);
hm.put("distributionIndex", distributionIndex);
Problem problem = new Sphere("Real", 7);
Real p1[] = new Real[7];
for(int i=0;i<4;i++){
p1[i] = new Real();
p1[i].setUpperBound(10000);
p1[i].setLowerBound(0);
}
for(int i=4;i<7;i++){
p1[i] = new Real();
p1[i].setUpperBound(1.00);
p1[i].setLowerBound(0);
}
p1[0].setValue(1500.00);
p1[1].setValue(2550.12);
p1[2].setValue(5650.12);
p1[3].setValue(2300.12);
p1[4].setValue(0.124);
p1[5].setValue(0.874);
p1[6].setValue(0.446);
//p1[0].setValue(b);
Real p2[] = new Real[1];
p2[0] = new Real();
Solution s1 = new Solution();
s1.setDecisionVariables((Variable[]) p1);
s1.setType(new RealSolutionType(problem));
GeneralRealMutationForRes gmu = new GeneralRealMutationForRes(hm);
gmu.doMutation(1.0, s1);
}
} // BitFlipMutation
<file_sep>package reet.fbk.eu.jmetal.stoppingCriteria;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
class Solution {
double objectives[];
Solution() {
objectives = new double[30];
}
Solution(double ob[]) {
this.objectives = ob;
}
double getObjective(int position) {
return objectives[position];
}
void setObjective(double value, int postion) {
objectives[postion] = value;
}
}
public class HausdroffDistance {
/*
* ArrayList<Solution> X,Y,Z;
*
* public HausdroffDistance(ArrayList<Solution> X, ArrayList<Solution> Y,
* ArrayList<Solution> Z) { this.X=X; this.Y=Y; this.Z=Z; }
*/
public static void main(String[] args) {
ArrayList<Solution> Sol1, Sol2, Sol3, Sol4;
String directoryName="C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC/ZDT1/run0/";
String fileName = "VAR";
for(int i=2;i<=300;i++){
// Sol4 = readFront(directoryName+fileName+(i-3));
//Sol3 = readFront(directoryName+fileName+(i-2));
Sol2 = readFront(directoryName+fileName+(i-1)*1);
Sol1 = readFront(directoryName+fileName+(i)*1);
//ArrayList<Solution> norSol4 = normalizedFront(Sol4, Sol1);
//ArrayList<Solution> norSol3 = normalizedFront(Sol3, Sol1);
// ArrayList<Solution> norSol2 = normalizedFront(Sol2, Sol1);
// ArrayList<Solution> norSol1 = normalizedFront(Sol1, Sol1);
// printFronts(norSol1, 3);
// System.out.println();
// norSol1 = buildNewFront(norSol1, 2);
// System.out.println();
normalizedFront(Sol2, Sol1);
//0 -> min value, 1->Xpositition, 2->YPosition
double posAndDis[] = calculateHausdroffDistanceForPosition(Sol1, Sol2);
System.out.print(i + " " + posAndDis[0]+ " "+ posAndDis[1] + " " + posAndDis[2]+" ");
// System.out.print(i+" "+calculateHausdroffDistance(Sol1, Sol2));
if(posAndDis[3] == 0){
System.out.print(Sol1.get((int) posAndDis[1]).getObjective(0) + " " + Sol1.get((int) posAndDis[1]).getObjective(1) + " ") ;
System.out.print(Sol2.get((int) posAndDis[2]).getObjective(0) + " " + Sol2.get((int) posAndDis[2]).getObjective(1) + " ") ;
}
else{
System.out.print(Sol1.get((int) posAndDis[2]).getObjective(0) + " " + Sol1.get((int) posAndDis[2]).getObjective(1) + " ") ;
System.out.print(Sol2.get((int) posAndDis[1]).getObjective(0) + " " + Sol2.get((int) posAndDis[1]).getObjective(1) + " ") ;
}
System.out.println();
}
// HausdroffDistance hd = new HausdroffDistance(X, Y, Z);
double[] maximumObjectivesValues = new double[3];
//maximumObjectivesValues = HausdroffDistance.findMaximumObjectiveValies(
// X, Y, Z);
//X = HausdroffDistance.convertAbsoluteObjectiveValuesToRelativeValues(X,
// maximumObjectivesValues);
//Y = HausdroffDistance.convertAbsoluteObjectiveValuesToRelativeValues(Y,
// maximumObjectivesValues);
//Z = HausdroffDistance.convertAbsoluteObjectiveValuesToRelativeValues(Z,
//maximumObjectivesValues);
// System.out.println("(Z,X)"+HausdroffDistance.calculateHausdroffDistance(norZ, norX));
/// System.out.println("(Z,Y)"+HausdroffDistance.calculateHausdroffDistance(norZ, norY));
//System.out.println("(X,Y)"+HausdroffDistance.calculateHausdroffDistance(X, Y));
//System.out.println("(X,Z)"+HausdroffDistance.calculateHausdroffDistance(X, Z));
//System.out.println("(Y,Z)"+HausdroffDistance.calculateHausdroffDistance(Y, Z));
// System.out.println("Average (Z,X)"+HausdroffDistance.calculateHausdroffDistance(norZ, norX)/Math.pow(norX.size(),1/2.0));
//System.out.println("Average (Z,Y)"+HausdroffDistance.calculateHausdroffDistance(norZ, norY)/Math.pow(norY.size(),1/2.0));
//System.out.println(HausdroffDistance.calculateHausdroffDistance(Z, Z));
System.out.println("HD");
for(int i=2;i<=500;i++){
Sol2 = readFront(directoryName+fileName+(i));
Sol1 = readFront(directoryName+fileName+(i-1));
System.out.println(i+ " "+ calculateHausdroffDistance(Sol2, Sol1));
}
}
public static void printFronts(ArrayList<Solution> front, int numberOfObjectives){
for(int i=0;i<front.size();i++){
for(int j=0;j<numberOfObjectives;j++){
System.out.print(front.get(i).getObjective(j)+" ");
}
System.out.println();
}
}
public static ArrayList<Solution> buildNewFront (ArrayList<Solution> front, int numberOfObjectives ){
double [] maximumValue;
//GenerationalDistance gd = new GenerationalDistance();
maximumValue = findMaximumObjectiveValies(front, numberOfObjectives);
double scaleFactor = 1.5;
for(int i=0;i<front.size();i++){
for(int j=0; j<numberOfObjectives;j++){
//front[i][j]=(front[i][j]-maximumValue[j])*scaleFactor+maximumValue[j];
double value = (front.get(i).getObjective(j)-maximumValue[j])*scaleFactor+maximumValue[j];
front.get(i).setObjective(value, j);
}
//front[i][0]=(front[i][0]-maximumValue[0])*scaleFactor+maximumValue[0];
//front[i][1]=(front[i][1]-maximumValue[1])*scaleFactor+maximumValue[1];
}
/*for(int i=0;i<front.size();i++){
for(int j=0; j<numberOfObjectives;j++){
System.out.print(front.get(i).getObjective(j)+" ");
}
System.out.println("");
}*/
return front;
}
public static ArrayList<Solution> readFront (String fileName){
ArrayList<Solution> Z= new ArrayList<Solution>();
try{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = "";
while ((line = br.readLine()) != null) {
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line);
int i = 0;
Solution solution = new Solution();
while (st.hasMoreTokens()) {
solution.setObjective(Double.parseDouble(st.nextToken()), i);
i++;
}
Z.add(solution);
}
} catch (IOException e) {
e.printStackTrace();
}
return Z;
}
public static double distanc(Solution s1, Solution s2) {
double distance = 0;
for (int i = 0; i < s1.objectives.length; i++) {
distance += Math.pow((s1.getObjective(i) - s2.getObjective(i)), 2);
}
return Math.sqrt(distance);
}
public static double distance(Solution x, ArrayList<Solution> Y) {
double min_ = Double.POSITIVE_INFINITY;
for (int i = 0; i < Y.size(); i++) {
double tmpDis = distanc(x, Y.get(i));
if (tmpDis <= min_) {
min_ = tmpDis;
}
}
return min_;
}
public static double distance(ArrayList<Solution> X, ArrayList<Solution> Y) {
double max_ = Double.NEGATIVE_INFINITY;
for (int i = 0; i < X.size(); i++) {
double tmpDis = distance(X.get(i), Y);
if (tmpDis >= max_) {
max_ = tmpDis;
}
}
return max_;
}
public static double calculateHausdroffDistance(ArrayList<Solution> X,
ArrayList<Solution> Y) {
return Math.max(distance(X, Y), distance(Y, X));
}
public static double [] distanceForPosition(Solution x, ArrayList<Solution> Y) {
double min = Double.POSITIVE_INFINITY;
double YPosition=-1;
for (int i = 0; i < Y.size(); i++) {
double tmpDis = distanc(x, Y.get(i));
if (tmpDis <= min) {
min = tmpDis;
YPosition=i;
}
}
double mulReturn[] = new double [2];
//0 -> min value, 1->positition
mulReturn[0] = min;
mulReturn[1]=YPosition;
return mulReturn;
}
public static double[] distanceForPosition(ArrayList<Solution> X, ArrayList<Solution> Y) {
double max = Double.NEGATIVE_INFINITY;
double XPosition=-1;
double YPosition=-1;
for (int i = 0; i < X.size(); i++) {
double tmpDis[] = distanceForPosition(X.get(i), Y);
//System.out.println(tmpDis[0]);
if (tmpDis[0] >= max) {
max = tmpDis[0];
XPosition = i;
YPosition = tmpDis[1];
}
}
double mulReturn[] = new double [3];
//0 -> min value, 1->Xpositition, 2->YPosition
mulReturn[0] = max;
mulReturn[1]=XPosition;
mulReturn[2]=YPosition;
return mulReturn;
}
public static double [] calculateHausdroffDistanceForPosition(ArrayList<Solution> X,
ArrayList<Solution> Y) {
//return Math.max(distance(X, Y), distance(Y, X));
double XtoY[] = distanceForPosition(X, Y);
double YtoX[] = distanceForPosition(Y, X);
//0 -> min value, 1->Xpositition, 2->YPosition, 3-> 0 means XtoY or 1 means YtoX (if XtoY, then index 1 contains X position, if YtoX, then index 1 contains Y position)
if(XtoY[0]>YtoX[0]){
double [] returnValue = new double[4];
for(int i=0;i<3;i++){
returnValue[i]=XtoY[i];
}
returnValue[3] = 0;
return returnValue;
}else{
double [] returnValue = new double[4];
for(int i=0;i<3;i++){
returnValue[i]=YtoX[i];
}
returnValue[3] = 1;
return returnValue;
}
}
public static double[] findMaximumObjectiveValies( ArrayList<Solution> X, ArrayList<Solution> Y, int numberOfObjectives) {
ArrayList<Solution> Z = new ArrayList<>();
double maximumObjectivesValues[] = new double[numberOfObjectives];
for (int i = 0; i < maximumObjectivesValues.length; i++) {
maximumObjectivesValues[i] = Double.MIN_VALUE;
}
Z.addAll(X);
Z.addAll(Y);
for (int i = 0; i < Z.size(); i++) {
for (int j = 0; j < maximumObjectivesValues.length; j++) {
if (Z.get(i).getObjective(j) > maximumObjectivesValues[j]) {
maximumObjectivesValues[j] = Z.get(i)
.getObjective(j);
}
}
}
return maximumObjectivesValues;
}
public static double[] findMinimumObjectiveValies( ArrayList<Solution> X, ArrayList<Solution> Y, int numberOfVariables) {
ArrayList<Solution> Z = new ArrayList<>();
double minimumObjectivesValues[] = new double[numberOfVariables];
for (int i = 0; i < minimumObjectivesValues.length; i++) {
minimumObjectivesValues[i] = Double.MAX_VALUE;
}
Z.addAll(X);
Z.addAll(Y);
for (int i = 0; i < Z.size(); i++) {
for (int j = 0; j < minimumObjectivesValues.length; j++) {
if (Z.get(i).getObjective(j) < minimumObjectivesValues[j]) {
minimumObjectivesValues[j] = Z.get(i)
.getObjective(j);
}
}
}
return minimumObjectivesValues;
}
public static void normalizedFront(ArrayList<Solution> X, ArrayList<Solution> Z){
double [] minimumObjectiveValues = findMinimumObjectiveValies(X, Z, 30);
double [] maximumObjectiveValues = findMaximumObjectiveValies(X, Z,30);
for(int i=0;i<X.size();i++){
double newValue=0;
for(int j=0;j<X.get(i).objectives.length;j++){
newValue= (X.get(i).getObjective(j) - minimumObjectiveValues[j])/ (maximumObjectiveValues[j]-minimumObjectiveValues[j]);
X.get(i).setObjective(newValue, j);
}
}
for(int i=0;i<Z.size();i++){
double newValue=0;
for(int j=0;j<Z.get(i).objectives.length;j++){
newValue= (Z.get(i).getObjective(j) - minimumObjectiveValues[j])/ (maximumObjectiveValues[j]-minimumObjectiveValues[j]);
Z.get(i).setObjective(newValue, j);
}
}
}
public static ArrayList<Solution> convertAbsoluteObjectiveValuesToRelativeValues(
ArrayList<Solution> X, double[] maximumObjectivesValues) {
for (int i = 0; i < X.size(); i++) {
for (int j = 0; j < X.get(i).objectives.length; j++) {
X.get(i).setObjective(
X.get(i).getObjective(j) / maximumObjectivesValues[j],
j);
}
}
return X;
}
}
<file_sep>package reet.fbk.eu.jmetal.stoppingCriteria;
import org.apache.commons.math3.stat.inference.MannWhitneyUTest;
public class MWTest {
public MWTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
double [] x = {0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46};
double[] y={1.15, 0.88, 0.90, 0.74, 1.21};
MannWhitneyUTest mwt = new MannWhitneyUTest();
double w = mwt.mannWhitneyU(x, y);
double p = mwt.mannWhitneyUTest(x, y);
System.out.println(w+" "+p);
}
}
<file_sep>This is the results (FUN and VAR) of 10 different runs with 30 different seeds with NSGAII with smart initilization for building true Pareto front.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution (modified to work without PP and boiler capacity, now, the number of decision variable is 5. The file will be found in initilization folder)
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm:NSGAIIForSI
selection: Binary Tournament 2.
long seed[] ={
145845,
198045,
210901,
228424,
251843,
343434,
351008,
427848,
434479,
447778,
458745,
551254,
551641,
555541,
607483,
613516,
618448,
619821,
625882,
685039,
702847,
741577,
747201,
764699,
765255,
789666,
830237,
915076,
985312,
7811554
};
read initial population from "C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\InitIndividualWithSI\WithoutRM" folder. These population are without random individuals.
mergeFUN_NSI_WRM: all Pareto front from 30 runs with NSGAII with smart inililization
N.B: this results are reported in ASOC paper<file_sep>package reet.fbk.eu.OptimizeEnergyPLANAalborg;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.logging.FileHandler;
import jmetal.core.Algorithm;
import jmetal.core.Operator;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.core.SolutionSet;
import jmetal.metaheuristics.nsgaII.NSGAII;
import jmetal.operators.crossover.CrossoverFactory;
import jmetal.operators.selection.SelectionFactory;
import jmetal.qualityIndicator.QualityIndicator;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.RandomGenerator;
import jmetal.operators.mutation.MutationFactory;
import reet.fbk.eu.OptimizeEnergyPLANAalborg.problem.EnergyPLANProblemAalborg;
import reet.fbk.eu.OptimizeEnergyPLANAalborg.problem.EnergyPLANProblemAalborg2Objectives;
import reet.fbk.eu.jmetal.metaheuristics.nsgaII.NSGAIIForDK;
//import reet.fbk.eu.jmetal.operators.mutation.MutationFactory;
import reet.fbk.eu.jmetal.metaheuristics.spea2.SPEA2ForDK;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class OPtimizeEnergyPLANAalborgMain {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
public static void main(String[] args) throws JMException,
SecurityException, IOException, ClassNotFoundException {
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
// fileHandler_ = new FileHandler("SPEA2.log");
logger_.addHandler(fileHandler_);
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
// seed for NSGAii
// long seed [] = {545782, 455875, 547945, 458478, 981354, 652262,
// 562366, 365652, 456545, 549235 };
// seed for spea2
// long seed[]={102354,986587,456987,159753,
// 216557,589632,471259,523486,4158963,745896};
int numberOfRun = 10;
for (int i = 0; i < numberOfRun; i++) {
// PseudoRandom.setRandomGenerator(new RandomGenerator(seed[i]));
indicators = null;
//problems for 2 objectives
problem=new EnergyPLANProblemAalborg2Objectives("Real");
//problem for 3 objectives
//problem = new EnergyPLANProblemAalborg("Real");
algorithm = new NSGAII(problem);
// algorithm = new SPEA2ForDK(problem, seed[i],
// "SPEA2_SBX_PolynomialMutation");
// indicators = new QualityIndicator(problem,
// "C:\\Users\\Nusrat\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\Results\\truePf\\mergefun.pf")
// ;
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 15000);
// for spea2
// algorithm.setInputParameter("archiveSize",100);
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover",
parameters);
parameters = new HashMap();
parameters.put("probability", 1.0 / problem.getNumberOfVariables());
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// parameters.put("maximum generation", (int)
// algorithm.getInputParameter("maxEvaluations")/(int)
// algorithm.getInputParameter("populationSize")-1);
// mutation =
// MutationFactory.getMutationOperator("GeneralModifiedPolynomialMutationForRes",
// parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
/*SolutionSet population = new SolutionSet() {
@Override
public void printVariablesToFile(String path) {
try {
FileOutputStream fos = new FileOutputStream(path);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
if (size() > 0) {
int numberOfVariables = solutionsList_.get(0)
.getDecisionVariables().length;
for (Solution aSolutionsList_ : solutionsList_) {
for (int j = 0; j < numberOfVariables; j++) {
if (j == 6) {
//decision variable is heat storage for group 3
//round to two decimal place
double a = (double) Math.round((aSolutionsList_
.getDecisionVariables()[j]
.getValue()*100)/100);
bw.write(a + " ");
} else {
double a = Math.round(aSolutionsList_
.getDecisionVariables()[j]
.getValue());
bw.write(a + " ");
}
}
bw.newLine();
}
}
bw.close();
} catch (IOException | JMException e) {
Configuration.logger_
.severe("Error acceding to the file");
e.printStackTrace();
}
} // printVariablesToFile
};
population = algorithm.execute();*/
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
//population.printVariablesToFile("AalborgNewResults\\VAR" + i);
population.printFeasibleVAR("AalborgNewResults\\VAR" + i);
logger_.info("Objectives values have been writen to file FUN");
//population.printObjectivesToFile("AalborgNewResults\\FUN" + i);
population.printFeasibleFUN("AalborgNewResults\\FUN" + i);
}
}
}
<file_sep>In the simulation we want to replace all the individual boilers using district heating. District heating contains CHP, HP and boilers. There are alos eletroliser for district heating where excess electricity from PV can be converted to H2 and use the H2 as CHP fuel.
In the first stage, boiler capacity is very high (17500 KJ/s, KW). In the second stage, the boiler capacity is fixed by using maximul use of boiler.
Decision variables:
0-> chp2 1 -> hp2 2 -> pv capacity
Objectives:
0 -> CO2 emission 1 -> annual cost 2 -> load following capccity
Constraints:
Biomass consumption<=56.78 GWh
EnergyPLAN configuration:
CHP efficiency was wrong.
Elec eff: 0.4 shoulkd be 0.2
TH eff: 0.5 should be 0.7
Technical optimization
Technical optimization Regulation : 2 (balancing both electricity and heat demand)<file_sep>#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
pdf("indicators_NSGAII_SPEA2.pdf", onefile=FALSE, width=10)
NSGAIIresultDirectory<-"./MutationStudyNSGAII/data/"
NSGAIIqIndicator <- function(indicator, problem)
{
filePolynomialMutation<-paste(NSGAIIresultDirectory, "PolynomialMutation", sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
PolynomialMutation<-scan(filePolynomialMutation)
fileDKMutation<-paste(NSGAIIresultDirectory, "DKMutation", sep="/")
fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
DKMutation<-scan(fileDKMutation)
algs<-c("Polynomial","DKMutation")
boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
titulo <-paste(indicator, "NSGAII", sep=":")
title(main=titulo)
}
SPEA2resultDirectory<-"./MutationStudySPEA2/data/"
SPEA2qIndicator <- function(indicator, problem)
{
filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
PolynomialMutation<-scan(filePolynomialMutation)
fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/")
fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
DKMutation<-scan(fileDKMutation)
algs<-c("Polynomial","DKMutation")
boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
titulo <-paste(indicator, "SPEA2", sep=":")
title(main=titulo)
}
par(mfrow=c(2,4))
indicator<-"HV"
NSGAIIqIndicator(indicator, "OptimizeElecEnergy_NSGAII")
indicator<-"IGD"
NSGAIIqIndicator(indicator, "OptimizeElecEnergy_NSGAII")
indicator<-"GD"
NSGAIIqIndicator(indicator, "OptimizeElecEnergy_NSGAII")
indicator<-"Epsilon"
NSGAIIqIndicator(indicator, "OptimizeElecEnergy_NSGAII")
indicator<-"HV"
SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
indicator<-"IGD"
SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
indicator<-"GD"
SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
indicator<-"Epsilon"
SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
<file_sep>The true Paretofrot is the merge of two separate run.
1. SBX_Poly
2. SBX_DKMutation probability 0.4
3. SBX_DKMutation probability 0.2
4. NGSAII_PolynomialMutation
5. NGSAII_DKMutation
6. SPEA2_PolynomialMutation
7. SPEA2_DKMutation<file_sep>This is the results (FUN and VAR) of 30 different runs with integrated NSGAII (Smart initialization + DK mutataion + Stopping criteria).
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: SPEA2ForDKandSCandSI (reet.fbk.eu.jmetal.metaheuristics.nsgaII)
selection: Binary Tournament 2.
Domain-knowledge (same used for Smart Initialization and DKMutataion):
Boolean favorGenesforRE[] = { true, true, true, true, true };
Boolean favorGenesforConventionalPP[] = { false, false, false,false, false };
Seeds:
long seed[]={
131528,
194125,
199140,
286828,
287192,
303839,
304408,
325235,
337877,
347354,
376366,
449029,
472366,
507361,
526317,
570490,
571961,
585378,
607688,
664876,
684002,
692766,
749363,
853504,
860186,
892574,
925410,
931203,
962803,
991907
};
The simutationa run unill all the evaluations are completed. FUN and VAR files for all evaluaitons completed are kept in AllEvoCom folder. Additionally, there are two stopping criteria (folder: criteria1, criteria2).
There are two stopping criteria.
Criterion # 1:
Parameters for Stopping criteria:
nGenLT = 20
noGenUnCh = 5;
significanceValue = 0.05;
Criterion#2:
nGenLT=15
nGenUnCh=7
alpha=0.05
AllEvoCom:
all 700 evaluations are completed.
Initial population read from 'C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\InitIndividualWithSI\WithoutRM' folder. These population are generated without random individuals.
Output:
FUN*: Fun files for different run
VAR*: var files for diferent run
StoppingGen: stopping generation fr different run
mergeFuUN_NInt_WRM: merge all Pareto-front of 30 runs for NSGA-II integrated/combined approach when stopping criteria # 1 is activated.
mergeFuUN_SInt_WRM_AllEvo: merge all Pareto-front of 30 runs for NSGA-II integrated/combined approach with all evaluations completed.
N.B.: results are criteria # 1 are reported in ASOC paper<file_sep>package reet.fbk.eu.jmetal.stoppingCriteria;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import jmetal.core.Problem;
import jmetal.problems.DTLZ.DTLZ1;
import jmetal.problems.ZDT.ZDT1;
import jmetal.problems.ZDT.ZDT2;
import jmetal.problems.ZDT.ZDT3;
import jmetal.problems.ZDT.ZDT4;
import jmetal.problems.ZDT.ZDT6;
import jmetal.qualityIndicator.Hypervolume;
public class GenerationHypervolume {
double [] array;
double [] sum;
int numberOfGenerations;
double trueHV;
Hypervolume qualityIndicator;
Problem problem;
String path;
double [][] trueFront={};
public GenerationHypervolume(String path, Problem problem) {
int totalNumberOfFiles = new File(path+"/run0").listFiles().length;
array = new double[totalNumberOfFiles/2];
sum = new double[totalNumberOfFiles/2];
numberOfGenerations = totalNumberOfFiles/2;
this.problem = problem;
this.path = path;
qualityIndicator = new Hypervolume();
if(problem.getName().startsWith("ZDT")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".pf");
}else if(problem.getName().startsWith("DTL")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".3D.pf");
}else{
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".pf");
}
trueHV= qualityIndicator.hypervolume(trueFront, trueFront, problem.getNumberOfObjectives());
}
public GenerationHypervolume(Problem problem){
qualityIndicator = new Hypervolume();
this.problem = problem;
if(problem.getName().startsWith("ZDT")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".pf");
}else if(problem.getName().startsWith("DTL")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".3D.pf");
}
trueHV= qualityIndicator.hypervolume(trueFront, trueFront, problem.getNumberOfObjectives());
}
public static void main(String[] args) throws ClassNotFoundException {
Problem problem = new ZDT6("Real");
GenerationHypervolume gHV= new GenerationHypervolume("C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC/ZDT6", problem);
/*MultiMap map = new MultiValueMap();
Problem problem = new ZDT6("Real");
gHV.calculateHyperVolume(problem, map);
for(int i=1;i<=500;i++){
String str=map.get(i).toString().replaceAll("\\[|\\]","");
System.out.println(str);
}*/
gHV.calculateAverageHVOfAllGenerations();
}
double calculate_ithGenerationHypervolume(String path, int i){
double [][] solutionFront = qualityIndicator.utils_.readFront(path+"/FUN"+i);
double value = qualityIndicator.hypervolume(solutionFront,
trueFront, problem.getNumberOfObjectives());
return value;
}
void calculateAllGenerationsHV(String path){
for(int i=0;i<numberOfGenerations;i++){
array[i]=calculate_ithGenerationHypervolume(path, (i+1));
}
}
void calculateAverageHVOfAllGenerations(){
File file = new File(path);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
for(int i=0;i<directories.length;i++){
calculateAllGenerationsHV(path+"/"+directories[i]);
for(int j=0;j<numberOfGenerations;j++){
sum[j]+=array[j];
}
}
for(int i=0;i<numberOfGenerations;i++){
System.out.println((i+1)+ " "+sum[i]/directories.length);
}
}
public MultiMap calculateHyperVolume(Problem problem, MultiMap map){
String directoryName="C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/StoppingCriteriaAnalysis/ZDT6/run0/";
String fileName = "FUN";
Hypervolume qualityIndicator = new Hypervolume();
double [][] trueFront={};
if(problem.getName().startsWith("ZDT")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".pf");
}else if(problem.getName().startsWith("DTL")){
trueFront = qualityIndicator.utils_.readFront("paretoFronts/"+problem.getName()+".3D.pf");
}
double trueHV= qualityIndicator.hypervolume(trueFront, trueFront, problem.getNumberOfObjectives());
for(int i=1;i<=500;i+=1){
double [][] solutionFront = qualityIndicator.utils_.readFront(directoryName+fileName+i*1);
//Obtain delta value
double value = qualityIndicator.hypervolume(solutionFront,
trueFront, problem.getNumberOfObjectives());
// map.put(i, value);
//map.put(i, trueHV);
map.put(i, value/trueHV);
}
return map;
}
/*
* ArrayList<Solution> X,Y,Z;
*
* public HausdroffDistance(ArrayList<Solution> X, ArrayList<Solution> Y,
* ArrayList<Solution> Z) { this.X=X; this.Y=Y; this.Z=Z; }
*/
public static double[][] buildNewFront (double [][] front ){
double [] maximumValue;
GenerationalDistance gd = new GenerationalDistance();
maximumValue = gd.utils_.getMaximumValues(front, 2);
double scaleFactor = 1.5;
for(int i=0;i<front.length;i++){
front[i][0]=(front[i][0]-maximumValue[0])*scaleFactor+maximumValue[0];
front[i][1]=(front[i][1]-maximumValue[1])*scaleFactor+maximumValue[1];
}
return front;
}
}
<file_sep>package reet.fbk.eu.jmetal.stoppingCriteria;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.math3.stat.inference.KolmogorovSmirnovTest;
import org.apache.commons.math3.stat.inference.MannWhitneyUTest;
import org.apache.commons.math3.stat.inference.WilcoxonSignedRankTest;
import jmetal.core.Problem;
import jmetal.core.Solution;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
class SolutionVariables {
double variable[] ;
public SolutionVariables(int numberOfVariables) {
variable = new double[30] ;
// TODO Auto-generated constructor stub
}
void setVariable(double value, int position) {
variable[position] = value;
}
double getVariable(int position) {
return variable[position];
}
}
public class CalculateDiversity {
double [] array;
double [] sum;
int numberOfGenerations;
List<SolutionVariables> solutionList;
public CalculateDiversity(String path) {
solutionList = new ArrayList<SolutionVariables>();
int totalNumberOfFiles = new File(path+"/run0").listFiles().length;
array = new double[totalNumberOfFiles/2];
sum = new double[totalNumberOfFiles/2];
numberOfGenerations = totalNumberOfFiles/2;
// TODO Auto-generated constructor stub
}
public CalculateDiversity(){
solutionList = new ArrayList<SolutionVariables>();
}
public static void main(String[] args){
CalculateDiversity cd = new CalculateDiversity("C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC/ZDT1");
//cd.calculateAverageOfDiversityOfAllGenerations("C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC/ZDT6",10);
cd.calculateDiversityOfAllGenerations("C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/NSGAIISC/ZDT1/run1", 10);
cd.printDiversity();
//MultiMap map = new MultiValueMap();
//map = cd.diversityStatisticalTest(10, map);
/*//cd.solutionList.clear();
String output="";
double [] array = new double[200];
for(int i=1;i<200;i++){
cd.solutionList.clear();;
cd.readVARFiles("generationVar\\VAR"+i);
output=output+","+cd.calculateDiversity();
array[i-1]=cd.calculateDiversity();
}
KolmogorovSmirnovTest kst = new KolmogorovSmirnovTest();
for(int i=30;i<200;i++){
double []x = Arrays.copyOfRange(array, (i-30), i);
double []y=Arrays.copyOfRange(array, i-5, i);
//System.out.println(Arrays.toString(x));
//System.out.println(Arrays.toString(y));
double pValue=kst.kolmogorovSmirnovTest(x, y);
System.out.println(i+" "+pValue);
}
//System.out.println(output);*/
/* cd.printDiversity();
for(int i=2;i<31;i++){
System.out.println(i+ " "+ map.get(i).toString());
}*/
}
double calculateDiversityOf_ithGeneration(String path, int i, int numberOfVariables){
solutionList.clear();
readVARFiles(path+"/VAR"+(i), numberOfVariables);
return calculateDiversity(numberOfVariables);
}
double calculateDiversityOf_ithGeneration(double [][] solFrontDS, int numberOfVariables){
solutionList.clear();
for(int i=0;i<solFrontDS.length;i++){
SolutionVariables sv = new SolutionVariables(numberOfVariables) ;
for(int j = 0;j<numberOfVariables ; j++){
sv.setVariable(solFrontDS[i][j], j);
}
solutionList.add(sv);
}
return calculateDiversity(numberOfVariables);
}
void calculateDiversityOfAllGenerations(String path,int numberOfVariables){
for(int i=0;i<array.length;i++){
array[i]=calculateDiversityOf_ithGeneration(path, i, numberOfVariables);
}
}
void calculateAverageOfDiversityOfAllGenerations(String path, int numberOfVariables){
File file = new File(path);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
for(int i=0;i<directories.length;i++){
calculateDiversityOfAllGenerations(path+"/"+directories[i], numberOfVariables);
for(int j=0;j<numberOfGenerations;j++){
sum[j]+=array[j];
}
}
for(int i=0;i<numberOfGenerations;i++){
System.out.println((i+1)+ " "+sum[i]/directories.length);
}
}
void readVARFiles(String fileName, int numberOfVariables) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
//System.out.println(line);
StringTokenizer st = new StringTokenizer(line);
int i = 0;
SolutionVariables sv = new SolutionVariables(numberOfVariables) ;
while (st.hasMoreTokens()) {
sv.setVariable(Double.parseDouble(st.nextToken()), i);
i++;
}
solutionList.add(sv);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
double calculationXkvar(int variablePosition){
double XkSum=0;
for(int i =0;i<solutionList.size();i++){
XkSum+=solutionList.get(i).getVariable(variablePosition);
}
return XkSum/solutionList.size();
}
double calculateXkSquareVar(int variablePosition){
double XkSquareSum=0;
for(int i =0;i<solutionList.size();i++){
XkSquareSum+=Math.pow(solutionList.get(i).getVariable(variablePosition),2);
}
return XkSquareSum/solutionList.size();
}
double calculateDiversity(int numberOfVariables){
double total=0;
for(int i=0;i<numberOfVariables;i++){
total+=(calculateXkSquareVar(i) -Math.pow(calculationXkvar(i),2));
}
double diversity = Math.sqrt(total)/numberOfVariables;
return diversity;
}
public void printDiversity(){
for(int i=0;i<this.array.length;i++){
//System.out.println(i+" "+this.array[i]);
System.out.println(this.array[i]);
}
}
public MultiMap diversityStatisticalTest(int numberOfVariables, MultiMap map){
KolmogorovSmirnovTest kst = new KolmogorovSmirnovTest();
//MannWhitneyUTest kst = new MannWhitneyUTest();
for(int i=2;i<31;i+=1){
double []x = Arrays.copyOfRange(array, i*10-2*10, i*10-10);
double []y=Arrays.copyOfRange(array, i*10-10, i*10);
//System.out.println(Arrays.toString(x));
//System.out.println(Arrays.toString(y));
//double pValue=kst.kolmogorovSmirnovTest(x, y, false);
//double dValue = kst.kolmogorovSmirnovStatistic(x, y);
final double d = kst.kolmogorovSmirnovStatistic(y, x);
double p=kst.exactP(d, x.length, y.length, false);
//double p =kst.mannWhitneyUTest(x, y);
//String str = p;
map.put(i, p);
}
return map;
}
}<file_sep>FUN_cmoead and VAR_cmoead are FUN and VAR files generated by cMOEAD (a constrained version of moead).
parameters:
algorithm.setInputParameter("T", 20) ;
algorithm.setInputParameter("delta", 0.9) ;
algorithm.setInputParameter("nr", 2) ;
Crossover parameters:
Crossover: DifferentialEvolutionCrossover
parameters = new HashMap() ;
parameters.put("CR", 1.0) ;
parameters.put("F", 0.5) ;
Mutation parameter:
mutation: GeneralModifiedPolynomialMutationForEnergySystems
Boolean favorGenesforRE[] ={true, false, null, true, true, true };
Boolean favorGenesforConventionalPP[] ={false, null, true, null, false, false};
Boolean favorGenesforLFC[]={false, null, null, null, true, true};
Boolean favorGenesforESD[] ={true, false, false, true, null, true};
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForConventioanlPP", favorGenesforConventionalPP);
parameters.put("favorGenesForLFC",favorGenesforLFC );
parameters.put("favorGenesForESD",favorGenesforESD );
FUN_spea2:i and VAR_spea2:i are FUN and VAR files generated by spea2.
algorithm.setInputParameter("populationSize", 200);
algorithm.setInputParameter("maxEvaluations", 15000);
// for spea2
algorithm.setInputParameter("archiveSize",200);
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover",parameters);
parameters = new HashMap();
parameters.put("probability", 1.0 / problem.getNumberOfVariables());
parameters.put("distributionIndex", 10.0);
parameters.put("maximum generation", (int) algorithm.getInputParameter("maxEvaluations")/(int) algorithm.getInputParameter("populationSize")-1);
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> Ngas boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Ngas micro chp heat percentage
// index - 5 -> electrc car percentage
Boolean favorGenesforRE[] ={true, false, null, true, true, true };
Boolean favorGenesforConventionalPP[] ={false, null, true, null, false, false };
Boolean favorGenesforLFC[]={false, null, null, null, true, true};
Boolean favorGenesforESD[] ={true, false, false, true, null, true};
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForConventioanlPP", favorGenesforConventionalPP);
parameters.put("favorGenesForLFC",favorGenesforLFC );
parameters.put("favorGenesForESD",favorGenesforESD );
mutation = MutationFactory.getMutationOperator(
"GeneralModifiedPolynomialMutationForEnergySystems", parameters);
<file_sep>Problem: reet.fbk.eu.OptimizeEnergyPLANCIVIS.CEIS.Problem.EnergyPLANProblemCivisCEIS4D
Algorithm: EnergyPLANProblemCivisCEIS4D
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> Ngas boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
Boolean favorGenesforRE[] ={true, false, null, true, true };
Boolean favorGenesforConventionalPP[] ={false, null, null, true, false };
Boolean favorGenesforLFC[]={false, null, null, null, true};
Boolean favorGenesforESD[] ={true, false, false, true, true};
number of runs=3
algorithm.setInputParameter("populationSize", 150);
algorithm.setInputParameter("maxEvaluations", 11250);
// for spea2
algorithm.setInputParameter("archiveSize",150);
Crossover: SBX
Crossover probability: 0.9
Mutation: GeneralModifiedPolynomialMutationForEnergySystems
Mutation Probability : 1/5
Selection: BinaryTournament
Initialization:
Parameters regarding smal initialization:
theta = 6.0
MaxDistributionIndex = 3
numberOfIndevPerCombination = 3
numberOfRandomIndividuals=0
Stopping Criteria:
nGenLT=20
nGenUnCh=5
alpha=0.05<file_sep>package reet.fbk.eu.jmetal.initialization;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.FileHandler;
import jmetal.core.Algorithm;
import jmetal.core.Operator;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import reet.fbk.eu.jmetal.metaheuristics.nsgaII.NSGAIIForDK;
import reet.fbk.eu.jmetal.metaheuristics.nsgaII.NSGAIIForSI;
import reet.fbk.eu.jmetal.metaheuristics.nsgaII.NSGAIITrackIndicators;
import jmetal.metaheuristics.nsgaII.NSGAII;
import jmetal.operators.crossover.CrossoverFactory;
import jmetal.operators.selection.SelectionFactory;
import jmetal.qualityIndicator.QualityIndicator;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.RandomGenerator;
//import reet.fbk.eu.jmetal.operators.mutation.MutationFactory;
import jmetal.operators.mutation.MutationFactory;
import java.util.logging.Logger;
import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;
public class GenerateInitialIndividual {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
public static void main(String[] args) throws JMException,
SecurityException, IOException, ClassNotFoundException {
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
/*long seed[] = { 545454, 565656, 455885, 245454, 714451, 752453, 125742,
455411, 447551, 844545 };*/
//2nd list
/*long seed[] = { 144759,
271439,
445964,
494817,
530563,
724859,
746153,
747584,
866309,
938562};
*/
//3rd list
/*long seed[] = {
/* 172480,
242648,
268602,
272313,
412455,
441996,
633160,
814562,
822805,
843288
};*/
long seed[]={
125742,
144759,
172480,
242648,
245454,
268602,
271439,
272313,
412455,
441996,
445964,
447551,
455411,
455885,
494817,
530563,
545454,
565656,
633160,
714451,
724859,
746153,
747584,
752453,
814562,
822805,
843288,
844545,
866309,
938562
};
int numberOfRun = 30;
long initTime = System.currentTimeMillis();
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(seed[i]));
indicators = null;
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution(
"Real");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
Boolean favorGenesforRE[] = { true, true, true, true, true };
Boolean favorGenesforConventionalPP[] = { false, false, false,
false, false };
int populationSize = 100;
SolutionSet population;
/*
* Matlab Implementation
* MatlabProxyFactory factory;
MatlabProxy proxy;
factory = new MatlabProxyFactory();
try {
proxy = factory.getProxy();
DKInitialization dkini = new DKInitialization(problem,
favorGenesforRE, favorGenesforConventionalPP,
populationSize, 6.0, 3, 4, 0, proxy);
population = dkini.doDKInitialization();
} catch (MatlabConnectionException e) {
throw new JMException("Matlab connection problem");
} catch (MatlabInvocationException e) {
throw new JMException("Matlab function invocation problem");
}
population
.printVariablesToFile("InitializationResults/InitIndividualWithSI/WithoutRM/InitIndv_seed_"
+ seed[i]);*/
//Java implementation with contribution maximize
DKInitializationInJAVA dkini = new DKInitializationInJAVA(problem,
favorGenesforRE, favorGenesforConventionalPP,
populationSize, 6.0, 3, 4, 0);
population = dkini.doDKInitialization();
population
.printVariablesToFile("InitializationResults/InitIndividualWithSI/WithoutRM/DivMax/Test/InitIndv_seed_"
+ seed[i]);
}
long estimatedTime = System.currentTimeMillis() - initTime;
System.out.println("Total execution time: " + estimatedTime + "ms");
}
}
<file_sep>This is the results of 10 different runs with 10 different seed.
Polynomial mutation is applies with SBX crossover.
Population: 100
Evolution: 5000
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 4
Algorithm: NSGA-II
selection: Binary Tournament 2.
seed [] = {545782, 455875, 547945, 458478, 981354, 652262, 562366, 365652, 456545, 549235 };
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANTrentoProvince.Problem;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.util.JMException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import reet.fbk.eu.OptimizeEnergyPLANTrentoProvince.parseFile.EnergyPLANFileParseForTrentoProvince;
import reet.fbk.eu.OptimizeEnergyPLANTrentoProvince.util.ExtractEnergyPLANParametersTrentoProvinceV10;
import reet.fbk.eu.OptimizeEnergyPLANVdN.parseFile.EnergyPLANFileParseForVdN;
/*
* This is a problem file that is dealing with VdN (mainly introduction of electric cars)
*/
public class EnergyPLANProblemTrentoProvinceV10__ extends Problem {
static String inputs[] = { "PV_Cap", "Hydro_Cap", /*"Biomass_CHP_Cap", "NGas_CHP_Cap", "HP_Cap",
"Oil_boiler_Cap", "NGas_boiler_Cap", "Biomass_boiler_Cap", "SolarThermal", */
"NumberOfConCars", "NumberOfEVCars", "NumberOfFCEVCars", "Eloctrolyzer_Cap",
"ElecStorage_Turbine_Cap","ElecStorage_Pump_Cap", "ElecStorage_Storage_Cap" };
static String outputsinEnergyPLANMap[] = { "AnnualPVElectr.", "AnnualHH-CHPElectr.",
"AnnualHH-HPElectr.", "AnnualFlexibleElectr.", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualHH SolarHeat",
"AnnualImportElectr.", "AnnualExportElectr.", "Oil Consumption",
"Biomass Consumption", "Ngas Consumption",
/*"Gasoil/Diesel",
"Biomass",*/ "Bottleneck", "Electricity exchange",
"Variable costs", "Fixed operation costs", "AdditionalCost",
//"ConCarInvestmentCost","EVCarInvestmentCost","FCEVCarInvestmentCost",
"Annual Investment costs", "CO2Emission", "AnnualCost",
"oilBoilerFuelDemand", "ngasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualHH SolarHeat",
"transOilDemand",
"OilBoilerSolarInput", "NGasBoilerSolarInput","NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput",
/*"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization",
"Annual MaximumImportElectr.", "Annual MaximumExportElectr."*/};
static String outputsinFile[] = { "AnnualPV", "AnnualCHPelec",
"AnnualHPelec", "AnnualElecCar", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermalheat",
"AnnualImport", "AnnualExport", "OilConsumption",
"BiomassConsumption", "NGasConsuption",
/*"PetrolCost",
"BiomassCost",*/ "Bottleneck", "TotalElectricityExchangeCost",
"TotalVariableCost", "FixedOperationCosts", "AdditionalCost",
//"ConCarInvestmentCost","EVCarInvestmentCost","FCEVInvestmentCost",
"InvestmentCost","CO2-Emission", "AnnualCost",
"oilBoilerFuelDemand", "NGasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermal",
"transOilDemand",
"OilBoilerSolarInput", "NGasBoilerSolarInput", "NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput",
/*"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization",
"Annual MaximumImportElectr.", "Annual MaximumExportElectr."*/
};
static String inputUnits[] = { "MWe", "MWe", /*"MWe", "MWe", "MWth", "MWth", "MWth", "TWh",*/ "1000 units", "1000 units", "1000 units", "MWe", "MW", "MW", "GWh" };
static String outputUnits[] = { "TWh", "TWh", // "AnnualPV", "AnnualCHPelec",
"TWh", "TWh", "TWh", "TWh", "TWh", //"AnnualHPelec", "AnnualElecCar", "AnnualH2demand", "AnnualOilBoilerheat", "AnnualNGasBoilerheat",
"TWh", "TWh", "TWh", "TWh", "TWh", //"AnnualBiomassBoilerheat", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat", "AnnualHPheat", "AnnualSolarThermalheat",
"TWh", "TWh", "TWh", //"AnnualImport", "AnnualExport", "OilConsumption",
"TWh", "TWh", //"BiomassConsumption", "NGasConsuption",
/*"MEuro", //"DieselCost",
"MEuro",*/ "MEuro", //"BiomassCost", "TotalElectricityExchangeCost",
"MEuro", "MEuro", "MEuro", //"TotalVariableCost", "FixedOperationCosts", "AdditionalCost",
//"KEuro", "KEuro", "KEuro", //"ConCarInvestmentCost","EVCarInvestmentCost","FCEVInvestmentCost",
"MEuro", "Mt", "MEuro", //"InvestmentCost","CO2-Emission", "Total Local System Emission", "AnnualCost",
"TWh","TWh","TWh","TWh","TWh","TWh","TWh", //"oilBoilerFuelDemand", "NGasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualNgasmCHPheat", "AnnualBiomassmCHPheat, "AnnualHPheat", "AnnualSolarThermal",
"TWh", //"transOilDemand"
"TWh","TWh","TWh", "TWh","TWh","TWh", //"OilBoilerSolatInput", "NGasBoilerSolarInput","NGasCHPSolarInput", "BiomassBoilerSolarInput", "BiomassCHPSolarInput", "HPSolarInput"
/*"TWh","TWh","TWh", "TWh","TWh", //"OilBoilerUtilization", "NGasBoilerUtilization", "biomassBoilerSolarUtilization", "biomassCHPSolarUtilization", "HPSolarUtilization"
"MW", "MW"*/
};
ExtractEnergyPLANParametersTrentoProvinceV10 ex;
MultiMap energyplanmMap;
String simulatedYear, folder;
public static final int averageKMPerYearPerCar = 12900;
public static final double maxH2DemandInDistribution = 0.000209257;
public static final double sumH2DemandInDistribution = 1.0;
//transport
public long totalKMRunByCars ;
//other variable
public double totalHeatDemand;
public double DHHeatProduction;
//cars efficiencies
public double efficiencyConCar; // KWh/km
public double efficiencyEVCar; // KWh/km
public double efficiencyFCEVCar; // KWh/km
public double efficiencyBiomassCHPThermal;
public double efficiencynGasCHPThermal;
// H2
public double efficiencyElectrolyzerTrans;
public double oilBoilerEfficiency;
public double nGasBoilerEfficiency;
public double biomassBoilerEfficiency;
public double COP;
//grid distribution cost
public double elecGridDistributionCost;
//building envelop energy efficiency
double buildingEnvelopesEnergyEfficiency;
//number of heating element
int numberOfHeatingTechnologies = 6;
double upperBoundsHeat[];
double lowerBoundsHeat[];
//number of different types of cars
int numberOfDifferentTypesOfCars = 3;
long lowerBoundsTrans[];
long upperBoundsTrans[];
//electrical storage
double lowerBoundsElecStorage[];
double upperBoundsElecStorage[];
//Hydro capacity
double lowerBoundsHydroCap[];
double upperBoundsHydroCap[];
/**
* Creates a new instance of problem ZDT1.
*
* @param numberOfVariables
* Number of variables.
* @param solutionType
* The solution type must "Real", "BinaryReal, and "ArrayReal".
*/
public EnergyPLANProblemTrentoProvinceV10__(String solutionType, String simulatedYear,
String folder) {
this.simulatedYear=simulatedYear;
this.folder = folder;
numberOfVariables_ = 18;
numberOfObjectives_ = 2;
numberOfConstraints_ = 1;
problemName_ = "OptimizeEnergyPLANTrentoProvince";
upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];
// Establishes upper and lower limits for the variables
int var;
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
// index - 7 -> ICE cars
// index - 8 -> EV car parcentage
// index - 9 -> FCEV(H2) car percentage
// index -10 -> solar thermal percentage in oil boiler
// index -11 -> solar thermal percentage in nGas boiler
// index 12 -> solar thermal percentage in bnGas CHP
// index -13 -> solar thermal percentage in biomass boiler
// index -14 -> solar thermal percentage in biomass CHP
// index -15 -> solar thermal percentage in HP
//index -16 -> electrical storage capacity
//index 17 -> hydro capacity
if(simulatedYear.equals("2025")) {
// PV upper and lower limit
lowerLimit_[0] = 0.0;
upperLimit_[0] = 435.372;
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
lowerBoundsHeat= new double [] {0.000, 0.000, 0.000, 0.000, 0.000, 0.000};
upperBoundsHeat= new double [] {6.927, 6.927, 6.927, 1.392, 0.034, 6.927};
// index - 7 -> ICE cars
// index - 8 -> EV car parcentage
// index - 9 -> FCEV(H2) car percentage
lowerBoundsTrans= new long [] {0000000000L, 0000000000L, 0000000000L };
upperBoundsTrans= new long [] {9821000000L, 9821000000L, 9821000000L };
//index -16 -> electrical storage capacity
lowerBoundsElecStorage= new double [] { 0.000};
upperBoundsElecStorage= new double [] { 1.741 };
//index -17-> hydro capacity
lowerBoundsHydroCap= new double [] { 0.000};
upperBoundsHydroCap= new double [] { 1748.439 };
}else if(simulatedYear.equals("2030")) {
// PV upper and lower limit
lowerLimit_[0] = 0.0;
upperLimit_[0] = 658.627;
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
lowerBoundsHeat= new double [] {0.000, 0.000, 0.000, 0.000, 0.000, 0.000};
upperBoundsHeat= new double [] {6.888, 6.888, 6.888, 1.384, 0.038, 6.888};
// index - 7 -> ICE cars
// index - 8 -> EV car parcentage
// index - 9 -> FCEV(H2) car percentage
lowerBoundsTrans= new long [] {00000000000L, 00000000000L, 00000000000L };
upperBoundsTrans= new long [] {10071000000L, 10071000000L, 10071000000L };
//index -16 -> electrical storage capacity
lowerBoundsElecStorage= new double [] { 0.000};
upperBoundsElecStorage= new double [] { 2.635 };
//index -17-> hydro capacity
lowerBoundsHydroCap= new double [] { 0.000};
upperBoundsHydroCap= new double [] { 1753.920 };
}else if(simulatedYear.equals("2050")) {
// PV upper and lower limit
lowerLimit_[0] = 0.0;
upperLimit_[0] = 1380.453;
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
lowerBoundsHeat= new double [] {0.000, 0.000, 0.000, 0.000, 0.000, 0.000};
upperBoundsHeat= new double [] {6.408, 6.408, 6.408, 1.288, 0.044, 6.408};
// index - 7 -> ICE cars
// index - 8 -> EV car parcentage
// index - 9 -> FCEV(H2) car percentage
lowerBoundsTrans= new long [] {00000000000L, 00000000000L, 00000000000L };
upperBoundsTrans= new long [] {10700000000L, 10700000000L, 10700000000L };
//index -16 -> electrical storage capacity
lowerBoundsElecStorage= new double [] { 0.000};
upperBoundsElecStorage= new double [] { 5.522 };
//index -17-> hydro capacity
lowerBoundsHydroCap= new double [] { 0.000};
upperBoundsHydroCap= new double [] { 1877.934 };
}
// other are the percentage from limit [0,1]
for (var = 1; var <=6; var++) {
lowerLimit_[var] = lowerBoundsHeat[var-1];
upperLimit_[var] = upperBoundsHeat[var-1];
} // for
// other are the percentage from limit [0,1]
for (int i = 7; i <=9; i++) {
lowerLimit_[i] = (double) lowerBoundsTrans[i-7];
upperLimit_[i] = (double) upperBoundsTrans[i-7];
} // for
for (int i = 10; i <=15; i++) {
lowerLimit_[i] = 0.0;
upperLimit_[i] = 1.0;
}
lowerLimit_[16] = lowerBoundsElecStorage[0];
upperLimit_[16] = upperBoundsElecStorage[0];
lowerLimit_[17] = lowerBoundsHydroCap[0];
upperLimit_[17] = upperBoundsHydroCap[0];
if (solutionType.compareTo("Real") == 0)
solutionType_ = new RealSolutionType(this);
else {
System.out.println("Error: solution type " + solutionType
+ " invalid");
System.exit(-1);
}
if(this.simulatedYear.equals("2025")){
// Heat
totalHeatDemand = 6.927; // in TWh
DHHeatProduction = 0.234; // in TWh
//cars
efficiencyConCar = 0.498; // KWh/km
efficiencyFCEVCar = 0.329; // KWh/km
efficiencyEVCar = 0.142; // Kwh/km
totalKMRunByCars = 9821000000L;
efficiencynGasCHPThermal = 0.47;
efficiencyBiomassCHPThermal = 0.47;
oilBoilerEfficiency = 0.86;
nGasBoilerEfficiency = 0.96;
biomassBoilerEfficiency = 0.77;
COP = 3.35;
// H2
efficiencyElectrolyzerTrans = 0.7173;
elecGridDistributionCost = 191.01;
buildingEnvelopesEnergyEfficiency = 1077117 ; //MWh
}
else if(this.simulatedYear.equals("2030")){
// Heat
totalHeatDemand = 6.888; // in TWh
DHHeatProduction = 0.233; // in TWh
//cars
efficiencyConCar = 0.460; // KWh/km
efficiencyFCEVCar = 0.299; // KWh/km
efficiencyEVCar = 0.133; // Kwh/km
totalKMRunByCars = 10071000000L;
efficiencynGasCHPThermal = 0.48;
efficiencyBiomassCHPThermal = 0.48;
oilBoilerEfficiency = 0.87;
nGasBoilerEfficiency = 0.97;
biomassBoilerEfficiency = 0.78;
COP = 3.44;
// H2
efficiencyElectrolyzerTrans = 0.7217;
elecGridDistributionCost = 213.61;
buildingEnvelopesEnergyEfficiency = 1147372;
}else if(this.simulatedYear.equals("2050")){
// Heat
totalHeatDemand = 6.408; // in TWh
DHHeatProduction = 0.217; // in TWh
//cars
efficiencyConCar = 0.340; // KWh/km
efficiencyFCEVCar = 0.226; // KWh/km
efficiencyEVCar = 0.106; // Kwh/km
totalKMRunByCars = 10700000000L;
efficiencynGasCHPThermal = 0.50;
efficiencyBiomassCHPThermal = 0.50;
oilBoilerEfficiency = 0.88;
nGasBoilerEfficiency = 0.98;
biomassBoilerEfficiency = 0.80;
COP = 3.75;
// H2
efficiencyElectrolyzerTrans = 0.7535;
elecGridDistributionCost = 236.31;
buildingEnvelopesEnergyEfficiency = 1363980;
}
ex = new ExtractEnergyPLANParametersTrentoProvinceV10(simulatedYear);
try {
ex.readProfiles();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // constructor end
/**
* Evalua tes a solution.
*
* @param solution
* The solution to evaluate.
* @throws JMException
*/
@SuppressWarnings("unchecked")
public void evaluate(Solution solution) throws JMException {
MultiMap modifyMap = new MultiValueMap();
// decision variables
// index - 0 -> PV Capacity
// index - 7 -> ICE cars
// index - 8 -> EV car parcentage
// index - 9 -> FCEV(H2) car percentage
// index -10 -> solar thermal percentage in oil boiler
// index -11 -> solar thermal percentage in nGas boiler
// index 12 -> solar thermal percentage in bnGas CHP
// index -13 -> solar thermal percentage in biomass boiler
// index -14 -> solar thermal percentage in biomass CHP
// index -15 -> solar thermal percentage in HP
// index 16 -> electrical storage
// index 17 -> hydro capacity
// PV
double pv = solution.getDecisionVariables()[0].getValue();
repairHeatVariables(solution);
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
double oilBoilerHeatDemand = solution.getDecisionVariables()[1].getValue();
double nGasBoilerHeatDemand = solution.getDecisionVariables()[2].getValue();
double nGasCHPHeatDemand = solution.getDecisionVariables()[3].getValue();
double biomassBoilerHeatDemand = solution.getDecisionVariables()[4].getValue();
double biomassCHPHeatDemand = solution.getDecisionVariables()[5].getValue();
double hpHeatDemand = solution.getDecisionVariables()[6].getValue();
repairTransVariables(solution);
double totalKMRunByConCar = (long) solution.getDecisionVariables()[7].getValue();
double totalKMRunByEVCar = (long) solution.getDecisionVariables()[8].getValue();
double totalKMRunByFCEVCar = (long) solution.getDecisionVariables()[9].getValue();
double totalPetrolDemandInTWhForTrns = totalKMRunByConCar
* efficiencyConCar / Math.pow(10, 9);
double totalElecDemandInTWhForTrns = totalKMRunByEVCar
* efficiencyEVCar / Math.pow(10, 9);
double totalH2DemandInTWhForTrns = totalKMRunByFCEVCar
* efficiencyFCEVCar / Math.pow(10, 9);
// solar thermal percentage
double oilBoilerSolarPercentage = solution.getDecisionVariables()[10]
.getValue();
double nGasBoilerSolarPercentage = solution.getDecisionVariables()[11]
.getValue();
double nGasCHPSolarPercentage = solution.getDecisionVariables()[12]
.getValue();
double biomassBoilerSolarPercentage = solution.getDecisionVariables()[13]
.getValue();
double biomassCHPSolarPercentage = solution.getDecisionVariables()[14]
.getValue();
double hpSolarPercentage = solution.getDecisionVariables()[15]
.getValue();
//electrical storage
double elecStorageCapacity = solution.getDecisionVariables()[16]
.getValue();
//hydro capacity
double hydroCapacity = solution.getDecisionVariables()[17]
.getValue();
try{
modifyMap = writeIntoInputFile(pv, oilBoilerHeatDemand,
nGasBoilerHeatDemand, nGasCHPHeatDemand,
biomassBoilerHeatDemand, biomassCHPHeatDemand,
hpHeatDemand,
totalPetrolDemandInTWhForTrns, totalElecDemandInTWhForTrns,
totalH2DemandInTWhForTrns, oilBoilerSolarPercentage,
nGasBoilerSolarPercentage, biomassBoilerSolarPercentage,
nGasCHPSolarPercentage, biomassCHPSolarPercentage, hpSolarPercentage, elecStorageCapacity, hydroCapacity);
}catch(IOException e){
System.out.print("Pobrlem writting in modified Input file");
}
String energyPLANrunCommand = ".\\EnergyPLAN_12.3\\EnergyPLAN.exe -i "
+ "\".\\modifiedInput.txt\" "
+ "-ascii \"result.txt\" ";
try{
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
EnergyPLANFileParseForTrentoProvince epfp = new EnergyPLANFileParseForTrentoProvince(
".\\result.txt");
energyplanmMap = epfp.parseFile();
energyplanmMap.putAll(modifyMap);
Iterator it;
Collection<String> col;
// objective # 1
col = (Collection<String>) energyplanmMap
.get("CO2-emission (total)");
it = col.iterator();
double localCO2emission = Double.parseDouble(it.next().toString());
//extract import
col = (Collection<String>) energyplanmMap
.get("AnnualImportElectr.");
it = col.iterator();
double elecImport = Double.parseDouble(it.next().toString());
double co2InImportedEleOil = 0.0, co2InImportedEleNGas=0.0;
if(simulatedYear.equals("2025")) {
co2InImportedEleOil =( (elecImport/0.51 *1.83/100) * 0.267 );
co2InImportedEleNGas =( (elecImport/0.51 *47.96/100) * 0.202);
}else if(simulatedYear.equals("2030")) {
co2InImportedEleOil =( (elecImport/0.53 *0.66/100) * 0.267 );
co2InImportedEleNGas =( (elecImport/0.53 *43.94/100) * 0.202 );
}else if(simulatedYear.equals("2050")) {
co2InImportedEleNGas =( (elecImport/0.56 *12/100) * 0.202 );
}
localCO2emission = localCO2emission + co2InImportedEleOil + co2InImportedEleNGas;
energyplanmMap.put("CO2Emission", localCO2emission);
solution.setObjective(0,localCO2emission);
// objective # 2
col = (Collection<String>) energyplanmMap.get("Variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanmMap.get("Bottleneck");
it = col.iterator();
String bottleneckStr = it.next().toString();
double bottlenack = Double.parseDouble(bottleneckStr);
energyplanmMap.put("Bottleneck", localCO2emission);
totalVariableCost -= bottlenack;
col = (Collection<String>) energyplanmMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
// extract
col = (Collection<String>) energyplanmMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
double investmentCost = Double.parseDouble(invest);
//calculation of additional cost
//read annual electricity demand
col = (Collection<String>) energyplanmMap.get("AnnualElectr.Demand");
it = col.iterator();
String fixedElecDemandStr = it.next().toString();
double fixedElecDemand = Double.parseDouble(fixedElecDemandStr);
//read HP electric demand
col = (Collection<String>) energyplanmMap.get("AnnualHH-HPElectr.");
it = col.iterator();
String HPElecDemandStr = it.next().toString();
double HPElecDemand = Double.parseDouble(HPElecDemandStr);
//read electrolyzer elec uses
col = (Collection<String>) energyplanmMap.get("AnnualTrans H2Electr.");
it = col.iterator();
String ElectrolyzerElecDemandStr = it.next().toString();
double electrolyzerElecDemand = Double.parseDouble(ElectrolyzerElecDemandStr);
//read pump elec uses
col = (Collection<String>) energyplanmMap.get("AnnualPumpElectr.");
it = col.iterator();
String pumpElectricStr = it.next().toString();
double pumpElectric = Double.parseDouble(pumpElectricStr);
//calculate Transportation electricity demand which is totalElecDemandInTWhForTrns
//variable cost
double additionalVariableCost = (fixedElecDemand + HPElecDemand + totalElecDemandInTWhForTrns+electrolyzerElecDemand
+ pumpElectric)*elecGridDistributionCost;
//fixed operational cost
double additionalFixedOperationalCost = DHHeatProduction*3600*0.145/100*0.76;
//annual invesment cost
double additionalAnnaulInvestmentCost = (DHHeatProduction *3600* 0.145 /40)+
(DHHeatProduction *3600* 0.145 /40/100*6)+
(buildingEnvelopesEnergyEfficiency*0.0033/30)+
(buildingEnvelopesEnergyEfficiency* 0.0033 /30/100*6);
double totalAdditionalCost = additionalAnnaulInvestmentCost + additionalFixedOperationalCost
+additionalVariableCost;
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ investmentCost + totalAdditionalCost;
energyplanmMap.put("AdditionalCost", totalAdditionalCost);
energyplanmMap.put("AnnualCost", actualAnnualCost);
solution.setObjective(1, actualAnnualCost);
col = (Collection<String>) energyplanmMap.get("AnnualOilBoilerheat");
it = col.iterator();
double AnnualOilBoilerheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("OilBoilerSolarInput");
it = col.iterator();
double OilBoilerSolarInput = Double.parseDouble(it.next().toString());
double OilBoilerUtilization = ex.solarUtilizationCalculation(AnnualOilBoilerheat, OilBoilerSolarInput);
energyplanmMap.put("OilBoilerUtilization", OilBoilerUtilization);
col = (Collection<String>) energyplanmMap.get("AnnualNGasBoilerheat");
it = col.iterator();
double AnnualNGasBoilerheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("NGasBoilerSolarInput");
it = col.iterator();
double NGasBoilerInput = Double.parseDouble(it.next().toString());
double NGasBoilerUtilization = ex.solarUtilizationCalculation(AnnualNGasBoilerheat, NGasBoilerInput);
energyplanmMap.put("NGasBoilerUtilization", NGasBoilerUtilization);
col = (Collection<String>) energyplanmMap.get("AnnualBiomassBoilerheat");
it = col.iterator();
double AnnualBiomassBoilerheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("BiomassBoilerSolarInput");
it = col.iterator();
double BiomassBoilerSolarInput = Double.parseDouble(it.next().toString());
double biomassBoilerSolarUtilization = ex.solarUtilizationCalculation(AnnualBiomassBoilerheat, BiomassBoilerSolarInput);
energyplanmMap.put("biomassBoilerSolarUtilization", biomassBoilerSolarUtilization);
col = (Collection<String>) energyplanmMap.get("AnnualNgasmCHPheat");
it = col.iterator();
double AnnualNgasmCHPheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("NGasCHPSolarInput");
it = col.iterator();
double nGasCHPSolarInput = Double.parseDouble(it.next().toString());
double nGasCHPSolarUtilization = ex.solarUtilizationCalculation(AnnualNgasmCHPheat, nGasCHPSolarInput);
energyplanmMap.put("NgasCHPSolarUtilization", nGasCHPSolarUtilization);
col = (Collection<String>) energyplanmMap.get("AnnualBiomassmCHPheat");
it = col.iterator();
double AnnualBiomassmCHPheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("BiomassCHPSolarInput");
it = col.iterator();
double BiomassCHPSolarInput = Double.parseDouble(it.next().toString());
double biomassCHPSolarUtilization = ex.solarUtilizationCalculation(AnnualBiomassmCHPheat, BiomassCHPSolarInput);
energyplanmMap.put("biomassCHPSolarUtilization", biomassCHPSolarUtilization);
col = (Collection<String>) energyplanmMap.get("AnnualHPheat");
it = col.iterator();
double AnnualHPheat = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("HPSolarInput");
it = col.iterator();
double HPSolarInput = Double.parseDouble(it.next().toString());
double HPSolarUtilization = ex.solarUtilizationCalculation(AnnualHPheat, HPSolarInput);
energyplanmMap.put("HPSolarUtilization", HPSolarUtilization);
this.evaluateConstraints(solution);
if(solution.getOverallConstraintViolation()>=0) {
String line="";
for(int i=0;i<solution.numberOfVariables();i++) {
line = line + " " +solution.getDecisionVariables()[i];
}
//MultiMap energyplanmMapForSimulation;
//energyplanmMapForSimulation = ex.simulateEnergyPLAN(line);
try {
ex.WriteEnergyPLANParametersFromEvaluateToFile(energyplanmMap, folder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// check warning
/*col = (Collection<String>) energyplanmMap.get("WARNING");
if (col != null) {
@SuppressWarnings("rawtypes")
Iterator it3 = col.iterator();
String warning = it3.next().toString();
if (!warning.equals("PP too small. Critical import is needed")
&& !warning
.equals("Grid Stabilisation requierments are NOT fullfilled")
&& !warning
.equals("Critical Excess Electricity Production"))
throw new IOException("warning!!" + warning);
// System.out.println("Warning " + it3.next().toString());
}
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}*/
}
@SuppressWarnings("unchecked")
public void evaluateConstraints(Solution solution) throws JMException {
Iterator it;
Collection<String> col;
// constraints about heat3-balance: balance<=0
col = (Collection<String>) energyplanmMap.get("Biomass Consumption");
it = col.iterator();
double annualBiomassConsumption = Double.parseDouble(it.next()
.toString());
double constraints[] = new double[numberOfConstraints_];
constraints[0] = 2.46 - annualBiomassConsumption;
double totalViolation = 0.0;
int numberOfViolation = 0;
for (int i = 0; i < numberOfConstraints_; i++) {
if (constraints[i] < 0.0) {
totalViolation += constraints[0];
numberOfViolation++;
}
}
solution.setOverallConstraintViolation(totalViolation);
solution.setNumberOfViolatedConstraint(numberOfViolation);
}
MultiMap writeIntoInputFile(double pv, double oilBoilerHeatDemand,
double nGasBoilerHeatDemand, double nGasCHPHeatDemand,
double biomassBoilerHeatDemand,
double biomassCHPHeatDemand, double hpHeatDemand,
double totalPetrolDemandInTWhForTrns,
double totalElecDemandInTWhForTrns,
double totalH2DemandInTWhForTrns, double oilBoilerSolarPercentage,
double nGasBoilerSolarPercentage, double biomassBoilerSolarPercentage,
double nGasCHPSolarPercentage, double biomassCHPSolarPercentage, double hpSolarPercentage,
double elecStorageCapacity, double hydroCapacity)
throws IOException {
// decision variables
// index - 0 -> PV Capacity
// index - 1 -> oil boiler heat percentage
// index - 2 -> nGas boiler heat percentage
// index - 3 -> nGas micro chp heat percentage
// index - 4 -> Biomass boiler heat percentage
// index - 5 -> Biomass micro chp heat percentage
// index 6 -> individual HP percentage
// index - 6 -> EV car parcentage
// index - 7 -> FCEV(H2) car percentage
//last percentage goes to conventional car
// index -8 -> solar thermal percentage in oil boiler
// index -9 -> solar thermal percentage in nGas boiler
// index 10 -> solar thermal percentage in bnGas CHP
// index -11 -> solar thermal percentage in biomass boiler
// index -12 -> solar thermal percentage in biomass CHP
// index -13 -> solar thermal percentage in HP
// index -14 -> solar thermal percentage in biomass CHP
// index -15 -> solar thermal percentage in HP
// index 16 -> electrical storage
// index 17 -> hydro capacity
MultiMap modifyMap = new MultiValueMap();
modifyMap.put("AnnualOilBoilerheat",
Math.round(oilBoilerHeatDemand * 100.0) / 100.0); //this is done for 2 decimal place precision
modifyMap.put("AnnualNGasBoilerheat",
Math.round(nGasBoilerHeatDemand * 100.0) / 100.0);
modifyMap.put("AnnualBiomassBoilerheat",
Math.round(biomassBoilerHeatDemand * 100.0) / 100.0);
modifyMap.put("AnnualNgasmCHPheat",
Math.round(nGasCHPHeatDemand * 100.0) / 100.0);
modifyMap.put("AnnualBiomassmCHPheat",
Math.round(biomassCHPHeatDemand * 100.0) / 100.0);
modifyMap.put("AnnualHPheat", Math.round(hpHeatDemand * 100.0) / 100.0);
modifyMap.put("PV_Cap", (int) Math.round(pv));
modifyMap.put("Hydro_Cap", (int) Math.round(hydroCapacity));
String modifiedParameters[] = { "input_RES1_capacity=", // pv (0)
"input_fuel_Households[2]=", // oil boiler (1)
"input_HH_oilboiler_Solar=", // oil Solar Thermal (2)
"input_fuel_Households[3]=", // nGas boiler (3)
"input_HH_ngasboiler_Solar=", // nGas boiler Solar Thermal (4)
"input_HH_NgasCHP_heat=", // nGas micro chp (5)
"input_HH_NgasCHP_solar=", // nGas microp chp solar (6)
"input_fuel_Households[4]=", // bioMass boiler (7)
"input_HH_bioboiler_Solar=", // biomas boiler Solar thermal (8)
"input_HH_BioCHP_heat=", // biomass CHP (9)
"input_HH_BioCHP_solar=", // biomass CHP Solar thermal (10)
"input_HH_HP_heat=", // HP (11)
"input_HH_HP_solar=", // HP Solar thermal (12)
"input_fuel_Transport[5]=", // Petrol demand (13)
"Input_Size_transport_conventional_cars=", // number of convensional cars (14)
"input_transport_TWh=", // EV car electricity demand (15)
"Input_Size_transport_electric_cars=", // number of electric car (16)
"input_fuel_Transport[6]=", // hydrogen demand for Transport (17)
"Input_Size_transport_other_vehicles1=", // number of FCEV car (18)
"input_cap_ELTtrans_el=", // //corresponding eletrolyzer capacity (19)
"input_cap_pump_el=", //Pump capacity (20)
"input_cap_turbine_el=", //turbine capacity (21)
"input_cap_turbine_el=", // elec storage capacity (22)
"input_hydro_cap=", //hydro capacity (23)
"input_hydro_watersupply=" //hydro water supply
};
String cooresPondingValues[] = new String[modifiedParameters.length];
File modifiedInput = new File("modifiedInput.txt");
if (modifiedInput.exists()) {
modifiedInput.delete();
}
modifiedInput.createNewFile();
FileWriter fw = new FileWriter(modifiedInput.getAbsoluteFile());
BufferedWriter modifiedInputbw = new BufferedWriter(fw);
String path="";
if(simulatedYear.equals("2025") ){
path =".\\EnergyPLAN_12.3\\energyPlan Data\\Data\\PEAP\\PEAP_PAT_LC_2025_DH_v10_opt.txt";
}else if(simulatedYear.equals("2030") ){
path =".\\EnergyPLAN_12.3\\energyPlan Data\\Data\\PEAP\\PEAP_PAT_LC_2030_DH_v10_opt.txt";
}else if(simulatedYear.equals("2050")) {
path =".\\EnergyPLAN_12.3\\energyPlan Data\\Data\\PEAP\\PEAP_PAT_LC_2050_DH_v10_opt.txt";
}
BufferedReader mainInputbr = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"));
double totalSolarThermalInput=0.0;
cooresPondingValues[0] = "" + pv;
double oilBoilerFuelDemand = oilBoilerHeatDemand / oilBoilerEfficiency;
cooresPondingValues[1] = "" + oilBoilerFuelDemand;
modifyMap.put("oilBoilerFuelDemand", oilBoilerFuelDemand);
double oilBoilerSolarThermal = oilBoilerFuelDemand * oilBoilerSolarPercentage;
cooresPondingValues[2] = "" + oilBoilerSolarThermal;
totalSolarThermalInput+=oilBoilerSolarThermal;
modifyMap.put("OilBoilerSolarInput", oilBoilerSolarThermal);
double nGasBoilerFuelDemand = nGasBoilerHeatDemand / nGasBoilerEfficiency;
cooresPondingValues[3] = "" + nGasBoilerFuelDemand;
modifyMap.put("ngasBoilerFuelDemand", nGasBoilerFuelDemand);
double nGasBoilerSolarThermal = nGasBoilerFuelDemand * nGasBoilerSolarPercentage;
cooresPondingValues[4] = "" + nGasBoilerSolarThermal;
totalSolarThermalInput+=nGasBoilerSolarThermal;
modifyMap.put("NGasBoilerSolarInput", nGasBoilerSolarThermal);
cooresPondingValues[5] = "" + nGasCHPHeatDemand;
double nGasCHPSolarThermal = nGasCHPHeatDemand * efficiencynGasCHPThermal * nGasCHPSolarPercentage;
cooresPondingValues[6] = "" + nGasCHPSolarThermal;
totalSolarThermalInput+=nGasCHPSolarThermal;
modifyMap.put("NGasCHPSolarInput", nGasCHPSolarThermal);
double biomassBoilerFuelDemand = biomassBoilerHeatDemand / biomassBoilerEfficiency;
cooresPondingValues[7] = "" + biomassBoilerFuelDemand;
modifyMap.put("biomassBoilerFuelDemand", biomassBoilerFuelDemand);
double biomassBoilerSolarThermal = biomassBoilerFuelDemand * biomassBoilerSolarPercentage;
cooresPondingValues[8] = "" + biomassBoilerSolarThermal;
totalSolarThermalInput+=biomassBoilerSolarThermal;
modifyMap.put("BiomassBoilerSolarInput", biomassBoilerSolarThermal);
cooresPondingValues[9] = "" + biomassCHPHeatDemand;
double biomassCHPSolarThermal = biomassCHPHeatDemand * efficiencyBiomassCHPThermal *
biomassCHPSolarPercentage;
cooresPondingValues[10] = "" + biomassCHPSolarThermal;
totalSolarThermalInput+=biomassCHPSolarThermal;
modifyMap.put("BiomassCHPSolarInput", biomassCHPSolarThermal);
cooresPondingValues[11] = "" + hpHeatDemand;
double hpSolarThermal = hpHeatDemand* hpSolarPercentage;
cooresPondingValues[12] = "" + hpSolarThermal;
totalSolarThermalInput+=hpSolarThermal;
modifyMap.put("HPSolarInput", hpSolarThermal);
modifyMap.put("SolarThermal", totalSolarThermalInput);
cooresPondingValues[13] = "" + totalPetrolDemandInTWhForTrns;
modifyMap.put("transOilDemand", totalPetrolDemandInTWhForTrns);
double numberOfConCars = (totalPetrolDemandInTWhForTrns * Math.pow(10, 9))
/ (efficiencyConCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[14] = "" + numberOfConCars;
modifyMap.put("NumberOfConCars", numberOfConCars);
cooresPondingValues[15] = "" + totalElecDemandInTWhForTrns;
double numberOfEVCars = totalElecDemandInTWhForTrns * Math.pow(10, 9)
/ (efficiencyEVCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[16] = "" + numberOfEVCars;
modifyMap.put("NumberOfEVCars", numberOfEVCars);
cooresPondingValues[17] = "" + totalH2DemandInTWhForTrns;
modifyMap.put("AnnualH2demand", totalH2DemandInTWhForTrns);
double numberOfFCEVCars = totalH2DemandInTWhForTrns
* Math.pow(10, 9)
/ (efficiencyFCEVCar * averageKMPerYearPerCar * Math.pow(10, 3));
cooresPondingValues[18] = "" + numberOfFCEVCars;
modifyMap.put("NumberOfFCEVCars", numberOfFCEVCars);
double electrolyzerCapacity = (int) Math.floor(maxH2DemandInDistribution
* totalH2DemandInTWhForTrns * Math.pow(10, 6)
/ (efficiencyElectrolyzerTrans * sumH2DemandInDistribution))+1;
cooresPondingValues[19] = "" + electrolyzerCapacity;
modifyMap.put("Eloctrolyzer_Cap", electrolyzerCapacity);
cooresPondingValues[20] = "" + elecStorageCapacity * 1000 / 2;
modifyMap.put("ElecStorage_Turbine_Cap", elecStorageCapacity * 1000 / 2);
cooresPondingValues[21] = "" + elecStorageCapacity * 1000 / 2;
modifyMap.put("ElecStorage_Pump_Cap", elecStorageCapacity * 1000 / 2);
cooresPondingValues[22] = "" + elecStorageCapacity;
modifyMap.put("ElecStorage_Storage_Cap", elecStorageCapacity);
cooresPondingValues[23] = ""+hydroCapacity;
cooresPondingValues[24] = ""+hydroCapacity*0.002664;
String line;
while ((line = mainInputbr.readLine()) != null) {
line.trim();
boolean trackBreak=false;
for (int i = 0; i < modifiedParameters.length; i++) {
if (line.startsWith(modifiedParameters[i]) || line.endsWith(modifiedParameters[i])) {
modifiedInputbw.write(line+"\n" );
line = mainInputbr.readLine();
line=line.replace(line, cooresPondingValues[i]);
modifiedInputbw.write(line+"\n");
trackBreak=true;
break;
}
}
if(trackBreak)
continue;
else
modifiedInputbw.write(line+"\n");
}
modifiedInputbw.close();
mainInputbr.close();
return modifyMap;
}
void repairHeatVariables(Solution s) {
double ranges[] = new double[numberOfHeatingTechnologies];
for(int i=0;i<ranges.length;i++) {
ranges[i] = upperBoundsHeat[i]-lowerBoundsHeat[i];
}
double array[] = new double[lowerBoundsHeat.length];
for(int i=0;i<numberOfHeatingTechnologies;i++) {
try {
array[i]= s.getDecisionVariables()[i+1].getValue();
} catch (JMException e) {
System.out.println("something wrone in heat calculation");
}
}
while(Math.abs(addArray(array) - totalHeatDemand) >0.005) {
double arraySum = addArray(array);
if(arraySum>totalHeatDemand) {
//we need to reduce from each technology
for(int i=0;i<array.length;i++) {
double reduceForThisTech = (arraySum-totalHeatDemand)*ranges[i]/addArray(ranges);
if((array[i] - reduceForThisTech) < lowerBoundsHeat[i]) {
array[i] = lowerBoundsHeat[i];
}else {
array[i]=array[i]-reduceForThisTech;
}
}
}else {
//we need to increase from each technology
for(int i=0;i<array.length;i++) {
double increaseForThisTech = (totalHeatDemand-arraySum)*ranges[i]/addArray(ranges);
if((array[i] + increaseForThisTech) > upperBoundsHeat[i]) {
array[i] = upperBoundsHeat[i];
}else {
array[i]=array[i]+increaseForThisTech;
}
}
}
}
for (int i = 0; i < numberOfHeatingTechnologies; i++) {
try {
s.getDecisionVariables()[i+1].setValue(array[i ]);
} catch (JMException e) {
System.out.println("something wrone in heat calculation");
}
}
}
void repairTransVariables(Solution s) {
long ranges[] = new long[lowerBoundsTrans.length];
for(int i=0;i<ranges.length;i++) {
ranges[i] = upperBoundsTrans[i]-lowerBoundsTrans[i];
}
long array[] = new long[lowerBoundsTrans.length];
for(int i=0;i<numberOfDifferentTypesOfCars;i++) {
try {
array[i]= (long) s.getDecisionVariables()[i+7].getValue();
} catch (JMException e) {
System.out.println("something wrone in trans repair");
}
}
while(Math.abs(addArray(array) - totalKMRunByCars) >10) {
long arraySum = addArray(array);
if(arraySum>totalKMRunByCars) {
//we need to decrease from each technology
for(int i=0;i<array.length;i++) {
BigInteger a = new BigInteger(Long.toString(arraySum-totalKMRunByCars));
BigInteger b = new BigInteger(Long.toString(ranges[i]));
BigInteger c = a.multiply(b);
BigInteger d = new BigInteger(Long.toString(addArray(ranges)));
BigInteger e = c.divide(d);
long reduceForThisTech = e.longValue();
if((array[i] - reduceForThisTech) < lowerBoundsTrans[i]) {
array[i] = lowerBoundsTrans[i];
}else {
array[i]=array[i]-reduceForThisTech;
}
}
}else {
//we need to increase from each technology
for(int i=0;i<array.length;i++) {
BigInteger a = new BigInteger(Long.toString( totalKMRunByCars-arraySum ));
BigInteger b = new BigInteger(Long.toString(ranges[i]));
BigInteger c = a.multiply(b);
BigInteger d = new BigInteger(Long.toString(addArray(ranges)));
BigInteger e = c.divide(d);
long increaseForThisTech = e.longValue();
if((array[i] + increaseForThisTech) > upperBoundsTrans[i]) {
array[i] = upperBoundsTrans[i];
}else {
array[i]=array[i]+increaseForThisTech;
}
}
}
}
for (int i = 0; i < numberOfDifferentTypesOfCars; i++) {
try {
s.getDecisionVariables()[i+7].setValue(array[i ]);
} catch (JMException e) {
System.out.println("something wrone in heat calculation");
}
}
}
static double addArray(double []arr) {
double sum=0.0;
for(int i=0;i<arr.length;i++) {
sum+=arr[i];
}
return sum;
}
static long addArray(long []arr) {
long sum=0L;
for(int i=0;i<arr.length;i++) {
sum+=arr[i];
}
return sum;
}
}
<file_sep>All the Pareto fronts found in 240 different runs are merged. Here, all the results considred the mutation probability 0.2. And new Pareto front is built.
mergeFUN_N_M0.2: all Pareto front from 30 runs with NSGAII
mergeFUN_NSI_WRM_M0.2: all Pareto front from 30 runs with NSGAII with smart inililization without random individuals
mergeFUN_S_M0.2: all Pareto front from 30 runs with SPEA2
mergeFUN_SSI_WRM_M0.2: all Pareto front from 30 runs with SPEA2 with smart inililization without random individuals
mergeFUN_NDK: all Pareto front from 30 runs with NSGAII with DK/smart mutation
mergeFUN_SDK: all Pareto front from 30 runs with SPEA2 with DK/smart mutation
mergeFUN_NInt_WRM: all Pareto front from 30 runs with NSGAII with integrated/combined approach without random individuals in initialization phase
mergeFUN_SInt_WRM: all Pareto front from 30 runs with SPEA2 with integrated/combined approach without random individuals in initialization phase
mergeFUN: merge mergeFUN_*
mergeFUN.pf: Pareto front after merging smart initializzation+ DK/smart mutation+integratedMOEA results
<file_sep>[DocHistory]
FileCount=1
File0=energyPlan Data\Data\Aalborg2050_vision.txt
<file_sep>In the simulation we want to replace all the individual boilers using district heating. District heating contains CHP, HP and boilers. There are alos eletroliser for district heating where excess electricity from PV can be converted to H2 and use the H2 as CHP fuel.
In the first stage, boiler capacity is very high (17500 KJ/s, KW). In the second stage, the boiler capacity is fixed by using maximul use of boiler.
Decision variables:
0-> chp2 1 -> hp2 2 -> pv capacity
Objectives:
0 -> CO2 emission 1 -> annual cost 2 -> load following capccity
Constraints:
Biomass consumption<=56.78 GWh
EnergyPLAN configuration
CHP efficiency:
Elec eff: 0.2
Th eff: 0.7
Regulation: technical optimization
technical regulation: 1 (balacing heat demands)
Note: This simulation is wrong in terms of trasport demand and heat demand. New demands are:
Transport:
Diesel: 15.59 GWh
Petrol: 11.44 GWh
Heat demand: 42.37 GWh<file_sep>package reet.fbk.eu.OptimizeEnergyPLANCIVIS.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import jmetal.core.Solution;
import jmetal.util.JMException;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import reet.fbk.eu.OptimizeEnergyPLANCIVIS.ParseFile.EnergyPLANFileParseForCivis;
public class ExtractEnergyPLANParametersCEIS4DWithTransport {
// static MultiMap energyplanmMap;
static String inputs[] = { "PV_Cap", "Biomass_CHP_Cap", "HP_Cap",
"Oil_boiler_Cap", "LPG_boiler_Cap", "Biomass_boiler_Cap", "NumberOfPetrolCars", "NumberOfDieselCars", "NumberOfElectricCars" };
static String outputsinEnergyPLANMap[] = { "AnnualPV", "AnnualHH-elec.CHP",
"AnnualHH-elec.HP", "Annualflexibleeldemand", "AnnualOilBoilerheat", "AnnualLPGBoilerheat",
"AnnualBiomassBoilerheat", "AnnualmCHPheat", "AnnualHPheat",
"Annualimport", "Annualexport", "Oil Consumption",
"Biomass Consumption", "Ngas Consumption", "Gasoil/Diesel",
"Petrol/JP", "Biomass", "Total Electricity exchange",
"Total variable costs", "Fixed operation costs", "AdditionalCost","ElecCarInvestmentCost",
"InvestmentCost", "CO2-emission (corrected)", "AnnualCost",
"LoadFollowingCapacity", "ESD",
"oilBoilerFuelDemand", "ngasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualmCHPheat", "AnnualHPheat", "reducedPetrolDemand", "reducedDieselDemand" };
static String outputsinFile[] = { "AnnualPV", "AnnualCHPelec",
"AnnualHPelec", "AnnualElecCar", "AnnualOilBoilerheat", "AnnualLPGBoilerheat",
"AnnualBiomassBoilerheat", "AnnualmCHPheat", "AnnualHPheat",
"AnnualImport", "AnnualExport", "OilConsumption",
"BiomassConsumption", "LPGConsuption", "DieselCost", "PetrolCost",
"BiomassCost", "TotalElectricityExchangeCost", "TotalVariableCost",
"FixedOperationCosts", "AdditionalCost", "ElecCarInvestmentCost", "InvestmentCost",
"CO2-Emission", "AnnualCost", "LoadFollowingCapacity", "ESD",
"oilBoilerFuelDemand", "LPGBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualmCHPheat", "AnnualHPheat", "reducedPetrolDemand", "reducedDieselDemand"};
static String inputUnits[] = { "KWe", "KWe", "KWe", "KWth", "KWth", "KWth", " ", " ", " " };
static String outputUnits[] = { "GWh", "GWh", "GWh", "GWh", "GWh", "GWh", "GWh",
"GWh", "GWh", "GWh", "GWh", "GWh", "GWh", "GWh", "KEuro", "KEuro",
"KEuro", "KEuro", "KEuro", "KEuro", "KEuro", "KEuro","KEuro", "Mt",
"KEuro", "", "", "GWh","GWh","GWh","GWh","GWh","GWh","GWh" };
public static final double PVInvestmentCostInKEuro = 2.6;
public static final double hydroInvestmentCostInKEuro = 1.9;
public static final double individualBoilerInvestmentCostInKEuro = 0.588;
public static final double BiogasInvestmentCostInKEuro = 4.0;
public static final double interest = 0.04;
public static final double currentPVCapacity = 7514;
public static final double currentHydroCapacity = 4000;
public static final double currentBiogasCapacity = 500;
public static final double currentIndvBiomassBoilerCapacity = 14306;
public static final double currentIndvOilBoilerCapacity = 9155;
public static final double currentIndvLPGBoilerCapacity = 3431;
public static final double totalHeatDemand = 55.82;
public static final double boilerLifeTime = 15;
public static final double PVLifeTime = 30;
public static final double HydroLifeTime = 50;
public static final double BiogasLifeTime = 20;
public static final double geoBoreHoleLifeTime = 100;
public static final double COP = 3.2;
public static final double maxHeatDemandInDistribution = 1.0;
public static final double sumOfAllHeatDistributions = 3112.94;
public static final double geoBoreholeCostInKWe = 3.2;
public static final double oilBoilerEfficiency = 0.80;
public static final double ngasBoilerEfficiency = 0.90;
public static final double biomassBoilerEfficiency = 0.75;
public static final double addtionalCostPerGWhinKEuro = 106.27;
//Transport related data
public static final int currentNumberOfPertrolCars = 2762;
public static final int currentNumberOfDieselCars = 2094;
public static final int averageKMPerYearForPetrolCar = 7250;
public static final int averageKMPerYearForDieselCar = 13400;
// lower calorific value (LCV): KWh/l (ref: http://www.withouthotair.com/c3/page_31.shtml) check with Diego
public static final double LCVPetrol = 8.86;
public static final double LCVDiesel = 10.12;
public static final double KWhPerKMElecCar = 0.168;
public static final double petrolCarRunsKMperL = 15.5;
public static final double DieselCarRunsKMperL = 18.2;
public static final int totalKMRunByCars = 48084100;
public static final double costOfElectricCarInKeuro = 18.690;
public static final int electricCarLifeTime = 15;
public static final double electricCarOperationalAndMaintanenceCost = 0.055; //5.5 percent of Investment cost (costOfElectricCarInKeuro)
public ExtractEnergyPLANParametersCEIS4DWithTransport() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException, JMException {
MultiMap energyplanmMap = null;
// TODO Auto-generated method stub
ExtractEnergyPLANParametersCEIS4DWithTransport ob = new ExtractEnergyPLANParametersCEIS4DWithTransport();
FileInputStream fos = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fos);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
energyplanmMap = ob.simulateEnergyPLAN(line);
ob.WriteEnergyPLANParametersToFile(energyplanmMap, args[0]);
}
br.close();
}
void WriteEnergyPLANParametersToFile(MultiMap energyPLANMap, String path)
throws IOException {
Iterator it;
Collection<String> col;
File filetmp = new File(path);
String arrayStr[] = path.split("\\\\");
File file = new File(filetmp.getParent() + "\\allParameters_"
+ arrayStr[arrayStr.length - 1] + ".txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
// create header of the file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
/*
* bw.write(
* "PV_C HP_Heat_P OilBoilerHeat NgasBoilerHeat BiomassBoilerHeat "
* +
* "AnlPV_P AnlImport AnlExport AnlOilBoilerFuel AnlNgasBoilerFuel "
* +
* "AnlBiomassBoilerFuel AnlOilCost AnlLPGCost AnlBiomassCost AnlElecExchage TotalVariableCost FixedOperationalCost "
* +
* "AdditionalCost InvestmentCost CO2Emission AnnualCost LoadFollowingCapacity"
* );
*/
String headings = "";
for (int i = 0; i < inputs.length; i++) {
headings += inputs[i] + ";";
}
for (int i = 0; i < outputsinFile.length; i++) {
headings += outputsinFile[i] + ";";
}
bw.write(headings);
bw.newLine();
String units = "";
for (int i = 0; i < inputUnits.length; i++) {
units += inputUnits[i] + ";";
}
for (int i = 0; i < outputUnits.length; i++) {
units += outputUnits[i] + ";";
}
bw.write(units);
/*
* bw.write(
* "(KW) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) " +
* "(GWh) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) "
* + "(Mt) (KEuro)");
*/
bw.newLine();
bw.close();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
String input = "", output = "";
for (int i = 0; i < inputs.length; i++) {
col = (Collection<String>) energyPLANMap.get(inputs[i]);
it = col.iterator();
input = input + it.next() + ";";
}
for (int i = 0; i < outputsinEnergyPLANMap.length; i++) {
try{
col = (Collection<String>) energyPLANMap
.get(outputsinEnergyPLANMap[i]);
it = col.iterator();
String str = it.next().toString();
if (str.endsWith("1000")) {
str = str.substring(0, str.lastIndexOf("1000"));
str = Double.parseDouble(str) + "";
}
output = output + str + ";";
}
catch(NullPointerException e){
System.out.println(i);
}
}
bw.write(input + output);
bw.newLine();
bw.close();
}
MultiMap simulateEnergyPLAN(String individual) throws JMException {
StringTokenizer st = new StringTokenizer(individual);
// PV
// PV
double pv = Double.parseDouble(st.nextToken().toString());
// index - 1 -> oil boiler heat percentage
// index - 2 -> LPG boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// Oil-boiler heat percentage
// index - 5 -> electric car percentage
double percentages[] = new double[4];
for (int i = 0; i < 4; i++) {
percentages[i] = Double.parseDouble(st.nextToken().toString());
}
Arrays.sort(percentages);
// oil-boiler percentage
double oilBoilerHeatPercentage = percentages[0];
// LPG-boiler heat percentage
double LPGBoilerHeatPercentage = percentages[1] - percentages[0];
// biomass-boiler heat percentage
double biomassBoilerHeatPercentage = percentages[2] - percentages[1];
// biomass chp heat percentage
double biomassCHPHeatPercentage = percentages[3] - percentages[2];
// heat pump heat percentage
double hpHeatPercentage = 1.0 - percentages[3];
//electric car percentage
double electricCarPercentage = Double.parseDouble(st.nextToken().toString());
int reducedNumberOfPetrolCars = (int) Math.round(currentNumberOfPertrolCars - currentNumberOfPertrolCars * electricCarPercentage);
int reducedNumberOfDieselCars = (int) Math.round(currentNumberOfDieselCars - currentNumberOfDieselCars * electricCarPercentage);
double reducedPetrolDemandInGWh = reducedNumberOfPetrolCars * averageKMPerYearForPetrolCar * LCVPetrol / (petrolCarRunsKMperL*1000000);
double reducedDieselDemandInGWh = reducedNumberOfDieselCars * averageKMPerYearForDieselCar * LCVDiesel / (DieselCarRunsKMperL*1000000);
int elecCarRunKM = totalKMRunByCars - (reducedNumberOfPetrolCars * averageKMPerYearForPetrolCar) - (reducedNumberOfDieselCars * averageKMPerYearForDieselCar);
double elecCarElectricityDemandInGWh = elecCarRunKM * KWhPerKMElecCar / 1000000;
double totalNumberOfElectricCars = (int) Math.round(currentNumberOfPertrolCars + currentNumberOfDieselCars - reducedNumberOfPetrolCars - reducedNumberOfDieselCars);
MultiMap energyplanMap = null;
MultiMap modifyMap = new MultiValueMap();
modifyMap = writeModificationFile(pv, oilBoilerHeatPercentage,LPGBoilerHeatPercentage, biomassBoilerHeatPercentage,biomassCHPHeatPercentage,
hpHeatPercentage, reducedPetrolDemandInGWh, reducedDieselDemandInGWh, elecCarElectricityDemandInGWh, "NC");
String energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i "
+ "\".\\src\\reet\\fbk\\eu\\OptimizeEnergyPLANCIVIS\\CEIS\\data\\CEIS_Complete_Current.txt\" "
+ "-m \"modification.txt\" -ascii \"result.txt\" ";
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParseForCivis epfp = new EnergyPLANFileParseForCivis(
".\\result.txt");
energyplanMap = epfp.parseFile();
energyplanMap.putAll(modifyMap);
//put transport information
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(2);
energyplanMap.put("NumberOfPetrolCars", reducedNumberOfPetrolCars);
energyplanMap.put("NumberOfDieselCars", reducedNumberOfDieselCars);
energyplanMap.put("NumberOfElectricCars", totalNumberOfElectricCars);
energyplanMap.put("reducedPetrolDemand", df.format(reducedPetrolDemandInGWh));
energyplanMap.put("reducedDieselDemand", df.format(reducedDieselDemandInGWh));
Iterator it;
Collection<String> col;
// objective # 2
col = (Collection<String>) energyplanMap
.get("Total variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
totalVariableCostStr = totalVariableCostStr.substring(0,
totalVariableCostStr.lastIndexOf("1000"));
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
fixedOperationalCostStr = fixedOperationalCostStr.substring(0,
fixedOperationalCostStr.lastIndexOf("1000"));
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
col = (Collection<String>) energyplanMap.get("AnnualHydropower");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract anual PV production
col = (Collection<String>) energyplanMap.get("AnnualPV");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
// extract annual import
col = (Collection<String>) energyplanMap.get("Annualimport");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanMap.get("Annualexport");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
//extract biomass CHP electricity production
col = (Collection<String>) energyplanMap.get("AnnualHH-elec.CHP");
it = col.iterator();
double biomassCHPElecProduction = Double.parseDouble(it.next().toString());
// calculate additional cost
// (hydroProduction+PVproduction+Import-Export)*average additional
// cost (85.74)
double totalAdditionalCost = Math.round((hydroPowerProduction
+ PVproduction + Import - Export + biomassCHPElecProduction)
* addtionalCostPerGWhinKEuro);
double capacityOfHeatPump = Math.round((maxHeatDemandInDistribution
* hpHeatPercentage * totalHeatDemand * Math.pow(10, 6))
/ (COP * sumOfAllHeatDistributions));
double geoBoreHoleInvestmentCost = (capacityOfHeatPump
* geoBoreholeCostInKWe * interest)
/ (1 - Math.pow((1 + interest), -geoBoreHoleLifeTime));
// see annual investment cost formula in EnergyPLAN manual
double newCapacityBiomassBoiler = Math
.round((totalHeatDemand * biomassBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionBiomassBoiler = 0.0;
if (newCapacityBiomassBoiler > currentIndvBiomassBoilerCapacity) {
investmentCostReductionBiomassBoiler = (currentIndvBiomassBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionBiomassBoiler = (newCapacityBiomassBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityOilBoiler = Math
.round((totalHeatDemand * oilBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionOilBoiler = 0.0;
if (newCapacityOilBoiler > currentIndvOilBoilerCapacity) {
investmentCostReductionOilBoiler = (currentIndvOilBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionOilBoiler = (newCapacityOilBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityLPGBoiler = Math
.round((totalHeatDemand * LPGBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionLPGBoiler = 0.0;
if (newCapacityLPGBoiler > currentIndvLPGBoilerCapacity) {
investmentCostReductionLPGBoiler = (currentIndvLPGBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionLPGBoiler = (newCapacityLPGBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double reductionInvestmentCost = (currentPVCapacity
* PVInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -PVLifeTime))
+ (currentHydroCapacity * hydroInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -HydroLifeTime))
+ (currentBiogasCapacity * BiogasInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -BiogasLifeTime))
+ investmentCostReductionBiomassBoiler
+ investmentCostReductionOilBoiler
+ investmentCostReductionLPGBoiler;
// extract
col = (Collection<String>) energyplanMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
String investmentCostStr = invest.substring(0,
invest.lastIndexOf("1000"));
double investmentCost = Double.parseDouble(investmentCostStr);
double realInvestmentCost = investmentCost
- reductionInvestmentCost + geoBoreHoleInvestmentCost;
//Electric car related cost
double totalInvestmentCostOfElectricCars = (totalNumberOfElectricCars * costOfElectricCarInKeuro * interest)/ (1 - Math.pow((1 + interest), -electricCarLifeTime));
double totalFixOperationalAndInvestmentCostOfElectricCars = totalNumberOfElectricCars * costOfElectricCarInKeuro * electricCarOperationalAndMaintanenceCost ;
energyplanMap.put("ElecCarInvestmentCost",Math.round(totalInvestmentCostOfElectricCars * 100.0) / 100.0 );
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ realInvestmentCost + totalAdditionalCost + totalInvestmentCostOfElectricCars + totalFixOperationalAndInvestmentCostOfElectricCars;
col = (Collection<String>) energyplanMap.get("Annualelec.demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
//Transport annual electricity demand
col = (Collection<String>) energyplanMap
.get("Annualflexibleeldemand");
it = col.iterator();
double transportElecDemand = Double.parseDouble(it.next().toString());
//Individual house HP electric demand
col = (Collection<String>) energyplanMap.get("AnnualHH-elec.HP");
it = col.iterator();
double annualHPdemand = Double.parseDouble(it.next().toString());
energyplanMap.put("AdditionalCost", totalAdditionalCost);
energyplanMap.put("InvestmentCost", realInvestmentCost);
energyplanMap.put("AnnualCost", actualAnnualCost);
energyplanMap
.put("LoadFollowingCapacity", (Import + Export) / (annualElecDemand+transportElecDemand +annualHPdemand));
//extract ngas consuption
col = (Collection<String>) energyplanMap
.get("Ngas Consumption");
it = col.iterator();
double nGasConsumption = Double.parseDouble(it.next().toString());
//extract oil consumption
col = (Collection<String>) energyplanMap
.get("Oil Consumption");
it = col.iterator();
double oilConsumption = Double.parseDouble(it.next().toString());
//extract biomass consupmtion
col = (Collection<String>) energyplanMap.get("Biomass Consumption");
it = col.iterator();
double BiomassConsumption = Double.parseDouble(it.next().toString());
//extract biogas production (it is named as wave power)
col = (Collection<String>) energyplanMap.get("AnnualWavepower");
it = col.iterator();
double BiogasElecProduction = Double.parseDouble(it.next()
.toString());
double PVPEF = 1.0;
double HYPEF = 1.0;
double BioGasPEF = 1/0.262;
double BiomassPEF = 1/0.18;
double PEFImport = 2.17;
double totalPEForElecrcity = PVproduction * PVPEF + hydroPowerProduction * HYPEF + BiogasElecProduction*BioGasPEF + biomassCHPElecProduction * BiomassPEF;
double totalLocalElecProduction = PVproduction + hydroPowerProduction + BiogasElecProduction+biomassCHPElecProduction;
double PEFLocalElec = totalPEForElecrcity/ totalLocalElecProduction;
double totalPEConsumtion = (totalLocalElecProduction - Export) * PEFLocalElec + Import * PEFImport + BiomassConsumption + oilConsumption + nGasConsumption
+ (totalHeatDemand* hpHeatPercentage - totalHeatDemand* hpHeatPercentage/COP);
double ESD = (Import * PEFImport + oilConsumption + nGasConsumption)/totalPEConsumtion;
energyplanMap.put("ESD", ESD);
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
return energyplanMap;
}
public MultiMap writeModificationFile(double pv, double oilBoilerHeatPercentage,
double LPGBoilerHeatPercentage,
double biomassBoilerHeatPercentage, double biomassCHPHeatPercentage,
double hpHeatPercentage, double reducedPetrolDemand, double reducedDieselDemand, double elecCarDemand, String elecChangeProfile) throws JMException {
MultiMap modifyMap = new MultiValueMap();
double totalOilBoilerHeat = oilBoilerHeatPercentage * totalHeatDemand;
double totalLPGBoilerHeat = LPGBoilerHeatPercentage * totalHeatDemand;
double totalBiomassBoilerHeat = biomassBoilerHeatPercentage
* totalHeatDemand;
double totalnGasCHPHeat = biomassCHPHeatPercentage * totalHeatDemand;
double totalHPHeat = hpHeatPercentage * totalHeatDemand;
modifyMap.put("AnnualOilBoilerheat",
Math.round(totalOilBoilerHeat * 100.0) / 100.0); //this is done for 2 decimal place precision
modifyMap.put("AnnualLPGBoilerheat",
Math.round(totalLPGBoilerHeat * 100.0) / 100.0);
modifyMap.put("AnnualBiomassBoilerheat",
Math.round(totalBiomassBoilerHeat * 100.0) / 100.0);
modifyMap.put("AnnualmCHPheat",
Math.round(totalnGasCHPHeat * 100.0) / 100.0);
modifyMap.put("AnnualHPheat", Math.round(totalHPHeat * 100.0) / 100.0);
double oilBCap = totalOilBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double LPGBCap = totalLPGBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double BiomassBCap = totalBiomassBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double biomassCHPCap = totalnGasCHPHeat * Math.pow(10, 6)
/ sumOfAllHeatDistributions;
double HPCap = totalHPHeat * Math.pow(10, 6)
/ (COP * sumOfAllHeatDistributions);
modifyMap.put(inputs[0], (int) Math.round(pv));
modifyMap.put(inputs[1], (int) Math.round(biomassCHPCap));
modifyMap.put(inputs[2], (int) Math.round(HPCap));
modifyMap.put(inputs[3], (int) Math.round(oilBCap));
modifyMap.put(inputs[4], (int) Math.round(LPGBCap));
modifyMap.put(inputs[5], (int) Math.round(BiomassBCap));
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) Math.round(pv);
bw.write(str);
bw.newLine();
// oil boiler fuel demand
str = "input_fuel_Households[2]=";
bw.write(str);
bw.newLine();
double oilBoilerFuelDemand = oilBoilerHeatPercentage
* totalHeatDemand / oilBoilerEfficiency;
str = "" + oilBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("oilBoilerFuelDemand", oilBoilerFuelDemand);
// Ngas boiler fuel demand
str = "input_fuel_Households[3]=";
bw.write(str);
bw.newLine();
double ngasBoilerFuelDemand = LPGBoilerHeatPercentage
* totalHeatDemand / ngasBoilerEfficiency;
str = "" + ngasBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("ngasBoilerFuelDemand", ngasBoilerFuelDemand);
// biomass boiler fuel demand
str = "input_fuel_Households[4]=";
bw.write(str);
bw.newLine();
double biomassBoilerFuelDemand = biomassBoilerHeatPercentage
* totalHeatDemand / biomassBoilerEfficiency;
str = "" + biomassBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("biomassBoilerFuelDemand", biomassBoilerFuelDemand);
// biomass micro chp heat demand
str = "input_HH_BioCHP_heat=";
bw.write(str);
bw.newLine();
str = "" + biomassCHPHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
// heat pump heat demand
str = "input_HH_HP_heat=";
bw.write(str);
bw.newLine();
str = "" + hpHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
//Electric car electricity demand
str = "input_transport_TWh=";
bw.write(str);
bw.newLine();
str = "" + elecCarDemand;
bw.write(str);
bw.newLine();
//to handle scintific number
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(2);
//Reduced Diesel demand
str = "input_fuel_Transport[2]=";
bw.write(str);
bw.newLine();
str = "" + df.format(reducedDieselDemand);
bw.write(str);
bw.newLine();
//reduced petrol demand
str = "input_fuel_Transport[5]=";
bw.write(str);
bw.newLine();
str = "" + df.format(reducedPetrolDemand);
bw.write(str);
bw.newLine();
if(elecChangeProfile.equals("DC")){
// day charge profile
str = "Filnavn_transport=";
bw.write(str);
bw.newLine();
str = "CIVIS_Transport_DC.txt";
bw.write(str);
bw.newLine();
}
else if(elecChangeProfile.equals("NC")){
// day charge profile
str = "Filnavn_transport=";
bw.write(str);
bw.newLine();
str = "CIVIS_Transport_NC.txt";
bw.write(str);
bw.newLine();
}else{
throw new JMException("chrging profile not given");
}
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
return modifyMap;
}
}
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANCIVIS.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import jmetal.core.Solution;
import jmetal.util.JMException;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import reet.fbk.eu.OptimizeEnergyPLANCIVIS.ParseFile.EnergyPLANFileParseForCivis;
;
public class ExtractEnergyPLANParametersCEIS4D {
// static MultiMap energyplanmMap;
static String inputs[] = { "PV_Cap", "Biomass_CHP_Cap", "HP_Cap",
"Oil_boiler_Cap", "LPG_boiler_Cap", "Biomass_boiler_Cap" };
static String outputsinEnergyPLANMap[] = { "AnnualPV", "AnnualHH-elec.CHP",
"AnnualHH-elec.HP", "AnnualOilBoilerheat", "AnnualLPGBoilerheat",
"AnnualBiomassBoilerheat", "AnnualmCHPheat", "AnnualHPheat",
"Annualimport", "Annualexport",
"Oil Consumption", "Biomass Consumption", "Ngas Consumption","Gasoil/Diesel",
"Petrol/JP", "Biomass", "Total Electricity exchange",
"Total variable costs", "Fixed operation costs", "AdditionalCost",
"InvestmentCost", "CO2-emission (corrected)", "AnnualCost",
"LoadFollowingCapacity", "ESD",
"oilBoilerFuelDemand", "ngasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualmCHPheat", "AnnualHPheat"};
static String outputsinFile[] = { "AnnualPV", "AnnualCHPelec",
"AnnualHPelec", "AnnualOilBoilerheat", "AnnualLPGBoilerheat",
"AnnualBiomassBoilerheat", "AnnualBiomassmCHPheat", "AnnualHPheat",
"AnnualImport", "AnnualExport", "OilConsumption",
"BiomassConsumption", "LPGConsuption", "DieselCost", "PetrolCost", "BiomassCost",
"TotalElectricityExchangeCost", "TotalVariableCost",
"FixedOperationCosts", "AdditionalCost", "InvestmentCost",
"CO2-Emission", "AnnualCost", "LoadFollowingCapacity", "ESD",
"oilBoilerFuelDemand", "ngasBoilerFuelDemand", "biomassBoilerFuelDemand", "AnnualmCHPheat", "AnnualHPheat"};
static String inputUnits[] = { "KWe", "KWe", "KWe", "KWth", "KWth", "KWth" };
static String outputUnits[] = { "GWh", "GWh", "GWh", "GWh", "GWh", "GWh",
"GWh", "GWh", "GWh", "GWh", "GWh", "GWh", "GWh", "KEuro", "KEuro",
"KEuro", "KEuro", "KEuro", "KEuro", "KEuro", "KEuro", "Mt",
"KEuro", "", "", "GWh","GWh","GWh","GWh","GWh" };
public static final double PVInvestmentCostInKEuro = 2.6;
public static final double hydroInvestmentCostInKEuro = 1.9;
public static final double individualBoilerInvestmentCostInKEuro = 0.588;
public static final double BiogasInvestmentCostInKEuro = 4.0;
public static final double interest = 0.04;
public static final double currentPVCapacity = 7514;
public static final double currentHydroCapacity = 4000;
public static final double currentBiogasCapacity = 500;
public static final double currentIndvBiomassBoilerCapacity = 14306;
public static final double currentIndvOilBoilerCapacity = 9155;
public static final double currentIndvLPGBoilerCapacity = 3431;
public static final double totalHeatDemand = 55.82;
public static final double boilerLifeTime = 15;
public static final double PVLifeTime = 30;
public static final double HydroLifeTime = 50;
public static final double BiogasLifeTime = 20;
public static final double geoBoreHoleLifeTime = 100;
public static final double COP = 3.2;
public static final double maxHeatDemandInDistribution = 1.0;
public static final double sumOfAllHeatDistributions = 3112.94;
public static final double geoBoreholeCostInKWe = 3.2;
public static final double oilBoilerEfficiency = 0.80;
public static final double ngasBoilerEfficiency = 0.90;
public static final double biomassBoilerEfficiency = 0.75;
public static final double addtionalCostPerGWhinKEuro = 106.27;
public ExtractEnergyPLANParametersCEIS4D() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException {
MultiMap energyplanmMap = null;
// TODO Auto-generated method stub
ExtractEnergyPLANParametersCEIS4D ob = new ExtractEnergyPLANParametersCEIS4D();
FileInputStream fos = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fos);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
energyplanmMap = ob.simulateEnergyPLAN(line);
ob.WriteEnergyPLANParametersToFile(energyplanmMap, args[0]);
}
br.close();
}
void WriteEnergyPLANParametersToFile(MultiMap energyPLANMap, String path)
throws IOException {
Iterator it;
Collection<String> col;
File filetmp = new File(path);
String arrayStr[] = path.split("\\\\");
File file = new File(filetmp.getParent() + "\\allParameters_"
+ arrayStr[arrayStr.length - 1] + ".txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
// create header of the file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
/*
* bw.write(
* "PV_C HP_Heat_P OilBoilerHeat NgasBoilerHeat BiomassBoilerHeat "
* +
* "AnlPV_P AnlImport AnlExport AnlOilBoilerFuel AnlNgasBoilerFuel "
* +
* "AnlBiomassBoilerFuel AnlOilCost AnlLPGCost AnlBiomassCost AnlElecExchage TotalVariableCost FixedOperationalCost "
* +
* "AdditionalCost InvestmentCost CO2Emission AnnualCost LoadFollowingCapacity"
* );
*/
String headings = "";
for (int i = 0; i < inputs.length; i++) {
headings += inputs[i] + " ";
}
for (int i = 0; i < outputsinFile.length; i++) {
headings += outputsinFile[i] + " ";
}
bw.write(headings);
bw.newLine();
String units = "";
for (int i = 0; i < inputUnits.length; i++) {
units += inputUnits[i] + " ";
}
for (int i = 0; i < outputUnits.length; i++) {
units += outputUnits[i] + " ";
}
bw.write(units);
/*
* bw.write(
* "(KW) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) " +
* "(GWh) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) "
* + "(Mt) (KEuro)");
*/
bw.newLine();
bw.close();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
String input = "", output = "";
for (int i = 0; i < inputs.length; i++) {
col = (Collection<String>) energyPLANMap.get(inputs[i]);
it = col.iterator();
input = input + it.next() + " ";
}
for (int i = 0; i < outputsinEnergyPLANMap.length; i++) {
try{
col = (Collection<String>) energyPLANMap
.get(outputsinEnergyPLANMap[i]);
it = col.iterator();
String str = it.next().toString();
if (str.endsWith("1000")) {
str = str.substring(0, str.lastIndexOf("1000"));
str = Double.parseDouble(str) + "";
}
output = output + str + ";";
}catch(NullPointerException e){
System.out.println(i);
}
}
bw.write(input + output);
bw.newLine();
bw.close();
}
MultiMap simulateEnergyPLAN(String individual) {
StringTokenizer st = new StringTokenizer(individual);
// PV
double pv = Double.parseDouble(st.nextToken().toString());
// index - 1 -> oil boiler heat percentage
// index - 2 -> LPG boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// Oil-boiler heat percentage
double percentages[] = new double[4];
for (int i = 0; i < 4; i++) {
percentages[i] = Double.parseDouble(st.nextToken().toString());
}
Arrays.sort(percentages);
// oil-boiler percentage
double oilBoilerHeatPercentage = percentages[0];
// LPG-boiler heat percentage
double LPGBoilerHeatPercentage = percentages[1] - percentages[0];
// biomass-boiler heat percentage
double biomassBoilerHeatPercentage = percentages[2] - percentages[1];
// biomass chp heat percentage
double biomassCHPHeatPercentage = percentages[3] - percentages[2];
// heta pump heat percentage
double hpHeatPercentage = 1.0 - percentages[3];
MultiMap energyplanMap = null;
MultiMap modifyMap = new MultiValueMap();
modifyMap = writeModificationFile(individual);
String energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i "
+ "\".\\src\\reet\\fbk\\eu\\OptimizeEnergyPLANCIVIS\\CEIS\\data\\CEIS_Complete_Current.txt\" "
+ "-m \"modification.txt\" -ascii \"result.txt\" ";
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParseForCivis epfp = new EnergyPLANFileParseForCivis(
".\\result.txt");
energyplanMap = epfp.parseFile();
energyplanMap.putAll(modifyMap);
Iterator it;
Collection<String> col;
// objective # 2
col = (Collection<String>) energyplanMap
.get("Total variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
totalVariableCostStr = totalVariableCostStr.substring(0,
totalVariableCostStr.lastIndexOf("1000"));
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
fixedOperationalCostStr = fixedOperationalCostStr.substring(0,
fixedOperationalCostStr.lastIndexOf("1000"));
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
col = (Collection<String>) energyplanMap.get("AnnualHydropower");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract annual PV production
col = (Collection<String>) energyplanMap.get("AnnualPV");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
//extract biogas production (it is named as wave power)
col = (Collection<String>) energyplanMap.get("AnnualWavepower");
it = col.iterator();
double BiogasElecProduction = Double.parseDouble(it.next()
.toString());
// extract annual import
col = (Collection<String>) energyplanMap.get("Annualimport");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanMap.get("Annualexport");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
//extract biomass CHP electricity production
col = (Collection<String>) energyplanMap.get("AnnualHH-elec.CHP");
it = col.iterator();
double BiomassCHPElecProduction = Double.parseDouble(it.next().toString());
// calculate additional cost
// (hydroProduction+PVproduction+Import-Export)*average additional
// cost (106.27)
double totalAdditionalCost = Math.round((hydroPowerProduction
+ PVproduction + BiogasElecProduction + Import - Export + BiomassCHPElecProduction)
* addtionalCostPerGWhinKEuro);
// new capacity of individual boilers
/*
* double newHeatdemandForBoilers = (totalHeatDemand *
* oilBoilerHeatPercentage + totalHeatDemand *
* ngasBoilerHeatPercentage + totalHeatDemand *
* biomassBoilerHeatPercentage); double
* capacityOfBoilerforNewHeatDemand =
* Math.round(maxHeatDemandInDistribution *
* newHeatdemandForBoilers*Math.pow(10,
* 6)*1.5/sumOfAllHeatDistributions);
*/
double capacityOfHeatPump = Math.round((maxHeatDemandInDistribution
* hpHeatPercentage * totalHeatDemand * Math.pow(10, 6))
/ (COP * sumOfAllHeatDistributions));
double geoBoreHoleInvestmentCost = (capacityOfHeatPump
* geoBoreholeCostInKWe * interest)
/ (1 - Math.pow((1 + interest), -geoBoreHoleLifeTime));
// see annual investment cost formula in EnergyPLAN manual
double newCapacityBiomassBoiler = Math
.round((totalHeatDemand * biomassBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionBiomassBoiler = 0.0;
if (newCapacityBiomassBoiler > currentIndvBiomassBoilerCapacity) {
investmentCostReductionBiomassBoiler = (currentIndvBiomassBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionBiomassBoiler = (newCapacityBiomassBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityOilBoiler = Math
.round((totalHeatDemand * oilBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionOilBoiler = 0.0;
if (newCapacityOilBoiler > currentIndvOilBoilerCapacity) {
investmentCostReductionOilBoiler = (currentIndvOilBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionOilBoiler = (newCapacityOilBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double newCapacityLPGBoiler = Math
.round((totalHeatDemand * LPGBoilerHeatPercentage)
* Math.pow(10, 6) * 1.5 / sumOfAllHeatDistributions);
double investmentCostReductionLPGBoiler = 0.0;
if (newCapacityLPGBoiler > currentIndvLPGBoilerCapacity) {
investmentCostReductionLPGBoiler = (currentIndvLPGBoilerCapacity
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
} else {
investmentCostReductionLPGBoiler = (newCapacityLPGBoiler
* individualBoilerInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime));
}
double reductionInvestmentCost = (currentPVCapacity
* PVInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -PVLifeTime))
+ (currentHydroCapacity * hydroInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -HydroLifeTime))
+ (currentBiogasCapacity * BiogasInvestmentCostInKEuro * interest)
/ (1 - Math.pow((1 + interest), -BiogasLifeTime))
+ investmentCostReductionBiomassBoiler
+ investmentCostReductionOilBoiler
+ investmentCostReductionLPGBoiler;
// extract
col = (Collection<String>) energyplanMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
String investmentCostStr = invest.substring(0,
invest.lastIndexOf("1000"));
double investmentCost = Double.parseDouble(investmentCostStr);
double realInvestmentCost = investmentCost
- reductionInvestmentCost + geoBoreHoleInvestmentCost;
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ realInvestmentCost + totalAdditionalCost;
// 3rd objective
col = (Collection<String>) energyplanMap.get("Annualelec.demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
//Individual house HP electric demand
col = (Collection<String>) energyplanMap.get("AnnualHH-elec.HP");
it = col.iterator();
double annualHPdemand = Double.parseDouble(it.next().toString());
energyplanMap.put("AdditionalCost", totalAdditionalCost);
energyplanMap.put("InvestmentCost", realInvestmentCost);
energyplanMap.put("AnnualCost", actualAnnualCost);
energyplanMap.put("LoadFollowingCapacity", (Import + Export) / (annualElecDemand + annualHPdemand));
//extract ngas consuption
col = (Collection<String>) energyplanMap
.get("Ngas Consumption");
it = col.iterator();
double nGasConsumption = Double.parseDouble(it.next().toString());
//extract oil consumption
col = (Collection<String>) energyplanMap
.get("Oil Consumption");
it = col.iterator();
double oilConsumption = Double.parseDouble(it.next().toString());
//extract biomass consupmtion
col = (Collection<String>) energyplanMap.get("Biomass Consumption");
it = col.iterator();
double BiomassConsumption = Double.parseDouble(it.next().toString());
double PVPEF = 1.0;
double HYPEF = 1.0;
double BioGasPEF = 1/0.262;
double BiomassPEF = 1/0.18;
double PEFImport = 2.17;
double totalPEForElecrcity = PVproduction * PVPEF + hydroPowerProduction * HYPEF + BiogasElecProduction*BioGasPEF + BiomassCHPElecProduction * BiomassPEF;
double totalLocalElecProduction = PVproduction + hydroPowerProduction + BiogasElecProduction+BiomassCHPElecProduction;
double PEFLocalElec = totalPEForElecrcity/ totalLocalElecProduction;
double totalPEConsumtion = (totalLocalElecProduction - Export) * PEFLocalElec + Import * PEFImport + BiomassConsumption + oilConsumption + nGasConsumption
+ (totalHeatDemand* hpHeatPercentage - totalHeatDemand* hpHeatPercentage/COP);
double ESD = (Import * PEFImport + oilConsumption + nGasConsumption)/totalPEConsumtion;
energyplanMap.put("ESD", ESD);
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
return energyplanMap;
}
public MultiMap writeModificationFile(String individual) {
MultiMap modifyMap = new MultiValueMap();
StringTokenizer st = new StringTokenizer(individual);
double pv = Double.parseDouble(st.nextToken().toString());
// index - 1 -> oil boiler heat percentage
// index - 2 -> LPG boiler heat percentage
// index - 3 -> Biomass boiler heat percentage
// index - 4 -> Biomass micro chp heat percentage
// last percentage will go to individual HP percentage
// Oil-boiler heat percentage
double percentages[] = new double[4];
for (int i = 0; i < 4; i++) {
percentages[i] = Double.parseDouble(st.nextToken().toString());
}
Arrays.sort(percentages);
// oil-boiler percentage
double oilBoilerHeatPercentage = percentages[0];
// LPG-boiler heat percentage
double LPGBoilerHeatPercentage = percentages[1] - percentages[0];
// biomass-boiler heat percentage
double biomassBoilerHeatPercentage = percentages[2] - percentages[1];
// biomass chp heat percentage
double biomassCHPHeatPercentage = percentages[3] - percentages[2];
// heta pump heat percentage
double hpHeatPercentage = 1.0 - percentages[3];
double totalOilBoilerHeat = oilBoilerHeatPercentage * totalHeatDemand;
double totalLPGBoilerHeat = LPGBoilerHeatPercentage * totalHeatDemand;
double totalBiomassBoilerHeat = biomassBoilerHeatPercentage
* totalHeatDemand;
double totalBiomassCHPHeat = biomassCHPHeatPercentage * totalHeatDemand;
double totalHPHeat = hpHeatPercentage * totalHeatDemand;
modifyMap.put("AnnualOilBoilerheat", Math.round(totalOilBoilerHeat * 100.0) / 100.0 );
modifyMap.put("AnnualLPGBoilerheat", Math.round(totalLPGBoilerHeat * 100.0) / 100.0);
modifyMap.put("AnnualBiomassBoilerheat", Math.round(totalBiomassBoilerHeat * 100.0) / 100.0);
modifyMap.put("AnnualmCHPheat", Math.round(totalBiomassCHPHeat * 100.0) / 100.0);
modifyMap.put("AnnualHPheat", Math.round(totalHPHeat * 100.0) / 100.0);
double oilBCap = totalOilBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double LPGBCap = totalLPGBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double BiomassBCap = totalBiomassBoilerHeat * Math.pow(10, 6) * 1.5
/ sumOfAllHeatDistributions;
double biomassCHPCap = totalBiomassCHPHeat * Math.pow(10, 6)
/ sumOfAllHeatDistributions;
double HPCap = totalHPHeat * Math.pow(10, 6)
/ (COP * sumOfAllHeatDistributions);
modifyMap.put(inputs[0], (int) Math.round(pv));
modifyMap.put(inputs[1], (int) Math.round(biomassCHPCap));
modifyMap.put(inputs[2], (int) Math.round(HPCap));
modifyMap.put(inputs[3], (int) Math.round(oilBCap));
modifyMap.put(inputs[4], (int) Math.round(LPGBCap));
modifyMap.put(inputs[5], (int) Math.round(BiomassBCap));
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) Math.round(pv);
bw.write(str);
bw.newLine();
// oil boiler fuel demand
str = "input_fuel_Households[2]=";
bw.write(str);
bw.newLine();
double oilBoilerFuelDemand = oilBoilerHeatPercentage
* totalHeatDemand / oilBoilerEfficiency;
str = "" + oilBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("oilBoilerFuelDemand", oilBoilerFuelDemand);
// Ngas boiler fuel demand
str = "input_fuel_Households[3]=";
bw.write(str);
bw.newLine();
double ngasBoilerFuelDemand = LPGBoilerHeatPercentage
* totalHeatDemand / ngasBoilerEfficiency;
str = "" + ngasBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("ngasBoilerFuelDemand", ngasBoilerFuelDemand);
// biomass boiler fuel demand
str = "input_fuel_Households[4]=";
bw.write(str);
bw.newLine();
double biomassBoilerFuelDemand = biomassBoilerHeatPercentage
* totalHeatDemand / biomassBoilerEfficiency;
str = "" + biomassBoilerFuelDemand;
bw.write(str);
bw.newLine();
modifyMap.put("biomassBoilerFuelDemand", biomassBoilerFuelDemand);
// biomass micro chp heat demand
str = "input_HH_BioCHP_heat=";
bw.write(str);
bw.newLine();
str = "" + biomassCHPHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
// heat pump heat demand
str = "input_HH_HP_heat=";
bw.write(str);
bw.newLine();
str = "" + hpHeatPercentage * totalHeatDemand;
bw.write(str);
bw.newLine();
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
return modifyMap;
}
}
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANCEIS2021.parseFile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
public class EnergyPLANFileParseForCEIS2021{
BufferedReader br = null;
MultiMap multiMap = new MultiValueMap();
public EnergyPLANFileParseForCEIS2021(String filePath) {
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public MultiMap parseFile() {
try {
String line;
boolean trackAnnualCost = false;
//read 2 lines starting with "ANNUAL CO2 EMISSIONS (kt):"
while (!(line = br.readLine()).startsWith("ANNUAL CO2 EMISSIONS (kt):") ) {
;
}
//1st line
line = br.readLine();
String StringSplit[] = line.split("\t");
String tmpKey=StringSplit[0].trim(); String tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//2nd line
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//read 3 lines starting with "SHARE OF RES (incl. Biomass):"
while (!(line = br.readLine()).startsWith("SHARE OF RES (incl. Biomass):") ) {
;
}
//1st line
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//2nd line
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//3rd line
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//read 12 lines starting with "ANNUAL FUEL CONSUMPTIONS (TWh/year)"
while (!(line = br.readLine()).startsWith("ANNUAL FUEL CONSUMPTIONS (GWh/year)") ) {
;
}
for(int i=0;i<12;i++){
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
}
//read 9 lines starting with "ANNUAL COSTS (k EUR)"
while (!(line = br.readLine()).startsWith("ANNUAL COSTS (k EUR)") ) {
;
}
for(int i=0;i<9;i++){
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
}
//read "Ngas Exchange costs"
while (!(line = br.readLine()).startsWith("Ngas Exchange costs") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[2].trim();
multiMap.put(tmpKey, tmpValue);
//read "Electricity exchange"
while (!(line = br.readLine()).startsWith("Electricity exchange") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[2].trim();
multiMap.put(tmpKey, tmpValue);
//read import
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[3].trim();
multiMap.put(tmpKey, tmpValue);
//read export
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[3].trim();
multiMap.put(tmpKey, tmpValue);
//read Bottleneck
line = br.readLine();
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[3].trim();
multiMap.put(tmpKey, tmpValue);
//read "Variable costs"
while (!(line = br.readLine()).startsWith("Variable costs") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//read "Fixed operation costs"
while (!(line = br.readLine()).startsWith("Fixed operation costs") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//read "Annual Investment costs"
while (!(line = br.readLine()).startsWith("Annual Investment costs") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//read "TOTAL ANNUAL COSTS"
while (!(line = br.readLine()).startsWith("TOTAL ANNUAL COSTS") ) {
;
}
StringSplit = line.split("\t");
tmpKey=StringSplit[0].trim(); tmpValue = StringSplit[1].trim();
multiMap.put(tmpKey, tmpValue);
//skip 12 lines
for(int i=0;i<12;i++){
String temp = br.readLine();
}
String line1 = br.readLine();
String line2 = br.readLine();
String l1[] = line1.split("\t");
String l2[] = line2.split("\t");
for (int i = 0; i < l1.length; i++) {
l1[i] = l1[i].trim();
l2[i] = l2[i].trim();
}
while (!(line = br.readLine()).equals("TOTAL FOR ONE YEAR (GWh/year):")) {
;
}
// read annual line
line = br.readLine();
String lineTmp[] = line.split("\t");
for (int i = 0; i < lineTmp.length; i++) {
lineTmp[i] = lineTmp[i].trim();
}
for (int i = 1; i < lineTmp.length; i++) {
String key = "Annual" + l1[i] + l2[i];
String value = lineTmp[i];
multiMap.put(key, value);
}
// read monthly line
line = br.readLine();
line = br.readLine();
for (int j = 0; j < 12; j++) {
line = br.readLine();
lineTmp = line.split("\t");
for (int i = 0; i < lineTmp.length; i++) {
lineTmp[i] = lineTmp[i].trim();
}
for (int i = 1; i < lineTmp.length; i++) {
String key = lineTmp[0] + l1[i] + l2[i];
String value = lineTmp[i];
multiMap.put(key, value);
}
}
//read average, maximum, minimum
line = br.readLine();
for (int j = 0; j < 3; j++) {
line = br.readLine();
lineTmp = line.split("\t");
for (int i = 0; i < lineTmp.length; i++) {
lineTmp[i] = lineTmp[i].trim();
}
for (int i = 1; i < lineTmp.length; i++) {
String key = lineTmp[0] + l1[i] + l2[i];
String value = lineTmp[i];
multiMap.put(key, value);
}
}
//read hour values
/*line = br.readLine();
line = br.readLine();
for (int j = 0; j < 8784; j++) {
line = br.readLine();
lineTmp = line.split("\0");
for (int i = 0; i < lineTmp.length; i++) {
lineTmp[i] = lineTmp[i].trim();
}
for (int i = 1; i < lineTmp.length; i++) {
String key = lineTmp[0] + l1[i] + l2[i];
String value = lineTmp[i];
multiMap.put(key, value);
}
}*/
//additional calculation
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return multiMap;
}
@SuppressWarnings("unchecked")
public static void main(String args[]){
EnergyPLANFileParseForSRI epfp = new EnergyPLANFileParseForSRI("C:\\Users\\shaik\\eclipse-workspace\\EnergyPLANDomainKnowledgeEA\\EnergyPLAN15.1\\spool\\results\\modifiedInput0.txt.txt");
MultiMap energyplanmMap = epfp.parseFile();
Iterator it;
Collection<String> col;
// objective # 1
col = (Collection<String>) energyplanmMap
.get("CO2-emission (corrected)");
it = col.iterator();
// objective # 2
col = (Collection<String>) energyplanmMap
.get("Variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanmMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
col = (Collection<String>) energyplanmMap.get("AnnualHydroElectr.");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract anual PV production
col = (Collection<String>) energyplanmMap.get("AnnualPVElectr.");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
// extract annual import
col = (Collection<String>) energyplanmMap.get("AnnualImportElectr.");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanmMap.get("AnnualExportElectr.");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
//extract biomass CHP electricity production
col = (Collection<String>) energyplanmMap.get("AnnualHH-CHPElectr.");
it = col.iterator();
double biomassCHPElecProduction = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
double investmentCost = Double.parseDouble(invest);
col = (Collection<String>) energyplanmMap
.get("AnnualFlexibleElectr.");
it = col.iterator();
double transportElecDemand = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("AnnualElectr.Demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
//Individual house HP electric demand
col = (Collection<String>) energyplanmMap.get("AnnualHH-HPElectr.");
it = col.iterator();
double annualHPdemand = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap
.get("Ngas Consumption");
it = col.iterator();
double nGasConsumption = Double.parseDouble(it.next().toString());
//extract biomass consupmtion
col = (Collection<String>) energyplanmMap.get("Biomass Consumption");
it = col.iterator();
double BiomassConsumption = Double.parseDouble(it.next().toString());
//extract solar thermal heat
col = (Collection<String>) energyplanmMap.get("AnnualHH SolarHeat");
it = col.iterator();
double solaThermal = Double.parseDouble(it.next().toString());
col = (Collection<String>) energyplanmMap.get("Annual MaximumImportElectr.");
it = col.iterator();
double x = Double.parseDouble(it.next().toString());
}
}<file_sep>postscript("SPEA2_SC_indicators.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
#pdf("SPEA2SC.pdf", width=12, height=8,pointsize=12)
resultDirectory<-"C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/StoppingCriteriaStudies/data/SPEA2SC"
qIndicator <- function(problem)
{
filePolynomialMutation<-paste(resultDirectory, problem, sep="/")
#filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, "HVD", sep="/")
PolynomialMutation<-scan(filePolynomialMutation)
fileDKMutation<-paste(resultDirectory, problem, sep="/")
#fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileDKMutation<-paste(fileDKMutation, "EpsD", sep="/")
DKMutation<-scan(fileDKMutation)
ind<-c(expression('HV'[d]), expression('eps'[d]))
boxplot(PolynomialMutation,DKMutation,names=ind, notch = FALSE, outline=FALSE)
abline(h=0.0)
titulo <-paste(problem)
title(main=titulo)
}
par(mfrow=c(2,3))
prob1<-"ZDT1"
qIndicator(prob1)
prob1<-"ZDT2"
qIndicator(prob1)
prob1<-"ZDT3"
qIndicator(prob1)
prob1<-"ZDT4"
qIndicator(prob1)
prob1<-"DTLZ2"
qIndicator(prob1)
prob1<-"DTLZ5"
qIndicator(prob1)
dev.off()<file_sep>The 4 results are produced by NSGAIIForDK for Aalborg data.
There are 7 decision variable (CHP group 3, HP for group 3, PP, wind, offshore wind, PV, boiler).
PP and boiler capcity is dertermine deterministically
There are two objectives (CO2 emssion and annual cost).
There are three constraints.
1. Maximumimport <=160
2. minimum grid stablization factor >=100
3. Annual heat balance <=0
Algorithm: NSGAIIForDK (reet.fbk.eu.jmetal.metaheuristics.nsgaII)
NSGAII parameters:
population: 100
max evaluation: 15000
Crossover: SBXCrossover, probability: 0.9, distribution index: 10
Mutation: GeneralModifiedPolynomialMutationForRes (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
Probability: 1.0/problem.getNumberOfVariables(), distribution index: 10
Domain-knowledge:
Boolean favorGenesforRE[] ={true, true, null, true, true, true, null};
Boolean favorGenesforConventionalPP[] ={false, false, null, false, false, false, null};
ture-> increase, false -> decrease
selection: binary tournament
<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII for building true Pareto front.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: polynomial
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: NSGA-II
selection: Binary Tournament 2.
//run#1 to run# 10
seed [] = {545782, 455875, 547945, 458478, 981354, 652262, 562366, 365652, 456545, 549235 };
//2nd 10 runs with 10 new seeds (run # 11 to run #20)
long seed [] = {
161395,
276644,
309259,
370995,
468245,
515856,
668763,
698156,
756252,
930462
};
//3rd seed for nsgaii (run#21 to run#30)
long seed [] = {
170339,
259029,
288470,
353882,
626495,
683991,
714786,
989776,
992177,
999921
};
mergeFUN_N: all Pareto front from 30 runs with NSGAII
N.B: These results are reported in ASOC paper<file_sep>postscript("NSGAII.Epsilon.Boxplot.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10)
resultDirectory<-"../data/"
qIndicator <- function(indicator, problem)
{
filePolynomialMutation<-paste(resultDirectory, "PolynomialMutation", sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/")
filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/")
PolynomialMutation<-scan(filePolynomialMutation)
fileDKMutation<-paste(resultDirectory, "DKMutation", sep="/")
fileDKMutation<-paste(fileDKMutation, problem, sep="/")
fileDKMutation<-paste(fileDKMutation, indicator, sep="/")
DKMutation<-scan(fileDKMutation)
algs<-c("PolynomialMutation","DKMutation")
boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE)
titulo <-paste(indicator, problem, sep=":")
title(main=titulo)
}
par(mfrow=c(2,3))
indicator<-"Epsilon"
qIndicator(indicator, "OptimizeElecEnergy_NSGAII")
<file_sep>[DocHistory]
FileCount=19
File0=energyPlan Data\Data\SRI_2025_V3.txt
File1=energyPlan Data\Data\initalize.txt
File2=spool\modifiedInput0.txt
File3=spool\modifiedInput9.txt
File4=spool\modifiedInput0
File5=energyPlan Data\Data\modifiedInput0
File6=energyPlan Data\Data\Aalborg2050_vision.txt
File7=energyPlan Data\Data\2050 IDA technical closed new_DK100pct.txt
File8=energyPlan Data\Data\2050 IDA market open new - v2_DK100pct.txt
File9=energyPlan Data\Data\IDA2030_anbefalinger.txt
File10=energyPlan Data\Data\IDA2030_anbefalinger+biogas.txt
File11=energyPlan Data\Data\DK2020_2018edition.txt
File12=energyPlan Data\Data\IDA2035-market-v1_latest.txt
File13=energyPlan Data\Data\IDA2030_update.txt
File14=energyPlan Data\Data\IDA2030_ref+BF19.txt
File15=energyPlan Data\Data\2035 IDA market open new.txt
File16=energyPlan Data\Data\IDA2035-market-v1.txt
File17=energyPlan Data\Data\IDA2030_ref.txt
File18=energyPlan Data\Data\2035 IDA market open new - v2.txt
<file_sep>package reet.fbk.eu.jmetal.initialization.AnalysisResults;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import reet.fbk.eu.OptimizeEnergyPLANWithAccuracy.problem.EnergyPLANProblemStep1;
import reet.fbk.eu.jmetal.initialization.EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import jmetal.qualityIndicator.*;
public class AverageAllQualityIndicatorValuesWithGenerations {
int noOfFiles;
File fs[];
File fileAvg;
FileWriter fwAvg;
BufferedWriter bwAvg;
/**
* Constructor
*
* @param problem
* The problem
* @param paretoFrontFile
* Pareto front file
*/
public AverageAllQualityIndicatorValuesWithGenerations(String folderName,
String indicators) {
fs = new File(folderName + "\\" + indicators).listFiles();
noOfFiles = fs.length;
fileAvg = new File(folderName + "\\" + indicators + "\\Avg");
try {
if (!fileAvg.exists()) {
fileAvg.createNewFile();
}
fwAvg = new FileWriter(fileAvg.getAbsoluteFile());
bwAvg = new BufferedWriter(fwAvg);
} catch (IOException e) {
e.printStackTrace();
}
} // Constructor
double[] readFile(String path) {
double data[] = new double[70];
try {
/* Open the file */
FileInputStream fis = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
int i = 0;
String aux = br.readLine();
while (aux != null) {
String str[] = aux.split(" ");
data[i++] = Double.parseDouble(str[1]);
aux = br.readLine();
}
br.close();
return data;
} catch (Exception e) {
System.out
.println("jmetal.qualityIndicator.util.readNonDominatedSolutionSet: "
+ path);
e.printStackTrace();
}
return null;
}
public void doAverageCalcutation() throws IOException {
double[][] allData = new double[70][fs.length];
for (int i = 0; i < noOfFiles; i++) {
double data[] = readFile(fs[i].getPath());
for (int j = 0; j<data.length;j++){
allData[j][i] = data[j];
}
}
for (int i = 0; i < 70; i++) {
double sum=0.0;
for(int j=0;j<noOfFiles;j++){
sum+=allData[i][j];
}
double avg = sum/noOfFiles;
bwAvg.write((i+1)+ " " +avg+"\n");
}
bwAvg.close();
}
/**
* @param args
* [0] absolute path of a folder that contain all the FUN files
* for different runs
* @param args
* [1] absolute path of the true Pareto front
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AverageAllQualityIndicatorValuesWithGenerations calGD = new AverageAllQualityIndicatorValuesWithGenerations(
args[0], "GD");
AverageAllQualityIndicatorValuesWithGenerations calIGD = new AverageAllQualityIndicatorValuesWithGenerations(
args[0], "IGD");
AverageAllQualityIndicatorValuesWithGenerations calHV = new AverageAllQualityIndicatorValuesWithGenerations(
args[0], "HV");
AverageAllQualityIndicatorValuesWithGenerations calEps = new AverageAllQualityIndicatorValuesWithGenerations(
args[0], "Epsilon");
AverageAllQualityIndicatorValuesWithGenerations calSpd = new AverageAllQualityIndicatorValuesWithGenerations(
args[0], "Spread");
try {
calEps.doAverageCalcutation();
calGD.doAverageCalcutation();
calIGD.doAverageCalcutation();
calHV.doAverageCalcutation();
calSpd.doAverageCalcutation();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>This is the results of 10 different runs with 10 different seed.
Here mutation based on domain knowledge is applies with SBX crossover.
It mutation is designed to work in 3 stages.
25% times, mutation favor RE sources.
25% times mutation favor conventation energies.
rest of the time Ploynomial mutation is used.
Population: 100
Evolution: 5000
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 4
Algorithm: NSGA-II
selection: Binary Tournament 2.
seed [] = {545782, 455875, 547945, 458478, 981354, 652262, 562366, 365652, 456545, 549235 };
Now this simutation will run track the evolution of hypervolume.<file_sep>Three objective results with storage capacity<file_sep>The true Paretofrot is the merge of two separate run.
1. SBX_Poly
2. SBX_DKMutation probability 0.4<file_sep>This is the results of 10 different runs with 10 different seed.
polynomial mutation is applies with SBX crossover.
Population: 100
Evolution: 5000
ArchiveSize: 100
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 4
Algorithm: SPEA2
selection: Binary Tournament
long seed[]={102354,986587,456987,159753, 216557,589632,471259,523486,4158963,745896};
<file_sep>This is the results of 10 different runs with 10 different seed.
Here mutation based on domain knowledge (modified polynomial mutation) is applies with SBX crossover.
It mutation is designed to work in 3 stages.
mutation probability of applying different types of mutation (RE favor, CE favor, generic mutataion) depends of generation. In the early generation, two favor mutation is moslt applied, after some generation the probability goes down and the probability of applying generic mutation goes up.
Population: 100
Evolution: 5000
ArchiveSize: 100
crossover Probabilty: 0.9
Mutation probability: 0.2
Distribution index: 4
Algorithm: SPEA2
selection: Binary Tournament.
long seed[]={102354,986587,456987,159753, 216557,589632,471259,523486,4158963,745896};
<file_sep>The 4 results are produced by NSGAII for Aalborg data.
There are 6 decision variable (CHP group 3, HP for group 3, PP, wind, offshore wind, PV).
There are two objectives (CO2 emssion and annual cost).
There are three constraints.
1. Maximumimport <=160
2. minimum grid stablization factor >=100
3. Annual heat balance <=0
NSGAII parameters:
population: 100
max evaluation: 15000
Crossover: SBXCrossover, probability: 0.9, distribution index: 10
Mutation: PolynomialMutation, Probability: 1.0/problem.getNumberOfVariables(), distribution index: 10
selection: binary tournament
This results are generated where PP capccity is determine by optimizer.<file_sep>package reet.fbk.eu.jmetal.initialization;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.FileHandler;
import jmetal.core.Algorithm;
import jmetal.core.Operator;
import jmetal.core.Problem;
import jmetal.core.SolutionSet;
import reet.fbk.eu.jmetal.initialization.metaheuristics.nsgaII.NSGAIIForSI;
import reet.fbk.eu.jmetal.initialization.metaheuristics.nsgaII.NSGAIITrackIndicators;
import reet.fbk.eu.jmetal.initialization.metaheuristics.spea2.SPEA2ForSI;
import reet.fbk.eu.jmetal.initialization.metaheuristics.spea2.SPEA2TrackIndicators;
import jmetal.metaheuristics.nsgaII.NSGAII;
import jmetal.metaheuristics.spea2.SPEA2;
import jmetal.operators.crossover.CrossoverFactory;
import jmetal.operators.selection.SelectionFactory;
import jmetal.qualityIndicator.QualityIndicator;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import jmetal.util.RandomGenerator;
//import reet.fbk.eu.jmetal.operators.mutation.MutationFactory;
import jmetal.operators.mutation.MutationFactory;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* The class is main class where the class can execute algorithm from the command line
* argument. The class run different algorithm to track different indicators for each
* generation/.
*
*/
class NSGAII_RunWithTracking {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
long NSGAII_seeds[] = { 545782, 455875, 547945, 458478, 981354, 652262,
562366, 365652, 456545, 549235 };
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
String path = "InitializationResults\\WithTrack\\NSGAII";
public void run() throws SecurityException, IOException {
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
for (int i = 0; i < 10; i++) {
PseudoRandom
.setRandomGenerator(new RandomGenerator(NSGAII_seeds[i]));
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolutionForThread(
"Real", path);
indicators = new QualityIndicator(problem,
".\\InitializationResults\\ParetoFront\\mergeFUN.pf");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
parameters = new HashMap();
algorithm = new NSGAIITrackIndicators(problem, NSGAII_seeds[i], path);
// algorithm = new ssNSGAII(problem);
// indicators = new QualityIndicator(problem,
// "C:\\Users\\Nusrat\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\Results\\truePf\\mergefun.pf")
// ;
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 7000);
algorithm.setInputParameter("indicators", indicators);
try {
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator(
"SBXCrossover", parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// mutation =
// MutationFactory.getMutationOperator("GeneralRealMutationForRes",
// . parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament2", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile(path + "\\VAR_seed_"
+ NSGAII_seeds[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile(path + "\\FUN_seed_"
+ NSGAII_seeds[i]);
} catch (JMException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class NSGAII_SI_RunWithTracking {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
long NSGAII_SI_seeds[] = { 343434, 551254, 145845, 555541, 551641, 625882,
985312, 458745, 228424, 7811554 };
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
String path = "InitializationResults\\WithTrack\\NSGAII_SI";
public void run() throws SecurityException, IOException {
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_SI_main.log");
logger_.addHandler(fileHandler_);
File folder = new File("InitializationResults/InitIndividualWithSI");
File[] listOfFiles = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("Init");
}
});
for (int i = 0; i < NSGAII_SI_seeds.length; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(
NSGAII_SI_seeds[i]));
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolutionForThread(
"Real", path);
indicators = new QualityIndicator(problem,
".\\InitializationResults\\ParetoFront\\mergeFUN.pf");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
Boolean favorGenesforRE[] ={true, true, true, true, true};
Boolean favorGenesforConventionalPP[] ={false, false, false, false, false};
parameters = new HashMap();
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForCon", favorGenesforConventionalPP);
parameters.put("InitialPopulationFile", listOfFiles[i].getAbsolutePath());
algorithm = new NSGAIIForSI(problem, NSGAII_SI_seeds[i], path, parameters);
// algorithm = new ssNSGAII(problem);
// indicators = new QualityIndicator(problem,
// "C:\\Users\\Nusrat\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\Results\\truePf\\mergefun.pf")
// ;
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 7000);
algorithm.setInputParameter("indicators", indicators);
try {
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator(
"SBXCrossover", parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// mutation =
// MutationFactory.getMutationOperator("GeneralRealMutationForRes",
// . parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament2", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile(path + "\\VAR_seed_"
+ NSGAII_SI_seeds[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile(path + "\\FUN_seed_"
+ NSGAII_SI_seeds[i]);
} catch (JMException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SPEA2_RunWithTracking {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
long seed[]={
126113,
148456,
154568,
212139,
274587,
289982,
368817,
387808,
418353,
430544,
434057,
447514,
458475,
467542,
471922,
500024,
585464,
596970,
622980,
632376,
686544,
712584,
784248,
808035,
833359,
879899,
888346,
953022,
975572,
983349
};
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
String path = "InitializationResults\\WithTrack\\SPEA2";
public void run(int populationSize, int maxEvaluations) throws SecurityException, IOException, ClassNotFoundException, JMException{
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("SPEA2_main.log");
logger_.addHandler(fileHandler_);
int numberOfRun = 30;
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom
.setRandomGenerator(new RandomGenerator(seed[i]));
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
indicators = new QualityIndicator(problem,
".\\InitializationResults\\ParetoFront\\WithoutRM\\With_mutation_pr_0.1\\mergeFUN.pf");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
parameters = new HashMap();
algorithm = new SPEA2TrackIndicators(problem, seed[i], path);
// Algorithm parameters
// Algorithm parameters
algorithm.setInputParameter("populationSize", populationSize);
algorithm.setInputParameter("maxEvaluations", maxEvaluations);
algorithm.setInputParameter("archiveSize", populationSize);
algorithm.setInputParameter("indicators", indicators);
try {
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator(
"SBXCrossover", parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// mutation =
// MutationFactory.getMutationOperator("GeneralRealMutationForRes",
// . parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament2", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile(path + "\\VAR_seed_"
+ seed[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile(path + "\\FUN_seed_"
+ seed[i]);
} catch (JMException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SPEA2_SI_RunWithTracking {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
String path = "InitializationResults\\WithTrack\\SPEA2_SI";
public void run(int populationSize, int maxEvaluations) throws SecurityException, IOException, JMException, ClassNotFoundException{
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("SPEA2_SI_main.log");
logger_.addHandler(fileHandler_);
int numberOfRun=30;
long seed[]={
125386,
145295,
158570,
207621,
227297,
243858,
354528,
356090,
378578,
384873,
425374,
437331,
461628,
538947,
544774,
631545,
637384,
647647,
647848,
712308,
733779,
764889,
857578,
866208,
867882,
878532,
891747,
917083,
919749,
957363
};
/*File folder = new File("InitializationResults/InitIndividualWithSI");
File[] listOfFiles = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("Init");
}
});*/
File[] listOfFiles = new File[numberOfRun] ;
/*long initSeed[] = { 144759,
271439,
445964,
494817,
530563,
724859,
746153,
747584,
866309,
938562};
*/
/*long initSeed[] = {
172480,
242648,
268602,
272313,
412455,
441996,
633160,
814562,
822805,
843288
};*/
long initSeed[]={
125742,
144759,
172480,
242648,
245454,
268602,
271439,
272313,
412455,
441996,
445964,
447551,
455411,
455885,
494817,
530563,
545454,
565656,
633160,
714451,
724859,
746153,
747584,
752453,
814562,
822805,
843288,
844545,
866309,
938562
};
for(int i=0;i<numberOfRun;i++){
listOfFiles[i] = new File("InitializationResults/InitIndividualWithSI/WithoutRM/InitIndv_seed_"+initSeed[i]);
}
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(seed[i]));
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution("Real");
indicators = new QualityIndicator(problem,
".\\InitializationResults\\ParetoFront\\WithoutRM\\With_mutation_pr_0.1\\mergeFUN.pf");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
Boolean favorGenesforRE[] ={true, true, true, true, true};
Boolean favorGenesforConventionalPP[] ={false, false, false, false, false};
parameters = new HashMap();
parameters.put("favorGenesforRE", favorGenesforRE);
parameters.put("favorGenesForCon", favorGenesforConventionalPP);
parameters.put("InitialPopulationFile", listOfFiles[i].getAbsolutePath());
algorithm = new SPEA2ForSI(problem, seed[i], path, parameters);
// Algorithm parameters
// Algorithm parameters
algorithm.setInputParameter("populationSize", populationSize);
algorithm.setInputParameter("maxEvaluations", maxEvaluations);
//for spea2
algorithm.setInputParameter("archiveSize", populationSize);
algorithm.setInputParameter("indicators", indicators);
try {
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator(
"SBXCrossover", parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// mutation =
// MutationFactory.getMutationOperator("GeneralRealMutationForRes",
// . parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament2", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population.printVariablesToFile(path + "\\VAR_seed_"
+ seed[i]);
logger_.info("Objectives values have been writen to file FUN");
population.printObjectivesToFile(path + "\\FUN_seed_"
+ seed[i]);
} catch (JMException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
public class AalborgProblemWithTrackingMain {
public static Logger logger_; // Logger object
public static FileHandler fileHandler_; // FileHandler object
public static void main(String[] args) throws JMException,
SecurityException, IOException, ClassNotFoundException {
/* logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
Problem problem; // The problem to solve
Algorithm algorithm; // The algorithm to use
Operator crossover; // Crossover operator
Operator mutation; // Mutation operator
Operator selection; // Selection operator
HashMap parameters; // Operator parameters
QualityIndicator indicators; // Object to get quality indicators
long SPEA2_seeds[] = { 154568, 148456, 447514, 458475, 274587, 712584,
975572, 585464, 467542, 686544 };
long SPEA2_SI_seeds[] = { 857578, 647647, 647848, 891747, 957363,
538947, 425374, 637384, 125386, 243858 };
int numberOfRun = 10;
for (int i = 0; i < numberOfRun; i++) {
PseudoRandom.setRandomGenerator(new RandomGenerator(SPEA2_seeds[i]));
indicators = null;
problem = new EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolutionForThread(
"Real", "InitializationResults\\WithTrack\\SPEA2");
// algorithm = new NSGAIITrackIndicators(problem, seed[i],
// "SBX_DKMutation");
parameters = new HashMap();
algorithm = new SPEA2(problem);
// algorithm = new ssNSGAII(problem);
// indicators = new QualityIndicator(problem,
// "C:\\Users\\Nusrat\\Documents\\GitHub\\EnergyPLANDomainKnowledgeEAStep1\\Results\\truePf\\mergefun.pf")
// ;
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 7000);
algorithm.setInputParameter("archiveSize", 100);
// Mutation and Crossover for Real codification
parameters = new HashMap();
parameters.put("probability", 0.9);
parameters.put("distributionIndex", 10.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover",
parameters);
parameters = new HashMap();
parameters.put("probability", 0.1);
parameters.put("distributionIndex", 10.0);
mutation = MutationFactory.getMutationOperator(
"PolynomialMutation", parameters);
// mutation =
// MutationFactory.getMutationOperator("GeneralRealMutationForRes",
// . parameters);
// Selection Operator
parameters = null;
selection = SelectionFactory.getSelectionOperator(
"BinaryTournament2", parameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
// Result messages
logger_.info("Total execution time: " + estimatedTime + "ms");
logger_.info("Variables values have been writen to file VAR");
population
.printVariablesToFile("InitializationResults\\SPEA2WithoutTrack\\VAR_seed_"
+ SPEA2_seeds[i]);
logger_.info("Objectives values have been writen to file FUN");
population
.printObjectivesToFile("InitializationResults\\SPEA2WithoutTrack\\FUN_seed_"
+ SPEA2_seeds[i]);
}*/
if(args[0].equals("NSGAII")){
NSGAII_RunWithTracking nsgaii = new NSGAII_RunWithTracking();
nsgaii.run();
}else if(args[0].equals("NSGAII_SI")){
NSGAII_SI_RunWithTracking nsgaii_si = new NSGAII_SI_RunWithTracking();
nsgaii_si.run();
}else if(args[0].equals("SPEA2")){
SPEA2_RunWithTracking spea2 = new SPEA2_RunWithTracking();
spea2.run(100, 7000);
}else if(args[0].equals("SPEA2_SI")){
SPEA2_SI_RunWithTracking spea2_si = new SPEA2_SI_RunWithTracking();
spea2_si.run(100,7000);
}
}
}
<file_sep>package reet.fbk.eu.jmetal.operators.mutation.DKRE;
//BitFlipMutation.java
//
//Author:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
//
//Copyright (c) 2011 <NAME>, <NAME>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import jmetal.core.Solution;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.BinarySolutionType;
import jmetal.encodings.solutionType.IntSolutionType;
import jmetal.encodings.variable.Binary;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntAndRealSolutionType;
import reet.fbk.eu.jmetal.encodings.solutionType.BinaryIntSolutionType;
import reet.fbk.eu.jmetal.encodings.variable.BinaryInt;
import jmetal.operators.mutation.*;
/**
* This class implements a bit flip mutation operator. NOTE: the operator is
* applied to binary or integer solutions, considering the whole solution as a
* single encodings.variable.
*/
public class BitFlipMutationFavorMaximizationOfRes extends Mutation {
/**
* Valid solution types to apply this operator
*/
private static final List VALID_TYPES = Arrays
.asList(BinaryIntSolutionType.class);
private Double bitFlipMutationProbability_ = null;
private static boolean favorGenes[] = new boolean[] { true, true, true,
false };
/**
* Constructor Creates a new instance of the Bit Flip mutation operator
*/
public BitFlipMutationFavorMaximizationOfRes(
HashMap<String, Object> parameters) {
super(parameters);
if (parameters.get("bitFlipMutationProbability") != null)
bitFlipMutationProbability_ = (Double) parameters
.get("bitFlipMutationProbability");
} // BitFlipMutation
/**
* Perform the mutation operation
*
* @param probability
* Mutation probability
* @param solution
* The solution to mutate
* @throws JMException
*/
public void doMutation(double probability, Solution solution)
throws JMException {
try {
if (solution.getType().getClass() == BinaryIntAndRealSolutionType.class) {
for (int i = 0; i < solution.getDecisionVariables().length; i++) {
// do mutation on all variables
// for (int j = 0; j < ((Binary)
// solution.getDecisionVariables()[i]).getNumberOfBits();
// j++) {
if (solution.getDecisionVariables()[i].getClass() == BinaryInt.class) {
// check if the probability is greater than a given
// probability
if (PseudoRandom.randDouble() < probability) {
if (favorGenes[i] == true) {
/*
* int position = (int) Math.ceil(Math
* .sqrt(PseudoRandom.randInt(0, (int) Math
* .pow((((BinaryInt) solution
* .getDecisionVariables()[i])
* .getNumberOfBits()), 2)))) + 1;
*/
int numberOfBits = (((BinaryInt) solution
.getDecisionVariables()[i])
.getNumberOfBits());
int position, random_number, attempt = 0;
// check if in the "position", the bit is 0.
// otherwise try to get another position
// and this attempt will do for 50 times,
// because if
// all bits are '1', then it will put into
// infinite
// loop
do {
++attempt;
random_number = PseudoRandom
.randInt(1, ((int) Math.pow(2,
numberOfBits) - 1));
position = (int) Math.floor(Math
.log(random_number) / Math.log(2));
} while (((BinaryInt) solution
.getDecisionVariables()[i]).bits_
.get(position) != false
|| attempt <= 50);
((BinaryInt) solution.getDecisionVariables()[i]).bits_
.flip(position);
} else {
int position = PseudoRandom.randInt(0,
((BinaryInt) solution
.getDecisionVariables()[i])
.getNumberOfBits() - 1);
((BinaryInt) solution.getDecisionVariables()[i]).bits_
.flip(position);
}
}
}
}
for (int i = 0; i < solution.getDecisionVariables().length; i++) {
if (solution.getDecisionVariables()[i].getClass() == BinaryInt.class) {
((BinaryInt) solution.getDecisionVariables()[i])
.decode();
if (((BinaryInt) solution.getDecisionVariables()[i])
.getValue() > ((BinaryInt) solution
.getDecisionVariables()[i]).getUpperBound()) {
((BinaryInt) solution.getDecisionVariables()[i])
.setValue(((BinaryInt) solution
.getDecisionVariables()[i])
.getUpperBound());
} else if (((BinaryInt) solution.getDecisionVariables()[i])
.getValue() < ((BinaryInt) solution
.getDecisionVariables()[i]).getLowerBound()) {
((BinaryInt) solution.getDecisionVariables()[i])
.setValue(((BinaryInt) solution
.getDecisionVariables()[i])
.getLowerBound());
}
}
// ((Binary) solution.getDecisionVariables()[i]).decode();
}
} // if
// else
} catch (ClassCastException e1) {
Configuration.logger_.severe("BitFlipMutation.doMutation: "
+ "ClassCastException error" + e1.getMessage());
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".doMutation()");
}
} // doMutation
/**
* Executes the operation
*
* @param object
* An object containing a solution to mutate
* @return An object containing the mutated solution
* @throws JMException
*/
public Object execute(Object object) throws JMException {
Solution solution = (Solution) object;
if (!VALID_TYPES.contains(solution.getType().getClass())) {
Configuration.logger_
.severe("BitFlipMutation.execute: the solution "
+ "is not of the right type. The type should be 'Binary', "
+ "'BinaryReal' or 'Int', but "
+ solution.getType() + " is obtained");
Class cls = java.lang.String.class;
String name = cls.getName();
throw new JMException("Exception in " + name + ".execute()");
} // if
doMutation(bitFlipMutationProbability_, solution);
return solution;
} // execute
} // BitFlipMutation
<file_sep>package reet.fbk.eu.jmetal.initialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import reet.fbk.eu.OptimizeEnergyPLANWithStep.EnergyPLANProblemWithStep;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.core.SolutionSet;
import jmetal.problems.ZDT.ZDT1;
import jmetal.util.JMException;
import jmetal.util.PseudoRandom;
import matlabcontrol.*;
import matlabcontrol.extensions.MatlabTypeConverter;
/*
* This class is responsible for doing Domain-knowledge initialization
*/
public class DKInitialization4D {
SolutionSet initialSolutions;
Problem problem_;
Boolean REFavorGenes[], ConFavorGenes[], LFCFavorGenes[], ESDFavorGenes[];
Random rm;
MatlabProxy proxy;
int populationSize, numberOfIndevPerCombination,numberOfRandomSolutions;
double theta;
int maxDistributionIndex;
public DKInitialization4D(Problem problem_, Boolean REFavorGenes[],
Boolean ConFavorGene[], Boolean LFCFavorGenes[],Boolean ESDFavorGenes[],
int populationSize, double theta, int maxDistributionIndex,
int numberOfIndevPerCombination, int numberOfRandomSolutions, MatlabProxy proxy)
throws MatlabInvocationException {
this.REFavorGenes = REFavorGenes;
this.ConFavorGenes = ConFavorGene;
this.LFCFavorGenes = LFCFavorGenes;
this.ESDFavorGenes = ESDFavorGenes;
this.populationSize = populationSize;
this.theta = theta;
this.maxDistributionIndex = maxDistributionIndex;
this.numberOfIndevPerCombination = numberOfIndevPerCombination;
this.numberOfRandomSolutions=numberOfRandomSolutions;
this.problem_ = problem_;
rm = new Random();
initialSolutions = new SolutionSet(10000);
this.proxy = proxy;
proxy.eval("addpath('C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/src/reet/fbk/eu/jmetal/initialization')");
}
public DKInitialization4D(Problem problem_, Boolean REFavorGenes[],
Boolean ConFavorGene[], int populationSize, double theta,
int maxDistributionIndex, int numberOfIndevPerCombination, int numberOfRandomSolutions,
MatlabProxy proxy) throws MatlabInvocationException {
this.REFavorGenes = REFavorGenes;
this.ConFavorGenes = ConFavorGene;
this.populationSize = populationSize;
this.theta = theta;
this.maxDistributionIndex = maxDistributionIndex;
this.numberOfIndevPerCombination = numberOfIndevPerCombination;
this.numberOfRandomSolutions=numberOfRandomSolutions;
this.problem_ = problem_;
rm = new Random();
initialSolutions = new SolutionSet(10000);
this.proxy = proxy;
proxy.eval("addpath('C:/Users/mahbub/Documents/GitHub/EnergyPLANDomainKnowledgeEAStep1/src/reet/fbk/eu/jmetal/initialization')");
}
public void generateInitialSolutions() {
}
public void generateInitialSolutionFavorRE() throws ClassNotFoundException,
JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (REFavorGenes[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (REFavorGenes[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateInitialSolutionFavorCon()
throws ClassNotFoundException, JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (ConFavorGenes[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (ConFavorGenes[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateInitialSolutionFavorLFC()
throws ClassNotFoundException, JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (LFCFavorGenes[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (LFCFavorGenes[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateInitialSolutionFavorESD()
throws ClassNotFoundException, JMException {
for (int no = 0; no < combinationsArray.size(); no++) {
Integer[] aCombination = combinationsArray.get(no);
aCombination = TransformArray(aCombination);
for (int z = 0; z < numberOfIndevPerCombination; z++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
try {
if (ESDFavorGenes[i] == true) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithIncreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
} else if (ESDFavorGenes[i] == false) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithDecreasedCapacity(
aCombination[i],
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
} catch (NullPointerException e) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
}
initialSolutions.add(sol);
}
}
}
public void generateRandomInitialSolutionWithoutFovor(int numberOfRandomIndividuals)
throws ClassNotFoundException, JMException {
for (int no = 0; no < numberOfRandomIndividuals; no++) {
Solution sol = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
sol.getDecisionVariables()[i]
.setValue(createGeneWithoutAnything(
problem_.getLowerLimit(i),
problem_.getUpperLimit(i)));
}
initialSolutions.add(sol);
}
}
public Integer[] TransformArray(Integer[] aCombination) {
Integer[] combination = new Integer[REFavorGenes.length];
int j = 0;
for (int i = 0; i < REFavorGenes.length; i++) {
try {
if (REFavorGenes[i] == true || REFavorGenes[i] == false) {
combination[i] = aCombination[j++];
}
} catch (NullPointerException e) {
combination[i] = -1;
}
}
return combination;
}
/*
*
*/
public double createGeneWithIncreasedCapacity(int n, double lowerBound,
double upperBound) {
double r = rm.nextDouble();
double delta = Math.pow(r, (1 / ((double) n + 1)));
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
/*
*
*/
public double createGeneWithDecreasedCapacity(int n, double lowerBound,
double upperBound) {
double r = rm.nextDouble();
double delta = 1 - Math.pow((1 - r), (1 / ((double) n + 1)));
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
public double createGeneWithoutAnything(double lowerBound, double upperBound) {
double r = rm.nextDouble();
double delta = r;
double dcv = lowerBound + (upperBound - lowerBound) * delta;
return dcv;
}
public SolutionSet doDKInitialization4D() throws ClassNotFoundException,
JMException, MatlabInvocationException, MatlabConnectionException {
/*
* generate all combinations
*/
// int maxDistributionIndex = 3;
initializeLengthAndCounter(maxDistributionIndex, REFavorGenes);
nestedLoopOperation(counters, length, 0);
/*
* generate two kinds of individuals by favoring RES and conventional
* energy
*/
generateInitialSolutionFavorRE();
generateInitialSolutionFavorCon();
generateInitialSolutionFavorLFC();
generateInitialSolutionFavorESD();
// generate some random solution
generateRandomInitialSolutionWithoutFovor(numberOfRandomSolutions);
sendPopulationToMatlab();
double[][] population = runMatlabCode();
/*
* Exit Matlab
*/
proxy.exit();
/*
* convert double into population set
*/
SolutionSet finalPopulation = new SolutionSet(populationSize);
for (int j = 0; j < populationSize; j++) {
Solution s = new Solution(problem_);
for (int i = 0; i < problem_.getNumberOfVariables(); i++) {
s.getDecisionVariables()[i].setValue(population[j][i] * 1500.0);
}
finalPopulation.add(s);
}
return finalPopulation;
}
public void sendPopulationToMatlab() throws MatlabInvocationException,
JMException {
proxy.eval("clear all");
String aMatrix;
aMatrix = "[";
for (int i = 0; i < initialSolutions.size(); i++) {
for (int j = 0; j < problem_.getNumberOfVariables(); j++) {
// diveded by 1500, maximum upper limit of all the decision
// variables
aMatrix = aMatrix
+ initialSolutions.get(i).getDecisionVariables()[j]
.getValue() / 1500.0 + " ";
}
aMatrix = aMatrix + ";";
}
aMatrix = aMatrix + "]";
proxy.eval("indvMatrix=" + aMatrix + ";");
}
public double[][] runMatlabCode() throws MatlabInvocationException {
proxy.eval("numberOfFinalIndv=" + populationSize + ";");
proxy.eval("theta=" + theta + ";");
proxy.eval("findIndvMaxDiversity");
double[][] population = new double[100][problem_.getNumberOfVariables()];
MatlabTypeConverter processor = new MatlabTypeConverter(proxy);
population = processor.getNumericArray("indMatrixTemp")
.getRealArray2D();
return population;
}
/*
* 486 code for generate all combinations
*/
int[] length;
int[] counters;
ArrayList<Integer[]> combinationsArray = new ArrayList<Integer[]>();
/*
* n: is the maximum value of the combinations
*/
void initializeLengthAndCounter(int n, Boolean[] favorGenes) {
combinationsArray.clear();
int combinationSize = 0;
for (int i = 0; i < favorGenes.length; i++) {
try {
if (favorGenes[i] == true || favorGenes[i] == false)
combinationSize++;
} catch (NullPointerException e) {
combinationSize++;
continue;
}
}
length = new int[combinationSize];
counters = new int[combinationSize];
for (int i = 0; i < combinationSize; i++) {
length[i] = n;
counters[i] = 0;
}
}
void nestedLoopOperation(int[] counters, int[] length, int level) {
if (level == counters.length)
performOperation(counters);
else {
for (counters[level] = 0; counters[level] < length[level]; counters[level]++)
nestedLoopOperation(counters, length, level + 1);
}
}
void performOperation(int[] counters) {
Integer[] counterAsString = new Integer[counters.length];
for (int level = 0; level < counters.length; level++) {
counterAsString[level] = counters[level];
// if(level < counters.length-1) counterAsString = counterAsString +
// ",";
}
System.out.println(Arrays.toString(counterAsString));
combinationsArray.add(counterAsString);
}
/*
* generate all combination: End
*/
/*
* test purpose
*/
public static void main(String args[]) throws ClassNotFoundException,
JMException, MatlabConnectionException, MatlabInvocationException {
Problem problem = new EnergyPLANProblemWithStep("Real");
Boolean REFavorGenes[] = new Boolean[] { true, true, true, null, false,
null, true };
Boolean ConFavorGenes[] = new Boolean[] { false, false, false, null,
true, null, false };
MatlabProxyFactory factory;
MatlabProxy proxy;
factory = new MatlabProxyFactory();
proxy = factory.getProxy();
DKInitialization4D dkini = new DKInitialization4D(problem, REFavorGenes,
ConFavorGenes, 100, 0.00005, 4, 3, proxy);
@SuppressWarnings("unused")
SolutionSet p = dkini.doDKInitialization();
}
}
<file_sep>Here, in this folder the result of deversity maximization is investigated. In this regards, new Pareto-front is generated. And the results is compared with other approach (the approach proposed in ASOC paper).
Folder description:
Pareto front: contain Pareto-front
NSGAII_WithoutRM_DivMax_Conf1: Contain the indicator results of NSGAII (with SI) Without random initialized silutions with diversity maximization with configuration 1 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrackWithSI\WithoutRM\DivMax\Configuration 1)
NSGAII_WithoutRM_DivMax_Conf2: Contain the indicator results of NSGAII (with SI) Without random initialized silutions with diversity maximization with configuration 2 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrackWithSI\WithoutRM\DivMax\Configuration 2)
NSGAII_WithoutRM_DivMax_Conf3: Contain the indicator results of NSGAII (with SI) Without random initialized silutions with diversity maximization with configuration 3 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrackWithSI\WithoutRM\DivMax\Configuration 3)
SPEA2_WithoutRM_DivMax_Conf1: Contain the indicator results of SPEA2 (with SI) Without random initialized silutions with diversity maximization with configuration 1 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrackWithSI\WithoutRM\DivMax\Configuration 1)
SPEA2_WithoutRM_DivMax_Conf2: Contain the indicator results of SPEA2 (with SI) Without random initialized silutions with diversity maximization with configuration 2 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrackWithSI\WithoutRM\DivMax\Configuration 2)
SPEA2_WithoutRM_DivMax_Conf3: Contain the indicator results of SPEA2 (with SI) Without random initialized silutions with diversity maximization with configuration 3 (refer to folder: C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrackWithSI\WithoutRM\DivMax\Configuration 3)
NSGAII_WithoutRM_SI: It the result of NSGAII with smart initialization result (report in ASOC paper, mutation probability 0.1), we take all FUN files (refer to C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrackWithSI\WithoutRM folder, mutation probability 0.1), because we want to calculate indicators' value with respect to new Pareto-front. And we do not want to delete those indicators' values which are reported in ASOC paper.
SPEA2_WithoutRM_SI: It the result of SPEA2 with smart initialization result (report in ASOC paper, mutation probability 0.1), we take all FUN files (refer to C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrackWithSI\WithoutRM folder, mutation probability 0.1), because we want to calculate indicators' value with respect to new Pareto-front. And we do not want to delete those indicators' values which are reported in ASOC paper.
NSGAII: it is the results of NSGAII with default configuration (see readme file inside the folder), we take all FUN file (refer to C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\NSGAIIWithoutTrack folder with mutation probability 0.1), because we want to calculate indicators' value with respect to new Pareto-front. And we do not want to delete those indicators' values which are reported in ASOC paper.
SPEA2: it is the results of SPEA2 with default configuration (see readme file inside the folder), we take all FUN file(refer to C:\Users\mahbub\Documents\GitHub\EnergyPLANDomainKnowledgeEAStep1\InitializationResults\SPEA2WithoutTrack folder with mutation probability 0.1), because we want to calculate indicators' value with respect to new Pareto-front. And we do not want to delete those indicators' values which are reported in ASOC paper.
<file_sep>This is the results (FUN and VAR) of 30 different runs with 30 different seeds with NSGAII with domain-knowledge mutation for.
Problem: EnergyPLANProblemAalborg2ObjectivesWith1EnergyPLANEvolution
Population: 100
Evolution: 7000
Crossover: SBX
Mutation: GeneralModifiedPolynomialMutationForEnergySystems (reet.fbk.eu.jmetal.operators.mutation.ModifiedPolynomial)
crossover Probabilty: 0.9
Mutation probability: 0.1
Distribution index: 10
Algorithm: NSGA-II
selection: Binary Tournament 2.
seed [] = {
161395,
170339,
259029,
276644,
288470,
309259,
353882,
365652,
370995,
455875,
456545,
458478,
468245,
515856,
545782,
547945,
549235,
562366,
626495,
652262,
668763,
683991,
698156,
714786,
756252,
930462,
981354,
989776,
992177,
999921
};
The seeds are same that is used in initilization experiment. It'll help to compare with typical NSGAII as two algorithms starts from same initialized individuals.
mergeFUN_NDK: merge all 30 runs fo NSGA-II with DK mutation
N.B.: these results are reported in ASOC paper<file_sep>package reet.fbk.eu.OptimizeEnergyPLANWithAccuracy.problem;
import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.encodings.variable.ArrayReal;
import jmetal.encodings.solutionType.ArrayRealSolutionType;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.util.JMException;
import jmetal.util.wrapper.XReal;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import reet.fbk.eu.OprimizeEnergyPLAN.file.parse.EnergyPLANFileParse;
public class EnergyPLANProblemStep1 extends Problem {
MultiMap energyplanmMap;
/**
* Creates a new instance of problem ZDT1.
*
* @param numberOfVariables
* Number of variables.
* @param solutionType
* The solution type must "Real", "BinaryReal, and "ArrayReal".
*/
public EnergyPLANProblemStep1(String solutionType) {
numberOfVariables_ = 7;
numberOfObjectives_ = 2;
numberOfConstraints_ = 1;
problemName_ = "OptimizeEnergyPLANWithAccuracy";
upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];
// Establishes upper and lower limits for the variables
int var;
for (var = 0; var < 4; var++) {
// capccities of wind, off-shore wind, PV and condencing power unit
lowerLimit_[var] = 0.0;
upperLimit_[var] = 20000.0;
} // for
for (; var < numberOfVariables_; var++) {
// share of coal, oil and natural-gas
lowerLimit_[var] = 0.0;
upperLimit_[var] = 1.0;
}
if (solutionType.compareTo("Real") == 0)
solutionType_ = new RealSolutionType(this);
else {
System.out.println("Error: solution type " + solutionType
+ " invalid");
System.exit(-1);
}
} // constructor end
/**
* Evaluates a solution.
*
* @param solution
* The solution to evaluate.
* @throws JMException
*/
public void evaluate(Solution solution) throws JMException {
writeModificationFile(solution);
String energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i \".\\EnergyPLAN_SEP_2013\\energyPlan data\\Data\\RefModelForOptimization.txt\" -m \"modification.txt\" -ascii \"result.txt\" ";
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParse epfp = new EnergyPLANFileParse(".\\result.txt");
energyplanmMap = epfp.parseFile();
Iterator it;
Collection<String> col;
col = (Collection<String>) energyplanmMap
.get("CO2-emission (total)");
it = col.iterator();
solution.setObjective(0, Double.parseDouble(it.next().toString()));
col = (Collection<String>) energyplanmMap.get("TOTAL ANNUAL COSTS");
it = col.iterator();
solution.setObjective(1, Double.parseDouble(it.next().toString()));
// check warning
col = (Collection<String>) energyplanmMap.get("WARNING");
if (col != null)
{
/* System.out.println("No warning");
}
else {*/
@SuppressWarnings("rawtypes")
Iterator it3 = col.iterator();
if (!it3.next().toString()
.equals("PP too small. Critical import is needed"))
throw new IOException("warning!!"+it3.next().toString());
//System.out.println("Warning " + it3.next().toString());
}
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
}
@SuppressWarnings("unchecked")
public void evaluateConstraints(Solution solution) throws JMException {
Iterator it;
Collection<String> col;
col = (Collection<String>) energyplanmMap.get("Maximumimport");
it = col.iterator();
int maximumImport = Integer.parseInt(it.next().toString());
double constrints = 2500 - maximumImport;
if (constrints < 0.0) {
solution.setOverallConstraintViolation(constrints);
solution.setNumberOfViolatedConstraint(1);
} else {
solution.setOverallConstraintViolation(0.0);
solution.setNumberOfViolatedConstraint(0);
}
}
void writeModificationFile(Solution solution) throws JMException {
DecimalFormat twoDForm = new DecimalFormat("0.00");
// wind
double RE1 = solution.getDecisionVariables()[0].getValue();
// off-shore wind
double RE2 = solution.getDecisionVariables()[1].getValue();
// PV
double RE3 = solution.getDecisionVariables()[2].getValue();
// condencing PP
double PP = solution.getDecisionVariables()[3].getValue();
// PP coal share
double PP_coal_share = solution.getDecisionVariables()[4].getValue();
// pp oil sahre
double PP_oil_share = solution.getDecisionVariables()[5].getValue();
// pp Ngas share
double PP_ngas_share = solution.getDecisionVariables()[6].getValue();
final double PP_coal_eff=0.35;
final double PP_oil_eff=0.45;
final double PP_ngas_eff=0.55;
//efficiency calculation for PP
//normalized the share
double nor_PP_coal_share = PP_coal_share / (PP_coal_share+PP_oil_share+PP_ngas_share);
double nor_PP_oil_share = PP_oil_share / (PP_coal_share+PP_oil_share+PP_ngas_share);
double nor_PP_ngas_share = PP_ngas_share / (PP_coal_share+PP_oil_share+PP_ngas_share);
double overall_eff_other = ((PP*nor_PP_coal_share)*PP_coal_eff + (PP*nor_PP_oil_share)*PP_oil_eff + (PP*nor_PP_ngas_share)*PP_ngas_eff)/PP;
//efficiency calculation from Dr. Marco
double overall_eff_marco = 1 / ((nor_PP_coal_share/PP_coal_eff) + (nor_PP_oil_share/PP_oil_eff) + (nor_PP_ngas_share/PP_ngas_eff) ) ;
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) RE1;
bw.write(str);
bw.newLine();
str = "input_RES2_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) RE2;
bw.write(str);
bw.newLine();
str = "input_RES3_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) RE3;
bw.write(str);
bw.newLine();
str = "input_cap_pp_el=";
bw.write(str);
bw.newLine();
str = "" + (int) PP;
bw.write(str);
bw.newLine();
str = "input_fuel_PP[1]=";
bw.write(str);
bw.newLine();
str = "" + twoDForm.format(PP_coal_share);
bw.write(str);
bw.newLine();
str = "input_fuel_PP[2]=";
bw.write(str);
bw.newLine();
str = "" + twoDForm.format(PP_oil_share);
bw.write(str);
bw.newLine();
str = "input_fuel_PP[3]=";
bw.write(str);
bw.newLine();
str = "" + twoDForm.format(PP_ngas_share);
bw.write(str);
bw.newLine();
str = "input_eff_pp_el=";
bw.write(str);
bw.newLine();
str = "" + twoDForm.format(overall_eff_marco);
bw.write(str);
bw.newLine();
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>[DocHistory]
FileCount=27
File0=energyPlan Data\Data\CIES_Complete_Current_V161.txt
File1=C:\Users\shaik\eclipse-workspace\EnergyPLANDomainKnowledgeEA\src\reet\fbk\eu\OptimizeEnergyPLANCIVIS\CEIS\data\CEIS_Complete_Current.txt
File2=energyPlan Data\Data\testSolar.txt
File3=energyPlan Data\Data\CEIS_2030_BAU.txt
File4=energyPlan Data\Data\CEIS_2050_BAU.txt
File5=energyPlan Data\Data\solarThermalProb.txt
File6=spool\modifiedInput6.txt
File7=spool\modifiedInput5.txt
File8=spool\modifiedInput4.txt
File9=spool\modifiedInput3.txt
File10=spool\modifiedInput2.txt
File11=spool\modifiedInput1.txt
File12=spool\modifiedInput0.txt
File13=energyPlan Data\Data\initalize.txt
File14=energyPlan Data\Data\Aalborg2050_vision.txt
File15=energyPlan Data\Data\2050 IDA technical closed new_DK100pct.txt
File16=energyPlan Data\Data\2050 IDA market open new - v2_DK100pct.txt
File17=energyPlan Data\Data\IDA2030_anbefalinger.txt
File18=energyPlan Data\Data\IDA2030_anbefalinger+biogas.txt
File19=energyPlan Data\Data\DK2020_2018edition.txt
File20=energyPlan Data\Data\IDA2035-market-v1_latest.txt
File21=energyPlan Data\Data\IDA2030_update.txt
File22=energyPlan Data\Data\IDA2030_ref+BF19.txt
File23=energyPlan Data\Data\2035 IDA market open new.txt
File24=energyPlan Data\Data\IDA2035-market-v1.txt
File25=energyPlan Data\Data\IDA2030_ref.txt
File26=energyPlan Data\Data\2035 IDA market open new - v2.txt
<file_sep>package reet.fbk.eu.OptimizeEnergyPLANCIVIS.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import jmetal.core.Solution;
import jmetal.util.JMException;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import reet.fbk.eu.OptimizeEnergyPLANCIVIS.ParseFile.EnergyPLANFileParseForCivis;
;
public class ExtractEnergyPLANParametersAlter13Objectives {
// static MultiMap energyplanmMap;
static String inputs[] = { "PV_Cap", "HP_Cap", "OilBoilerHeat", "NgasBoilerHeat", "BiomassBoilerHeat" };
static String outputs[] = { "AnnualPV", "Annualimport", "Annualexport",
"OilBoilerFuel", "NgasBoilerFuel", "BiomassBoilerFuel",
"Gasoil/Diesel", "Total Ngas Exchange costs", "Biomass",
"Total Electricity exchange", "Total variable costs",
"Fixed operation costs", "AdditionalCost", "InvestmentCost",
"CO2-emission (corrected)", "AnnualCost", "LoadFollowingCapacity"};
int currentPVCapacity, currentHydroCapacity;
//double OilBoilerHeatdemand, nGasBoilerHeatDemand, biomassBoilerHeatDemand;
double maxHeatDemandInScaleOf1;
double totalHeatdemand, currentNumberOfBoilers;
int boilerLifeTime, PVLifeTime, HydroLifeTime, geoBoreHoleLifeTime;
double interest;
double COP;
public ExtractEnergyPLANParametersAlter13Objectives(String siteName) {
// TODO Auto-generated constructor stub
if (siteName.equals("CEIS")) {
currentPVCapacity = 5328;
currentHydroCapacity = 4000;
/*OilBoilerHeatdemand = 6.51;
nGasBoilerHeatDemand = 4.00;
biomassBoilerHeatDemand = 15.54;*/
boilerLifeTime = 20;
PVLifeTime = 25;
HydroLifeTime = 20;
geoBoreHoleLifeTime = 100;
interest = 0.04;
COP = 3.2;
maxHeatDemandInScaleOf1 = 0.000312745;
totalHeatdemand = 26.05;
currentNumberOfBoilers = 12220;
} else if (siteName.equals("CEDIS")) {
currentPVCapacity = 5566;
currentHydroCapacity = 4592;
boilerLifeTime = 20;
PVLifeTime = 25;
HydroLifeTime = 20;
interest = 0.04;
geoBoreHoleLifeTime = 100;
COP = 3.2;
maxHeatDemandInScaleOf1 = 0.000322065;
} else
System.exit(-1);
}
public static void main(String[] args) throws IOException {
MultiMap energyplanmMap = null;
// TODO Auto-generated method stub
ExtractEnergyPLANParametersAlter13Objectives ob = new ExtractEnergyPLANParametersAlter13Objectives(
args[1]);
FileInputStream fos = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fos);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
energyplanmMap = ob.simulateEnergyPLAN(line, args[1]);
ob.WriteEnergyPLANParametersToFile(energyplanmMap, args[0]);
}
br.close();
}
void WriteEnergyPLANParametersToFile(MultiMap energyPLANMap, String path)
throws IOException {
Iterator it;
Collection<String> col;
File filetmp = new File(path);
String arrayStr[] = path.split("\\\\");
File file = new File(filetmp.getParent() + "\\allParameters_"
+ arrayStr[arrayStr.length - 1] + ".txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
// create header of the file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("PV_C HP_Heat_P OilBoilerHeat NgasBoilerHeat BiomassBoilerHeat "
+ "AnlPV_P AnlImport AnlExport AnlOilBoilerFuel AnlNgasBoilerFuel "
+ "AnlBiomassBoilerFuel AnlOilCost AnlLPGCost AnlBiomassCost AnlElecExchage TotalVariableCost FixedOperationalCost "
+ "AdditionalCost InvestmentCost CO2Emission AnnualCost LoadFollowingCapacity");
bw.newLine();
bw.write("(KW) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) (GWh) "
+ "(GWh) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) (KEuro) "
+ "(Mt) (KEuro)");
bw.newLine();
bw.close();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
String input = "", output = "";
for (int i = 0; i < inputs.length; i++) {
col = (Collection<String>) energyPLANMap.get(inputs[i]);
it = col.iterator();
input = input + it.next() + " ";
}
for (int i = 0; i < outputs.length; i++) {
col = (Collection<String>) energyPLANMap.get(outputs[i]);
it = col.iterator();
String str = it.next().toString();
if (str.endsWith("1000")) {
str = str.substring(0, str.lastIndexOf("1000"));
str = Double.parseDouble(str) + "";
}
output = output + str + " ";
}
bw.write(input + output);
bw.newLine();
bw.close();
}
MultiMap simulateEnergyPLAN(String individual, String siteName) {
MultiMap energyplanMap = null;
MultiMap modifyMap = new MultiValueMap();
modifyMap = writeModificationFile(individual);
String energyPLANrunCommand="";
if (siteName.equals("CEIS")) {
energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i "
+ "\".\\src\\reet\\fbk\\eu\\OptimizeEnergyPLANCIVIS\\CEIS\\data\\Civis_CEIS.txt\" "
+ "-m \"modification.txt\" -ascii \"result.txt\" ";
} else {
energyPLANrunCommand = ".\\EnergyPLAN_SEP_2013\\EnergyPLAN.exe -i "
+ "\".\\src\\reet\\fbk\\eu\\OptimizeEnergyPLANCIVIS\\CEdiS\\CediS_data.txt\" "
+ "-m \"modification.txt\" -ascii \"result.txt\" ";
}
try {
// Process process = new
// ProcessBuilder(energyPLANrunCommand).start();
Process process = Runtime.getRuntime().exec(energyPLANrunCommand);
process.waitFor();
process.destroy();
EnergyPLANFileParseForCivis epfp = new EnergyPLANFileParseForCivis(
".\\result.txt");
energyplanMap = epfp.parseFile();
energyplanMap.putAll(modifyMap);
Iterator it;
Collection<String> col;
col = (Collection<String>) energyplanMap.get("TOTAL ANNUAL COSTS");
it = col.iterator();
String totalAnnualCost = it.next().toString();
String extractCost = totalAnnualCost.substring(0,
totalAnnualCost.lastIndexOf("1000"));
double extractCostfromEnergyPLAN = Double.parseDouble(extractCost);
col = (Collection<String>) energyplanMap
.get("Total variable costs");
it = col.iterator();
String totalVariableCostStr = it.next().toString();
totalVariableCostStr = totalVariableCostStr.substring(0,
totalVariableCostStr.lastIndexOf("1000"));
double totalVariableCost = Double.parseDouble(totalVariableCostStr);
col = (Collection<String>) energyplanMap
.get("Fixed operation costs");
it = col.iterator();
String fixedOperationalCostStr = it.next().toString();
fixedOperationalCostStr = fixedOperationalCostStr.substring(0,
fixedOperationalCostStr.lastIndexOf("1000"));
double fixedOperationalCost = Double
.parseDouble(fixedOperationalCostStr);
// calculate additional cost
// extrect annual hydro production
col = (Collection<String>) energyplanMap.get("AnnualHydropower");
it = col.iterator();
double hydroPowerProduction = Double.parseDouble(it.next()
.toString());
// extract anual PV production
col = (Collection<String>) energyplanMap.get("AnnualPV");
it = col.iterator();
double PVproduction = Double.parseDouble(it.next().toString());
// extract annual import
col = (Collection<String>) energyplanMap.get("Annualimport");
it = col.iterator();
double Import = Double.parseDouble(it.next().toString());
// extract annual export
col = (Collection<String>) energyplanMap.get("Annualexport");
it = col.iterator();
double Export = Double.parseDouble(it.next().toString());
// calculate additional cost
// (hydroProduction+PVproduction+Import-Export)*average additional
// cost (85.74)
double additionalCost = Math.round((hydroPowerProduction
+ PVproduction + Import - Export) * 85.74);
/*
* now, calculte how many boiler need to diassamble
*/
StringTokenizer st = new StringTokenizer(individual);
st.nextToken();
double percents[] = new double[4];
// 0-> HP, 1->oil, 2->Ngas, 3->Boimass
for (int i = 0; i < 4; i++)
percents[i] = Double.parseDouble(st.nextToken().toString());
double total = 0;
for (int i = 0; i < 4; i++)
total = total + percents[i];
double boilerHeatDemands[] = new double[3];
double HPheatDemand = percents[0] / total * totalHeatdemand;
for (int i = 1; i < 4; i++)
boilerHeatDemands[i-1] = percents[i] / total * totalHeatdemand;
double numberOfBoilerforNewHeatDemand = Math
.round(maxHeatDemandInScaleOf1
* (boilerHeatDemands[0] + boilerHeatDemands[1] + boilerHeatDemands[2])
* Math.pow(10, 6) * 1.5);
double reductionInvestmentCost;
if (numberOfBoilerforNewHeatDemand <= currentNumberOfBoilers) {
// reduced investment cost = number of boiler to meet new heat
// demand after introducing HP* boiler cost + current PV
// capccity *
// pv cost + Hydro * hydro cost
// see anual investment cost formual in EnergyPLAN manual
reductionInvestmentCost = (numberOfBoilerforNewHeatDemand * 0.625 * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime))
+ (currentPVCapacity * 3.978 * interest)
/ (1 - Math.pow((1 + interest), -PVLifeTime))
+ (currentHydroCapacity * 3.51 * interest)
/ (1 - Math.pow((1 + interest), -HydroLifeTime));
} else {
reductionInvestmentCost = (currentNumberOfBoilers * 0.625 * interest)
/ (1 - Math.pow((1 + interest), -boilerLifeTime))
+ (currentPVCapacity * 3.978 * interest)
/ (1 - Math.pow((1 + interest), -PVLifeTime))
+ (currentHydroCapacity * 3.51 * interest)
/ (1 - Math.pow((1 + interest), -HydroLifeTime));
}
double numberOfHeatPump = Math.round(maxHeatDemandInScaleOf1 * HPheatDemand
* Math.pow(10, 6) / COP);
double geoBoreHoleInvestmentCost = (numberOfHeatPump * 3.2 * interest)
/ (1 - Math.pow((1 + interest), -geoBoreHoleLifeTime));
// extract
col = (Collection<String>) energyplanMap
.get("Annual Investment costs");
it = col.iterator();
String invest = it.next().toString();
String investmentCostStr = invest.substring(0,
invest.lastIndexOf("1000"));
double investmentCost = Double.parseDouble(investmentCostStr);
double realInvestmentCost = investmentCost
- reductionInvestmentCost + geoBoreHoleInvestmentCost;
double actualAnnualCost = totalVariableCost + fixedOperationalCost
+ realInvestmentCost + additionalCost;
col = (Collection<String>) energyplanMap
.get("Annualelec.demand");
it = col.iterator();
double annualElecDemand = Double.parseDouble(it.next().toString());
energyplanMap.put("AdditionalCost", additionalCost);
energyplanMap.put("InvestmentCost", realInvestmentCost);
energyplanMap.put("AnnualCost", actualAnnualCost);
energyplanMap.put("LoadFollowingCapacity", (Import+Export)/annualElecDemand);
} catch (IOException e) {
System.out.println("Energyplan.exe has some problem");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Energyplan interrupted");
}
return energyplanMap;
}
public MultiMap writeModificationFile(String individual) {
MultiMap modifyMap = new MultiValueMap();
StringTokenizer st = new StringTokenizer(individual);
// PV
double pv = Double.parseDouble(st.nextToken().toString());
double percents[] = new double[4];
// 0-> HP, 1->oil, 2->Ngas, 3->Boimass
for (int i = 0; i < 4; i++)
percents[i] = Double.parseDouble(st.nextToken().toString());
double total = 0;
for (int i = 0; i < 4; i++)
total = total + percents[i];
double heatDemands[] = new double[4];
for (int i = 0; i < 4; i++)
heatDemands[i] = percents[i] / total * totalHeatdemand;
double HP = heatDemands[0];
double oilBoilerHeatDemand = heatDemands[1];
double nGasBoilerHeatDemand = heatDemands[2];
double biomassBoilerHeatDemand=heatDemands[3];
modifyMap.put(inputs[0], (int) Math.round(pv));
modifyMap.put(inputs[1], HP);
modifyMap.put(inputs[2], oilBoilerHeatDemand);
modifyMap.put(inputs[3], nGasBoilerHeatDemand);
modifyMap.put(inputs[4],biomassBoilerHeatDemand );
try {
File file = new File("modification.txt");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String str = "EnergyPLAN version";
bw.write(str);
bw.newLine();
str = "698";
bw.write(str);
bw.newLine();
str = "input_RES1_capacity=";
bw.write(str);
bw.newLine();
str = "" + (int) Math.round(pv);
bw.write(str);
bw.newLine();
str = "input_HH_HP_heat=";
bw.write(str);
bw.newLine();
str = "" + heatDemands[0];
bw.write(str);
bw.newLine();
double oilBoilerFuelConsumption = heatDemands[1] / 0.8; // 0.8 is
// the
// efficiency
str = "input_fuel_Households[2]=";
bw.write(str);
bw.newLine();
str = "" + oilBoilerFuelConsumption;
bw.write(str);
bw.newLine();
modifyMap.put("OilBoilerFuel", oilBoilerFuelConsumption);
double nGasBoilerFuelConsumption = heatDemands[2] / 0.9; // 0.9 is
// the
// efficiency
str = "input_fuel_Households[3]=";
bw.write(str);
bw.newLine();
str = "" + nGasBoilerFuelConsumption;
bw.write(str);
bw.newLine();
modifyMap.put("NgasBoilerFuel", nGasBoilerFuelConsumption);
double biomassBoilerFuelConsumption = heatDemands[3] / 0.7; // 0.7
// is
// the
// efficiency
str = "input_fuel_Households[4]=";
bw.write(str);
bw.newLine();
str = "" + biomassBoilerFuelConsumption;
bw.write(str);
bw.newLine();
modifyMap.put("BiomassBoilerFuel",biomassBoilerFuelConsumption);
bw.close();
// file.delete();
} catch (IOException e) {
e.printStackTrace();
}
return modifyMap;
}
}
|
09486238326c1adcb80b29bdb0023ca65155ccb7
|
[
"Java",
"Text",
"R",
"INI"
] | 89
|
Java
|
shaikatcse/EnergyPLANDomainKnowledgeEAStep1
|
649cd38e0ca5e53105f9f6a051831da9cf401646
|
127b58e0727d19a2ed999f7f24a8921b79d5a6d9
|
refs/heads/master
|
<repo_name>zeljko94/text-detection-scene-image<file_sep>/opencv_text_detection/main.py
import argparse
import os
import time
import cv2
from nms import nms
import numpy as np
import utils
from decode import decode
from draw import drawPolygons, drawBoxes
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def text_detection(image, east, min_confidence, width, height):
image = cv2.imread(image)
orig = image.copy()
(origHeight, origWidth) = image.shape[:2]
(newW, newH) = (width, height)
ratioWidth = origWidth / float(newW)
ratioHeight = origHeight / float(newH)
image = cv2.resize(image, (newW, newH))
(imageHeight, imageWidth) = image.shape[:2]
layerNames = [ "feature_fusion/Conv_7/Sigmoid", "feature_fusion/concat_3" ]
# original slika
cv2.imshow("Original", orig)
print("[INFO] Učitavanje EAST text detektora...")
net = cv2.dnn.readNet(east)
blob = cv2.dnn.blobFromImage(image, 1.0, (imageWidth, imageHeight), (123.68, 116.78, 103.94), swapRB=True, crop=False)
start = time.time()
net.setInput(blob)
(scores, geometry) = net.forward(layerNames)
end = time.time()
print("[INFO] Trajanje detekcije: {:.6f} sekundi".format(end - start))
confidenceThreshold = min_confidence
nmsThreshold = 0.4
(rects, confidences, baggage) = decode(scores, geometry, confidenceThreshold)
offsets = []
thetas = []
for b in baggage:
offsets.append(b['offset'])
thetas.append(b['angle'])
functions = [nms.felzenszwalb.nms, nms.fast.nms, nms.malisiewicz.nms]
#print("[INFO] Running nms.boxes . . .")
for i, function in enumerate(functions):
start = time.time()
indicies = nms.boxes(rects, confidences, nms_function=function, confidence_threshold=confidenceThreshold,
nsm_threshold=nmsThreshold)
end = time.time()
indicies = np.array(indicies).reshape(-1)
drawrects = np.array(rects)[indicies]
name = function.__module__.split('.')[-1].title()
print("[INFO] Trajanje izvođenja {} metode: {:.6f} seconds i prondađeno je {} okvira".format(name, end - start, len(drawrects)))
drawOn = orig.copy()
drawBoxes(drawOn, drawrects, ratioWidth, ratioHeight, (0, 255, 0), 2)
title = "nms.boxes {}".format(name)
cv2.imshow(title,drawOn)
cv2.moveWindow(title, 150+i*300, 350)
cv2.waitKey(0)
"""
polygons = utils.rects2polys(rects, thetas, offsets, ratioWidth, ratioHeight)
print("[INFO] Running nms.polygons . . .")
for i, function in enumerate(functions):
start = time.time()
indicies = nms.polygons(polygons, confidences, nms_function=function, confidence_threshold=confidenceThreshold,
nsm_threshold=nmsThreshold)
end = time.time()
indicies = np.array(indicies).reshape(-1)
drawpolys = np.array(polygons)[indicies]
name = function.__module__.split('.')[-1].title()
print("[INFO] {} NMS took {:.6f} seconds and found {} boxes".format(name, end - start, len(drawpolys)))
drawOn = orig.copy()
drawPolygons(drawOn, drawpolys, ratioWidth, ratioHeight, (0, 255, 0), 2)
title = "nms.polygons {}".format(name)
cv2.imshow(title,drawOn)
cv2.moveWindow(title, 150+i*300, 150)
cv2.waitKey(0)
"""
def text_detection_command():
imgs_path = "imgs"
east = os.path.join(os.path.dirname(os.path.realpath("__file__")), 'frozen_east_text_detection.pb')
min_confidence = 0.5
width = 320
height = 320
for filename in os.listdir(imgs_path):
text_detection(imgs_path + "/" + filename, east, min_confidence, width, height)
break
if __name__ == '__main__':
text_detection_command()
|
4d587936391b3989566db39c4de7b2d82f0f74e5
|
[
"Python"
] | 1
|
Python
|
zeljko94/text-detection-scene-image
|
baf2aeab6557bafb17fe78e63fef98ba96c37489
|
3d96806a0109003503b89770ba5fda13c685803e
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
"""
BSD 3-Clause License
Copyright (c) 2020, <NAME> & <NAME>.
All rights reserved.
"""
import rospy
import random
from std_msgs.msg import Int32
from std_msgs.msg import String
n = 0
a = ['必う日は近い','他人に妨げられる事あり','願いを伝えよ','他人を助けよ、助けることで叶う','初めは思わしくないが後は必ず良し','2つの願いを一度に叶えんとすれば悪し','思いがけぬ人の助けありて叶うことあり','にわかに事をなさんとすれば災いあり','必ず叶う','早くすれば他人の助けありて調う','少し時がかかるが叶う','願い難し、努力せよ','叶い難く利なけれど後自然成就す','無理に事をなすは悪し、時を待て叶う','遅くとも必ず叶う','叶いにくい']
b = ['来ず、待たない方が良い','便りが有り来る','音信有り来る','来る','来る、連れあり','便り無し来ず','すぐあり','非を認めれば来る','遅いが来る','来ること難し','待つことで災いあり','来る喜びあり','さわりなく来る','速やかに来たる','かなり遅く来る']
c = ['上方にあり','下方にあり','低き所にて見つかる','高き所にあり','男子の知ることあり','女にとふべし','手近より出る','出ず','いつのまにかある','苦労して捜し出すことになる','家族にとふと良い','忘れたころに出る','必ず出る、早く捜せ','遠くにあり','出るとも遅し','戻らず','北を捜すべし','西を捜すべし','南を捜すべし','東を捜すべし','捜さずとも出る']
d = ['列車の旅が良い','早朝出立すべし','出発は吉日を選べ','ゆるゆる行くべし','つれあれば共に行け','近き所、特に良し','行く先利益あり','船旅良し','災いあり控えるべし','遠くに縁あり','何れに行くも損なし','水難に注意すべし','北は控えよ','特に南よし','夏に行くが良し','海に近いところ良し','海を越えると良い','山の近くが良い','秋に行くが良し','夜に出立すべし']
e = ['確かなる利益あり','利あり、売るに良し','物の値、大きく変動あり','乗り気にてやるべし','利益少なし','値段上下無し','苦労の甲斐あり','売り買い何れも吉','成せば成る','隆昌に向かうが慎重にせよ','投資せよ','買うに良し、利あり','利益少なし、時を待て','利益相当あり','己の思うままに成すべし','俄かに下ることあり','災い有り','利も損も無し','少し待て','他人の手を借りるべし','後に利益あり','利益有るが何れか失う','物の値下げるべし','物の値上げるべし']
f = ['初心に返ると良い','他人を当てにすること勿れ','安心して勉学せよ','幸運訪れ有','焦らず頑張','全力を尽くせば必ず叶う','順調に進む','挫けずに努力せよ','友達を選べ','実力以上を発揮','日々の積重現わる','感謝の心で一筋に努力せよ、叶う','自己への甘えを捨てよ','寝不足に注意','雑念多し、努力せよ','頑張れば幸運有り','辛ければ他人に相談せよ']
g = ['人生の伴走者に出会う','愛情を捧げよ','愛を捧げよ倖せあり','短気は敵','自身に問題あり','お互いを知れ','一途な想いが愛を深める、行動で示せ','楽しむことが吉','考え過ぎれば災いあり','多くを話合うこと','我を張らず愛情を捧げる事','思わぬ出会い有り、逃すな','相手に誠意無し','深入りするな','周りに気を付ける事','他人の話を聞くこと','贈り物に注意','焦らず考えよ','器大きくあるべし','自己に甘えることなく勇気を出すこと吉']
h = ['日頃を気をつけよ','治る気第一','信心によりてなおる','軽し治る','治る','重し、気をつけよ','休むが一番の治療','重いが全快す','全快早し','重くない治る','睡眠第一','食生活に気をつけよ','医者の話を聞くべし','細心の注意を払え','周りの話を聞くべし','再発に気をつけよ','気持ち次第で必ず治る','落ち着いて待つべし']
i = ['人の世話あれば良し','勝つ、気長く思え','自己を戒めよ、勝つ','慎重になせ','短期は早計','勝進むは良し','女相手なら負け','短期は戒めよ、勝つ','容易く勝つ','辛いが今だけ','万事解決','勝ども後に恨みあり','恐れず挑め','負けが続くが最後は勝つ','負け知らず','欲をかけば災いあり','勝機は必ずあり','助け有りて勝つ','勝てども失うもの多く','油断大敵','必勝','初めは勝つが後に大敗']
def cb(message):
global n
n = message.data
rospy.init_node('henkan')
sub = rospy.Subscriber('kai',Int32,cb)
rate =rospy.Rate(15)
while not rospy.is_shutdown():
if n==1:
n = random.choice(a)
print (f"願事:{n}")
elif n==2:
n = random.choice(b)
print (f"待人:{n}")
elif n==3:
n = random.choice(c)
print (f"失物:{n}")
elif n==4:
n = random.choice(d)
print (f"旅行:{n}")
elif n==5:
n = random.choice(e)
print (f"商売:{n}")
elif n==6:
n = random.choice(f)
print (f"学問:{n}")
elif n==7:
n = random.choice(g)
print (f"恋愛:{n}")
elif n==8:
n = random.choice(h)
print (f"健康:{n}")
elif n==9:
n = random.choice(i)
print (f"争事:{n}")
rate.sleep()
<file_sep># mypkg
# リポジトリの概要
2021年度ロボットシステム学の課題2の提出用リポジトリです。
今年の運勢を占えます。ぜひお試しを
# 動作環境
- ubuntu 20.04.1 LTS
# 使用したもの
- Raspberry pi 4
- Micro SD Card
# デモ動画
- https://www.youtube.com/watch?v=qE2sXgm62OQ&feature=youtu.be
# インストール方法
ROSを予めインストールしておいてください。
```
cd ~/catkin_ws/src
git clone https://github.com/sakurai-ruka/mypkg.git
cd ..
catkin_make
```
# 実行方法
以下のコマンドで実行できます
- ターミナル1
```
roscore
```
- ターミナル2
```
cd ~/catkin_ws/src/mypkg/scripts
rosrun mypkg omi.py
```
- ターミナル3
```
cd ~/catkin_ws/src/mypkg/scripts
rosrun mypkg henkan.py
```
# ライセンス
BCD 3-Clause License
<file_sep>#!/usr/bin/env python3
"""
BSD 3-Clause License
Copyright (c) 2020, <NAME> & <NAME>.
All rights reserved.
"""
import rospy
import random
from std_msgs.msg import Int32
from std_msgs.msg import String
rospy.init_node("omi")
pub = rospy.Publisher("kai",Int32,queue_size=1)
pub2 = rospy.Publisher("kai",Int32,queue_size=1)
pub3 = rospy.Publisher("kai",Int32,queue_size=1)
pub4 = rospy.Publisher("kai",Int32,queue_size=1)
pub5 = rospy.Publisher("kai",Int32,queue_size=1)
pub6 = rospy.Publisher("kai",Int32,queue_size=1)
pub7 = rospy.Publisher("kai",Int32,queue_size=1)
pub8 = rospy.Publisher("kai",Int32,queue_size=1)
pub9 = rospy.Publisher("kai",Int32,queue_size=1)
rate =rospy.Rate(10)
a = 0
b = 1
c = 2
d = 3
e = 4
f = 5
g = 6
h = 7
i = 8
j = 9
unsei = ['大大吉','大吉','向大吉','末大吉','吉凶未分末大吉','吉','中吉','小吉','後吉','末吉','吉凶不分末吉','吉凶相交末吉','吉凶相半','吉凶相央','小吉後吉','凶後吉','凶後大吉']
print('今年の運勢を占います')
rospy.sleep(2)
print('今年の運勢は........')
rospy.sleep(2)
u = random.choice(unsei)
print (u)
rospy.sleep(2)
while True:
print('今年の運勢の内容を占えます')
a = input('占う場合は1を、終了する場合は2を押してください:')
try:
a = int(a)
except ValueError:
a = 0
if int(a)==1:
print('以下の内容を占えます')
print('1:願事(ねがいごと)')
print('2:待人(まちびと)')
print('3:失物(うせもの)')
print('4:旅行(りょこう)')
print('5:商売(しょうばい)')
print('6:学問(がくもん)')
print('7:恋愛(れんあい)')
print('8:健康(けんこう)')
print('9:争事(あらそいごと)')
while not rospy.is_shutdown():
x = input('占いたい番号を押してください,終了する場合は0を押してください:')
try:
x = int(x)
except ValueError:
x = 0
if int (x)==1:
pub.publish(b)
rate.sleep()
elif int (x)==2:
pub2.publish(c)
rate.sleep()
elif int (x)==3:
pub3.publish(d)
rate.sleep()
elif int (x)==4:
pub4.publish(e)
rate.sleep()
elif int (x)==5:
pub5.publish(f)
rate.sleep()
elif int (x)==6:
pub6.publish(g)
rate.sleep()
elif int (x)==7:
pub7.publish(h)
rate.sleep()
elif int (x)==8:
pub8.publish(i)
rate.sleep()
elif int (x)==9:
pub9.publish(j)
rate.sleep()
elif int(x)==0:
break
elif int(a)==2:
print('今年一年が良き一年となりますように')
break
|
4eeeb2f98d44dec7b15df4b6185557692c287a36
|
[
"Markdown",
"Python"
] | 3
|
Python
|
sakurai-ruka/mypkg
|
0c3aca6527b46c78341d1b790bff74d01d2002e5
|
aeb10214254e15f7e30b7e8eefef707349fd377f
|
refs/heads/master
|
<file_sep>version: '2'
services:
jdk7:
build: java-7
jetty:
depends_on:
- jdk7
build: core/environment/src/main/resources
ufos-core-jetty:
build: core/sufd-server/target
dockerfile: core/sufd-server/src/assembly/Dockerfile
ports:
- "18080"
- "5005"
<file_sep>#!/bin/bash
echo "#1 building java7"
pushd .
jdk=`docker images otr/oracle-jdk7 | wc -l`
[ $jdk -eq 1 ] && cd java-7 && docker build -t otr/oracle-jdk7:latest .
popd
echo "#2 building jetty"
pushd .
cd ./core/environment/src/main/resources/ && docker build -t otr/jetty:latest .
popd
echo "#3 building sufd-server"
pushd .
cd ./core/sufd-server && mvn docker:build -Pdocker
popd
echo "#4 building func"
pushd .
cd rshn-func && docker build -t otr/rshn-func:latest .
popd
ehco "5 building db"
pushd .
cd create-db && docker build -t otr/ufos-db .
popd
<file_sep>FROM otr/ufos-core-jetty:latest
COPY sufd.config /usr/share/jetty/sufd.config
<file_sep>from postgres:9
COPY create.sql /tmp/create.sql
COPY init_db.sh /docker-entrypoint-initdb.d/
ENV POSTGRES_PASSWORD Oracle33
ENV POSTGRES_USER ufos
ENV POSTGRES_DB ufos
#RUN gosu postgres postgres && pg_restore /tmp/db_dump
#RUN /docker-entrypoint.sh postgres && pg_restore --verbose /tmp/db_dump
CMD ["postgres"]
<file_sep>echo "#cheking data-cotainer"
dbcont=`docker ps -a -f name=dbstore | wc -l`
[ $dbcont -eq 1 ] && docker create -v /var/lib/postgresql/data --name dbstore postgres /bin/true
echo "#checking postgre"
db=`docker ps -a -f name=db | wc -l`
[ $db -eq 1 ] && docker run -d --volumes-from dbstore -p 4321:4321 --name db otr/ufos-db
echo "#running ufos"
docker run --rm --name ufos --link db:db -p 18080:18080 otr/rshn-func
<file_sep>#!/bin/bash
#psql --username postgres "CREATE DATABASE ufos ; create user ufos with password '<PASSWORD>'; grant all privileges on database ufos to ufos;"
if [ -f /tmp/create.sql ];
then
echo "initing empty schema"
psql --username ufos -d ufos -f /tmp/create.sql
rm /tmp/create.sql
fi<file_sep>from postgres:9
COPY db_dump /tmp/db_dump
COPY pgup.sh /tmp/
ENV POSTGRES_PASSWORD <PASSWORD>
ENV POSTGRES_USER ufos
ENV POSTGRES_DB ufos
#RUN chmod 0777 /tmp/pgup.sh
#RUN /tmp/pgup.sh
#RUN gosu postgres postgres && pg_restore /tmp/db_dump
#RUN /docker-entrypoint.sh postgres && pg_restore --verbose /tmp/db_dump
CMD ["postgres"]
<file_sep>FROM ubuntu:14.04
RUN echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" >> /etc/apt/sources.list
# INSTALL JAVA 7
RUN echo debconf shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \
echo debconf shared/accepted-oracle-license-v1-1 seen true | debconf-set-selections && \
apt-get install -y software-properties-common && \
add-apt-repository -y ppa:webupd8team/java && \
apt-get update && \
apt-get install -y oracle-java7-installer unzip vim mc && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /var/cache/oracle-jdk7-installer
ENV JAVA_HOME /usr/lib/jvm/java-7-oracle
|
1e061ee23981e5180896a3c9df8cdffbfdf2e994
|
[
"YAML",
"Dockerfile",
"Shell"
] | 8
|
YAML
|
sirvaulterscoff/ufos-dockerscripts
|
3a1e904975dac662f6eef5ff38c059eebfe6e4b5
|
22172bc16711edc52100aaabd88112bf944f6fcb
|
refs/heads/master
|
<file_sep>var pythonver = require("fs").readFileSync("pythonver.txt")
function getSTInfo(id, password, url) {
var spawn = require("child_process").spawn;
var process = spawn(pythonver,["./getStudentInfo.py", id, password, url] );
return new Promise(resolve => {
process.stdout.on('data', function(data) {
resolve(data.toString());
})
});
}
async function getSInfo(id, password, url) {
var result = await getSTInfo(id, password, url)
return JSON.parse(result)
}
function getSCInfo(id, password, url) {
var spawn = require("child_process").spawn;
var process = spawn(pythonver,["./getSchoolInfo.py", id, password, url] );
return new Promise(resolve => {
process.stdout.on('data', function(data) {
resolve(data.toString());
})
});
}
async function getSCHInfo(id, password, url) {
var result = await getSCInfo(id, password, url)
return JSON.parse(result)
}
function getC(id, password, url) {
var spawn = require("child_process").spawn;
var process = spawn(pythonver,["./getClasses.py", id, password, url] );
return new Promise(resolve => {
process.stdout.on('data', function(data) {
resolve(data.toString());
})
});
}
async function getCL(id, password, url) {
var result = await getC(id, password, url)
return JSON.parse(result)
}
module.exports.getSchoolInfo = getSCHInfo
module.exports.getStudentInfo = getSInfo
module.exports.getClasses = getCL
<file_sep># StudentVUEApi
Powered by kachang's StudenetVue python script.
# Usage
Change the text inside pythonver.txt to the name of your python.
You need jsonpickle and StudentVue installed via pip.<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const StudentVue = require('./vue.js');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.json({"message": "StudentVUE API by Logandev_ and kachang"});
});
app.post('/getStudentInfo', (req, res) => {
console.log("index.js: getStudentInfo requested, summoning vue.js")
if(!req.body.id) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.password) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.url) {
return res.status(400).send({
message: "id content can not be empty"
});
}
StudentVue.getStudentInfo(req.body.id, req.body.password, req.body.url).then(resp => res.send(resp))
})
app.post('/getSchoolInfo', (req, res) => {
if(!req.body.id) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.password) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.url) {
return res.status(400).send({
message: "id content can not be empty"
});
}
StudentVue.getSchoolInfo(req.body.id, req.body.password, req.body.url).then(resp => res.send(resp))
})
app.post('/getClasses', (req, res) => {
if(!req.body.id) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.password) {
return res.status(400).send({
message: "id content can not be empty"
});
}
if(!req.body.url) {
return res.status(400).send({
message: "id content can not be empty"
});
}
StudentVue.getClasses(req.body.id, req.body.password, req.body.url).then(resp => res.send(resp))
})
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
<file_sep>import sys
import studentvue
import jsonpickle
id = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
sv = studentvue.StudentVue(id, password, url) # e.g. portal.sfusd.edu
print(jsonpickle.encode(sv.get_classes(), unpicklable=False))
#print(id)
|
198a6f53fc254c9f83471fc7942e28a2da85c475
|
[
"JavaScript",
"Python",
"Markdown"
] | 4
|
JavaScript
|
LoganMD/StudentVueAPI
|
6a0b7c1279379102a5755c524e27e5ba910d97c7
|
426b4129e49bc3c68286b713ab26dc15b2e40aeb
|
refs/heads/master
|
<repo_name>gsc229/node-db-challenge<file_sep>/data/seeds/003-resources.js
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('resources').insert([
{ proj_id: 1, resource_name: 'hammer', res_desc: 'used to hammer nails', res_notes: '' }, // res_id 1
{ proj_id: 1, resource_name: 'saw', res_desc: 'for cutting wood', res_notes: '' }, // res_id 2
{ proj_id: 1, resource_name: 'drill', res_desc: 'for drilling holes', res_notes: '' } // res_id 3
]);
};
<file_sep>/data/seeds/004-project-resources.js
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('project_resources').insert([
{ proj_id: 1, res_id: 1 },
{ proj_id: 1, res_id: 2 },
{ proj_id: 1, res_id: 3 },
{ proj_id: 2, res_id: 1 },
{ proj_id: 2, res_id: 2 },
{ proj_id: 2, res_id: 3 },
{ proj_id: 3, res_id: 1 },
{ proj_id: 3, res_id: 2 },
{ proj_id: 3, res_id: 3 }
]);
};
<file_sep>/projects/projectsRouter.js
const express = require('express');
const Projects = require('./projectsModel');
const router = express.Router();
router.get('/', (req, res) => {
Projects.findProjects()
.then(projs => {
projs.forEach(proj => {
proj.completed = proj.completed ? true : false
})
res.status(200).json(projs);
})
.catch(err => {
res.status(500).json({ message: 'Failed to get projects' });
});
})
router.post('/', (req, res) => {
const newProject = req.body;
Projects.addProject(newProject)
.then(info => {
res.status(201).json(info);
})
.catch(err => {
res.status(500).json({ message: 'Failed to create projects' });
});
})
router.post('/task', (req, res) => {
const newTask = req.body;
Projects.addTask(newTask)
.then(info => {
res.status(201).json(info);
})
.catch(err => {
res.status(500).json({ message: 'Failed to create task' });
});
})
router.get('/resources', (req, res) => {
Projects.getAllResources()
.then(resources => {
res.status(200).json(resources)
})
.catch(err => {
res.status(500).json({ message: 'Failed to get resources' });
});
})
router.post('/resources', (req, res) => {
const newResource = req.body;
Projects.addResource(newResource)
.then(info => {
res.status(201).json(info)
})
.catch(err => {
res.status(500).json({ message: 'Failed to get resources' });
});
})
router.get('/:id', (req, res) => {
const proj_id = req.params.id;
Projects.findProject(proj_id)
.then(proj => {
proj.completed = proj.completed ? true : false;
res.status(200).json(proj)
})
.catch(err => {
res.status(500).json({ message: 'Failed to get project by that id' });
});
})
router.get('/:id/with-tasks', (req, res) => {
const proj_id = req.params.id;
let projTasks;
Projects.getProjectTasks(proj_id)
.then(tasks => {
tasks.forEach(task => {
task.completed = task.completed ? true : false
})
projTasks = tasks
Projects.findProject(proj_id)
.then(proj => {
console.log(projTasks);
proj.tasks = projTasks;
res.status(200).json(proj);
})
})
})
router.get('/:id/tasks', (req, res) => {
Projects.getProjectTasks(proj_id)
.then(tasks => {
tasks.forEach(task => {
task.completed = task.completed ? true : false
})
console.log(tasks);
res.status(200).json(tasks);
})
.catch(err => {
res.status(500).json({ message: 'Failed to get tasks by that project id' });
});
})
module.exports = router;
/*
ENDPOINTS:
Design the data model and use knex migrations to create the database and tables.
Build an API with endpoints for:
1. adding resources. --
2. retrieving a list of resources. --
3. adding projects. --
4. retrieving a list of projects. --
5. adding tasks. --
6. retrieving a list of tasks. The list of tasks should include the project name and project description.
When returning project or task information, the completed property should be true or false. -- ~
*/<file_sep>/projects/projectsModel.js
const db = require('../db-config');
module.exports = {
findProjects,
findProject,
getProjectTasks,
getAllResources,
addResource,
addTask,
addProject
}
function findProjects() {
return db('projects')
}
function findProject(proj_id) {
return db('projects')
.where({ id: proj_id })
.first()
}
function getProjectTasks(proj_id) {
return db('projects')
.join('tasks', 'tasks.proj_id', 'projects.id')
.select('projects.project_name', 'projects.description', 'tasks.task_description', 'tasks.completed', 'tasks.id')
.where({ 'proj_id': proj_id })
}
function getAllResources() {
return db('resources')
}
function addResource(newResource) {
return db('resources')
.insert(newResource);
}
function addTask(newTask) {
return db('tasks')
.insert(newTask)
}
function addProject(newPrject) {
return db('projects')
.insert(newPrject);
}
/*
ENDPOINTS:
Design the data model and use knex migrations to create the database and tables.
Build an API with endpoints for:
1. adding resources.
2. retrieving a list of resources.
3. adding projects.
4. retrieving a list of projects.
5. adding tasks.
6. retrieving a list of tasks. The list of tasks should include the project name and project description.
When returning project or task information, the completed property should be true or false.
*/<file_sep>/essayQuestions.md
• Explain the difference between Relational Databases and SQL.
o RDMS and use structured query language as the main interface for manipulation of data.
• Why do tables need a primary key?
o To distinguish them from other tables and to uniquely identify all the records in a table.
• What is the name given to a table column that references the primary key on another table.
o Foreign key
• What do we need in order to have a many to many relationship between two tables.
o Foreign keys.
<file_sep>/data/seeds/001-projects.js
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('projects').insert([
{ project_name: "Build House", description: 'A biggo house', completed: false },
{ project_name: "Build Boat", description: 'A huge boat', completed: false },
{ project_name: "Build Airplane", description: 'A fast airplane', completed: false }
]);
};
<file_sep>/data/seeds/002-tasks.js
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('tasks').insert([
{ step_num: 1, proj_id: 1, task_description: "build foundation", notes: "", completed: false },
{ step_num: 2, proj_id: 1, task_description: "build walls", notes: "", completed: false },
{ step_num: 3, proj_id: 1, task_description: "build roof", notes: "", completed: false }
]);
};
|
75a5ba232e1a02c51a06a6c5b608083c28528337
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
gsc229/node-db-challenge
|
5070f4b5513e4ff3ef4a0507cc351aa23d25856b
|
7017f7d3635f60da98a2e0e90ed89bb2073f5013
|
refs/heads/master
|
<repo_name>Gleb3214/Diplom_js<file_sep>/script.js
const catalogProduct = [
{
id: 'product1',
name: '<NAME>',
price: 199999,
img: './images/grid_1.png',
},
{
id: 'product2',
name: 'BMW',
price: 1348909,
img: './images/grid_2.png',
},
{
id: 'product3',
name: 'Mercedes',
price: 209780,
img: './images/grid_3.png',
},
{
id: 'product4',
name: 'Volkswagen',
price: 789046,
img: './images/grid_4.png',
},
{
id: 'product5',
name: '<NAME>',
price: 304950934199999,
img: './images/grid_5.png',
}
]
|
d6d12e4d7dc626a0b609ac1aeec8869c32e9704c
|
[
"JavaScript"
] | 1
|
JavaScript
|
Gleb3214/Diplom_js
|
73f4388310650b2c998cbe13359c5616ce7920af
|
8f9f8ba1967ad627ae6f2559f591d02e38651e0d
|
refs/heads/main
|
<repo_name>anibale11/myDotfiles<file_sep>/background
#!/bin/bash
feh --randomize --bg-fill /home/anibale/Imágenes/background/*
compton -b
udisksctl mount -b /dev/sda1
<file_sep>/links-directorys.sh
#!/bin/bash
rm -r ~/{Documentos,Descargas,Música,Vídeos,Imágenes}
ln -s /media/anibale/DATA/Documentos ~/Documentos
ln -s /media/anibale/DATA/Descargas ~/Descargas
ln -s /media/anibale/DATA/Música ~/Música
ln -s /media/anibale/DATA/Vídeos ~/Vídeos
ln -s /media/anibale/DATA/Imágenes ~/Imágenes
ln -s /media/anibale/DATA/GitFiles ~/GitProject
ls ~
echo "link symbolik created"
<file_sep>/bspwmrc
#! /bin/bash
# ] ---- AUTOSTART ---- [
sxhkd &
~/.fehbg
setxkbmap latam &
flameshot &
picom -b &
nm-applet &
udisksctl mount --block-device /dev/sda1
feh --bg-scale /media/anibale/DATA/Imágenes/background/pinguinitos.jpg
#select random theme
themes=('blocks' 'colorblocks' 'cuts' 'docky' 'forest' 'grayblocks' 'hack' 'material' 'panels' 'pwidgets' 'shades' 'shapes')
rndm=$((0 + $RANDOM % 11))
bash ~/.config/polybar/launch.sh --${themes[$rndm]}
# ] ---- WORKSPACES ---- [
notify-send --urgency=low --app-name=Polybar "Polybar" "Polybar ${themes[$rndm]} launched..."
#bspc monitor -d
#bspc monitor -d CONSOLE CODE WEB FILES MUSIC CHAT OTHERS
# ] ---- WINDOW CONFIG ---- [
bspc config border_width 0
bspc config window_gap 15
bspc config normal_border_color "#2A2426"
bspc config focused_border_color "#87AF87"
bspc config split_ratio 0.70
bspc config borderless_monocle true
bspc config gapless_monocle true
bspc config focus_follows_pointer true
bspc rule -a brave-browser desktop=^6 follow=on
bspc rule -a emacs desktop=^3 follow=on
bspc rule -a spotify desktop=^2 follow=on
<file_sep>/readme.md
### This is My Linux Configurations Files ####
- Instalar i3 y cp archivo de configuracion en .config/i3/config
- instalar compton para transparencia y cp archivo de configuracion en .config/compton.conf
- Terminator config
- nm-applet for conect wifi
- (fedora) sudo dnf install https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm --> install graph drivers intel
### Display config for bspwm
- xrandr --output HDMI-1-1 --rotate normal --right-of eDP-1-1
paypal.me/anibale11
|
f5df28b8cba570a954c6249f9acf19d27fdad7bf
|
[
"Markdown",
"Shell"
] | 4
|
Shell
|
anibale11/myDotfiles
|
b8c9c9c3ecee75417e4603ba0629d2cd004e580e
|
9d136afade29ccb8b0b07d40dff818aa8404d632
|
refs/heads/master
|
<file_sep>'''
Created on Dec 21, 2013
@author: <NAME>
'''
from mrjob.job import MRJob
from common_functions import CoordinatesSharing, Utils
from settings import jobsettings
from cjson import decode
class MRUserCoordinatesSharingDistribution(MRJob):
'''
Generates a distribution of users based and
coordinates sharing behavior in a given dataset
generated by dataextractor.TweetParser .
'''
def __init__(self, args):
super(MRUserCoordinatesSharingDistribution, self).__init__(args)
def configure_options(self):
super(MRUserCoordinatesSharingDistribution, self).configure_options()
self.add_file_option('--filter_file', help = 'The file containing'
' the uids, to be applied as filter on the data.')
self.add_passthrough_option('--apply_filter', action = 'store_true',
default = False, dest = 'apply_filter')
def load_options(self, args):
super(MRUserCoordinatesSharingDistribution, self).load_options(args)
filter_filename = self.options.filter_file
if self.options.apply_filter:
self._uids = Utils.get_filter_uids(filter_filename)
def read_data(self, _, line):
data = decode(line)
if self.options.apply_filter:
if data['u'] in self._uids:
return CoordinatesSharing.read_data(data)
else:
return CoordinatesSharing.read_data(data)
def aggregate_data(self, uid, data):
return CoordinatesSharing.aggregate_data(uid, data)
def calculate_user_distribution(self, uid, checkins):
index = self.get_index(checkins)
yield index, 1
def emit_distribution(self, index, count):
yield index, sum(count)
def get_index(self, checkins):
return CoordinatesSharing.get_index(checkins)
def steps(self):
return [self.mr(mapper = self.read_data,
reducer = self.aggregate_data),
self.mr(mapper = self.calculate_user_distribution,
reducer = self.emit_distribution),
]
def main():
MRUserCoordinatesSharingDistribution.run()
if __name__ == '__main__':
main()
<file_sep>function createTableFromJson(parsedJson,id){
console.log("json objects number - "+ parsedJson.length);
var div = document.getElementById(id);
div.setAttribute("class","res");
for (i = 0; i < parsedJson.length; i++)
{
divCntr = document.createElement("div");
divCntr.setAttribute('class','mrg');
divImg = document.createElement("div");
divImg.setAttribute('class','flt'); // applying css for float left
pp = document.createElement("img"); //parsedJson[i].profile_image_url - <img src="img url" width="80px" height="80px"></img>
pp.setAttribute('src',parsedJson[i].profile_image_url);
pp.setAttribute('width',"100px");
pp.setAttribute('height',"100px");
divImg.appendChild(pp);
divDescCntr = document.createElement("div");
divDescCntr.setAttribute('class','flt descntr');
divUserName = document.createElement("div");
anchorUserName = document.createElement("a");
anchorUserName.setAttribute("href","http://www.twitter.com/@"+parsedJson[i].user_name);
anchorUserName.setAttribute("target","_blank");
anchorUserName.appendChild(document.createTextNode(parsedJson[i].user_name));
divUserName.appendChild(anchorUserName);
divDesc = document.createElement("div");
divDesc.setAttribute('class','desc');
txtDesc = document.createTextNode(parsedJson[i].user_description)
divDesc.appendChild(txtDesc);
divLoc = document.createElement("div");
divLoc.appendChild(document.createTextNode("Location: "+ parsedJson[i].user_location));
divDescCntr.appendChild(divUserName);
divDescCntr.appendChild(divLoc);
divDescCntr.appendChild(divDesc);
divCntr.appendChild(divImg);
divCntr.appendChild(divDescCntr);
div.appendChild(divCntr);
}
}
function sub(id, query, location){
var requestString = "getExpertSearchResults?query=" + query + "&userlocation=" + location;
$.get(requestString ,function(jsonData,status) {
parsedJson = JSON.parse(jsonData);
var div = document.getElementById(id);
while(div.firstChild){
div.removeChild(div.firstChild); // to make sure only one table exists if clicked on search multiple times.
}
createTableFromJson(parsedJson,id);
});
}<file_sep>'''
Created on Mar 24, 2013
@author: <NAME>
'''
from math import log, pow
from multiprocessing import Process, Queue
from random import randint
from pprint import pprint
from operator import itemgetter
import time
from bucket_users import BucketUsers
from extractdata import DataExtractorFactory
from region import Region
from userdata import UsersData
#import map_plots
from settings import Settings
class BackStromExpertiseModelGenerator:
_dictExpertUsersData = {}
_dictExpertiseRegions = {'tech': [Region((0, 0), (0, 0))]}
_dictExpertModels = {'tech': [{'C':.8, 'alpha' : 2.9, 'center': (23, -67.9)}]}
_dataDirectory = ''
_expertDataExtractor = None
_usersClusterer = None
_usersBucket = None
def __init__(self, dataDirectory, dataExtractor = None):
self._dictExpertiseRegions.clear()
self._dictExpertModels.clear()
self._dataDirectory = dataDirectory
if dataExtractor == None:
self._expertDataExtractor = DataExtractorFactory.getDataExtractor('expertisemodel', self._dataDirectory)
self._expertDataExtractor.populateData(self._dataDirectory)
else:
self._expertDataExtractor = dataExtractor
self._dictExpertUsersData = self._expertDataExtractor.getAllExpertsData()
self._createParentRegions()
UsersData.addUserDataToRegions(self._dictExpertUsersData)
'''
Calculates the likelihood value for Backstorm model p = C*d^-alpha
@param C: The value of parameter C
@param alpha: The value of parameter C
@param childRegion: The childRegion for which we want to calculate the model
'''
def _likelihoodFunction(self, C, alpha, childRegion):
expertValueSum = 0
nonExpertValueSum = 0
# We will use all the users data for a given expertise's parent childRegion
# to calculate the log likelihood about the center of a
# given child childRegion.
usersDataBuckets = self._usersBucket.getUsersBucket()
if childRegion.getName() != self._usersBucket._region.getName():
print childRegion.getName(), ' is using the bucket for ', self._usersBucket._region.getName()
for bucketKey in usersDataBuckets:
usersBucket = usersDataBuckets[bucketKey]
# We calculate the maximum likelihood for the Backstorm model
# using the center of this childRegion as the center of the model
expertModelValue, nonExpertModelValue = 0, 0
if 'expert' in usersBucket:
expertUsersBucket = usersBucket['expert']
expertUsersConfidenceSum = expertUsersBucket['confidenceSum']
expertUserDistance = expertUsersBucket['averageDistance']
# expertUserCount = expertUsersBucket['usersCount']
# try:
if expertUserDistance <= 1:
expertUserDistance = 1.01
expertModelValue = expertUsersConfidenceSum * log(C * pow(expertUserDistance, -alpha))
# except:
# print 'Expert: distance->', expertUserDistance, ' confidence->' , expertUsersConfidenceSum
# print 'usersBucketKey', bucketKey
# raise
if 'nonexpert' in usersBucket:
nonExpertUsersBucket = usersBucket['nonexpert']
nonExpertUsersConfidenceSum = nonExpertUsersBucket['confidenceSum']
nonExpertUserDistance = nonExpertUsersBucket['averageDistance']
# nonExpertUserCount = nonExpertUsersBucket['usersCount']
# try:
if nonExpertUserDistance <= 1:
nonExpertUserDistance = 1.01
nonExpertModelValue = (1 - C * pow(nonExpertUserDistance, -alpha))
nonExpertModelValue = nonExpertUsersConfidenceSum * log(nonExpertModelValue)
# except:
# print 'Non Expert: distance->', nonExpertUserDistance, ' confidence->' , nonExpertUsersConfidenceSum
# print 'usersBucketKey', bucketKey
# raise
#print 'Expert Value:', expertModelValue
expertValueSum += expertModelValue
nonExpertValueSum += nonExpertModelValue
#print 'C = ', C, 'alpha = ', alpha
#print 'Expert likelihood component:' , expertValueSum
#print 'non Expert likelihood component:' , nonExpertValueSum
functionValue = expertValueSum + nonExpertValueSum
#print functionValue,' is the total likelihood value'
return functionValue
'''
Calculates the alpha for maximum value of likelihood function for
childRegion for a fixed value of C
@param C: The value of parameter C
@param childRegion: The childRegion for which we want to calculate the model
'''
def _goldenSectionSearchForAlpha(self, C, childRegion):
# Golden section search for alpha parameter for a fixed C
goldenRatio = 0.618
aAlpha = Settings.alphaMin
bAlpha = Settings.alphaMax
while bAlpha - aAlpha > Settings.alphaTolerance:
x1Alpha = aAlpha + (1 - goldenRatio) * (bAlpha - aAlpha)
x2Alpha = aAlpha + goldenRatio * (bAlpha - aAlpha)
fx1Alpha = self._likelihoodFunction(C, x1Alpha, childRegion)
fx2Alpha = self._likelihoodFunction(C, x2Alpha, childRegion)
if fx1Alpha >= fx2Alpha:
bAlpha = x2Alpha
else:
aAlpha = x1Alpha
argmaxAlpha = (aAlpha + bAlpha) / 2
maxLikelihoodValue = self._likelihoodFunction(C, argmaxAlpha, childRegion)
return (argmaxAlpha, maxLikelihoodValue)
'''
Calculates the alpha for maximum value of likelihood function for
childRegion and returns the tuple (C, alpha, maxLikelihoodValue)
@param C: The value of parameter C
@param childRegion: The childRegion for which we want to calculate the model
'''
def _goldenSectionSearch(self, childRegion):
# Golden section search for C and alpha parameters
goldenRatio = 0.618
aC = Settings.Cmin
bC = Settings.Cmax
while bC - aC > Settings.Ctolerance:
x1C = aC + (1 - goldenRatio) * (bC - aC)
x2C = aC + goldenRatio * (bC - aC)
fx1C = self._goldenSectionSearchForAlpha(x1C, childRegion)[1]
fx2C = self._goldenSectionSearchForAlpha(x2C, childRegion)[1]
if fx1C >= fx2C:
bC = x2C
else:
aC = x1C
argmaxC = (aC + bC) / 2
(argmaxAlpha, maxLikelihoodValue) = self._goldenSectionSearchForAlpha(argmaxC, childRegion)
return (argmaxC, argmaxAlpha, maxLikelihoodValue)
'''
Just a wrapper method which hides how exactly the maximum likehood value is
calculated.
'''
def _calculateMaxLogLikelihood(self, region):
self._usersBucket = BucketUsers(region, Settings.bucketingInterval)
# print 'prepared bucket for ', region.getName()
# self._usersBucket.printBucket()
value = self._goldenSectionSearch(region)
return value
'''
Finds the childRegion of the given parentRegion for which it
is maximum likely that the center of the Backstorm model will
lie in the center of this childRegion. This method calculates the
likelihood values for all the children region then return the one
with maximum likelihood value.
@param parentRegion: The parent region.
@return : A tuple containing the mleRegion, argmaxC, argmaxAlpha in that order.
mleRegion : The maximum likely region.
argmaxC : The value of C which maximizes the likelihood function for the given
mleRegion.
argmaxAlpha: The value of alpha which maximizes the likelihood function for the given
mleRegion.
'''
def _getMaximumLikelyChildRegion(self, parentRegion):
# print 'calculating maximum likelihood for all regions in'+ parentRegion.getName() +' and getting the maximum parentRegion'
previousMaxLikelihoodValue = maxLikelihoodValue = -9999999999999
(argmaxC, argmaxAlpha) = (0, 0)
mleRegion = None
for childrenRegionRow in parentRegion.getChildRegions():
for childRegion in childrenRegionRow:
(argmaxC, argmaxAlpha, value) = self._calculateMaxLogLikelihood(childRegion)
# print 'Got value =' , value
maxLikelihoodValue = max(maxLikelihoodValue, value)
# print 'Got mle Value = ', maxLikelihoodValue
if maxLikelihoodValue > previousMaxLikelihoodValue:
# print maxLikelihoodValue, ' is greater than ', previousMaxLikelihoodValue
mleRegion = childRegion
previousMaxLikelihoodValue = maxLikelihoodValue
return (mleRegion, argmaxC, argmaxAlpha)
'''
Calculates the Backstorm for a region and puts the calculted result into the queue.
@param expertiseRegion: This is the region for which the backstorm model is calculated.
@param queue: The queue in which the calculated model's data is pushed.
'''
def _computeModel(self, expertiseRegion, queue):
region = expertiseRegion
childRegionVerticalSize = Settings.initialChildRegionVerticalSize
childRegionHorizontalSize = Settings.initialChildRegionHorizontalSize
mleRegion = None
print 'Computing model for', region.getName()
while childRegionHorizontalSize >= Settings.minChildRegionSize:
region.segmentByChildSize(childRegionHorizontalSize, childRegionVerticalSize)
mleRegion, argmaxC, argmaxAlpha = self._getMaximumLikelyChildRegion(region)
# print mleRegion.getName(), ' has the largest mle value', 'C = ', argmaxC, ' alpha = ', argmaxAlpha
region = mleRegion
childRegionHorizontalSize = childRegionHorizontalSize / 2
childRegionVerticalSize = childRegionVerticalSize / 2
# Putting the resultant computed model into the queue
dictResult = {'C':argmaxC,
'alpha':argmaxAlpha,
'center':mleRegion.getCenter(),
'regionName': expertiseRegion.getName()
}
# print 'The resultant model is :', dictResult
queue.put(dictResult)
'''
Spawn a subprocess for every region in the provided 'expertiseRegions' list
and performs parallel computation then puts the results in to the provided
dataQueue asynchronously.
@param expertiseRegions: A list of regions for which we want to compute the
backstorm model
@param dataQueue: A queue which used by all the subprocess to store their results
'''
def _computeModelsParallely(self, expertiseRegions, dataQueue):
processes = []
for expertiseRegion in expertiseRegions:
processName = expertiseRegion.getName() + 'process'
process = Process(target=self._computeModel, args=(expertiseRegion, dataQueue), name=processName)
processes.append(process)
for process in processes:
process.start()
return processes
'''
The method reads the dataQueue and populates the '_dictExpertModels' dictionary
with the results present in the dataQueue.
@param expertise: The expertise for which the model data is residing in the dataQueue.
@param dataQueue: The queue in which the model data is present
'''
def _populateResultsFromQueue(self, expertise, dataQueue):
# All the children processes have finished their computation now
# lets populate the dictionary with the results that they have
# pushed into the queue.
while not dataQueue.empty():
modelDict = dataQueue.get()
if expertise in self._dictExpertModels:
# print 'Added Entry to dictionary for ', modelDict['regionName']
self._dictExpertModels[expertise].append(modelDict)
else:
# print 'Appended entry for', modelDict['regionName']
self._dictExpertModels[expertise] = [modelDict]
'''
Checks if all processes have finished computation if yes then returns
otherwise sleeps.
'''
def _waitForProcesses(self, processes):
# Here the current process sleeps while the subprocesses
# are busy in computation
while True:
areAlive = False
for process in processes:
areAlive = areAlive or process.is_alive()
if areAlive == False:
break
time.sleep(2)
'''
Simply a wrapper over _calculateMaxLogLikelihood to support
multiprocessing.
'''
def _computeLogLikeliHood(self, expertiseRegion, dataQueue):
(argmaxC, argmaxAlpha, maxLikelihoodValue) = self._calculateMaxLogLikelihood(expertiseRegion)
# Putting the resultant computed model into the queue
dictResult = {
'C':argmaxC,
'alpha':argmaxAlpha,
'center':expertiseRegion.getCenter(),
'regionName': expertiseRegion.getName()
}
dataQueue.put(dictResult)
'''
Spawn a subprocess for every region in the provided 'expertiseRegions' list
and performs parallel computation then puts the results in to the provided
dataQueue asynchronously.
@param expertiseRegions: A list of regions for which we want to compute the
backstorm model
@param dataQueue: A queue which used by all the subprocess to store their results
'''
def _computeLogLikelihoodValuesParallely(self, expertiseRegions, dataQueue):
processes = []
for expertiseRegion in expertiseRegions:
processName = expertiseRegion.getName() + 'process'
process = Process(target=self._computeLogLikeliHood, args=(expertiseRegion, dataQueue), name=processName)
processes.append(process)
for process in processes:
process.start()
self._waitForProcesses(processes)
return processes
def _optimizeParameters(self, expertise):
expertiseRegions = self._dictExpertiseRegions[expertise]
dataQueue = Queue(len(expertiseRegions))
self._computeLogLikelihoodValuesParallely(expertiseRegions, dataQueue)
self._populateResultsFromQueue(expertise, dataQueue)
def _updateExpertiseRegions(self, expertise):
dictRegionPartition = {}
usersData = UsersData.getUsersData()
for userData in usersData:
regionName = userData[5]
if regionName in dictRegionPartition:
dictRegionPartition[regionName].append(userData)
else:
dictRegionPartition[regionName] = [userData]
print 'Regions: ', dictRegionPartition.keys()
dictCenters = {}
for model in self._dictExpertModels[expertise]:
dictCenters[model['regionName']] = model['center']
expertRegions = []
for regionName in dictRegionPartition:
usersData = dictRegionPartition[regionName]
print regionName, ' has ', len(usersData), ' users assigned to it out of', len(UsersData.getUsersData()), ' users'
leftTop, rightBottom = self._getBoundingBox(usersData)
try:
expertRegion = Region(leftTop, rightBottom,
center=dictCenters[regionName], name=regionName,
isParent=True, expertise=expertise)
expertRegions.append(expertRegion)
except:
print 'Region invalid.. discarded!!'
self._dictExpertiseRegions[expertise] = expertRegions
def _displayRegionsInfo(self, expertise):
expertiseRegions = self._dictExpertiseRegions[expertise]
models = self._dictExpertModels[expertise]
#map_plots.plotRegion(expertiseRegions, models)
'''
Generates models for given expertises regions
@param expertise: The expertise for which we want to generate Backstorm models.
'''
def generateModelForExpertise(self, expertise):
print 'Generating model for', expertise
# extracting the regions for the given expertise
self._optimizeParameters(expertise)
expertiseRegions = self._dictExpertiseRegions[expertise]
dataQueue = Queue(len(expertiseRegions))
print 'Initially computed models:-'
pprint(self._dictExpertModels)
iternum = 0
while iternum < Settings.numberOfIterations:
UsersData.partitionUsers(self._dictExpertModels[expertise], expertise)
print 'Recomputed Bounding boxes for regions-----'
self._updateExpertiseRegions(expertise)
self._displayRegionsInfo(expertise)
self._dictExpertModels.clear()
expertiseRegions = self._dictExpertiseRegions[expertise]
print '---- Recomputing the centers------------'
start = time.time()
processes = self._computeModelsParallely(expertiseRegions, dataQueue)
self._waitForProcesses(processes)
self._populateResultsFromQueue(expertise, dataQueue)
print 'It took ', start - time.time(), ' seconds'
print '---------------Generated multiple center model----------'
pprint(self._dictExpertModels)
iternum += 1
def generateSingleCenterModel(self, expertise):
expertiseRegion = self._dictExpertiseRegions[expertise][0]
dataQueue = Queue(1)
self._computeModel(expertiseRegion, dataQueue)
self._populateResultsFromQueue(expertise, dataQueue)
self._dictExpertModels[expertise] = dataQueue.get()
pprint(self._dictExpertModels)
'''
Generates models for all expertise extracted from the users data
'''
def generateModelForAllExpertise(self):
print 'Generating model for all expertise'
for expertise in self._dictExpertiseRegions:
self.generateModelForExpertise(expertise)
'''
Creates bounding regions for all the expertise extracted from the users data
'''
def _createParentRegions(self):
print 'creating parent Regions'
for expertise in self._dictExpertUsersData:
self._initializeExpertRegions(expertise)
'''
Generates a random center for a given bounding region's lefttop and
right bottom coordinates
@param leftTop: The coordinates tuple for the left top corner
of the region (latitude, longitude)
@param rightBottom: The coordinates tuple for the right bottom
corner of the region (latitude, longitude)
'''
def _getRandomCenter(self, leftTop, rightBottom):
randomLattitude = randint(int(rightBottom[0] * 1000), int(leftTop[0] * 1000)) / 1000.0
randomLongitude = randint(int(leftTop[1] * 1000), int(rightBottom[1] * 1000)) / 1000.0
randomCenter = (randomLattitude, randomLongitude)
return randomCenter
'''
Generates the random centers such that they are uniformly distributed over the
targeted geographical region
'''
def _getRandomCenters(self, leftTop, rightBottom):
dummyRegion = Region(leftTop, rightBottom)
childRegionCount = int(round(pow(Settings.numberOfcenters,0.5)))
dummyRegion.segmentByChildCount(childRegionCount, childRegionCount)
randomCenters = []
for childRegionRow in dummyRegion.getChildRegions():
for childRegion in childRegionRow:
randomCenter = self._getRandomCenter(childRegion.getLeftTop(), childRegion.getRightBottom())
randomCenters.append(randomCenter)
return randomCenters
'''
Creates a bounding region for a certain expertise based on the
location information in user data.
@param expertise: The expertise for which we want to create a bounding
region.
@return: The bounding region corresponding to the expertise.
'''
def _getBoundingBox(self, expertUsersData):
maxLatitude = max(expertUsersData, key=itemgetter(2))[2]
minLatiude = min(expertUsersData, key=itemgetter(2))[2]
maxLongitude = max(expertUsersData, key=itemgetter(3))[3]
minLongitude = min(expertUsersData, key=itemgetter(3))[3]
leftTop = maxLatitude, minLongitude
rightBottom = minLatiude, maxLongitude
return leftTop, rightBottom
def _initializeExpertRegions(self, expertise):
expertUsersData = self._dictExpertUsersData[expertise]
if len(expertUsersData) == 0:
return
leftTop, rightBottom = self._getBoundingBox(expertUsersData)
expertRegions = []
centers = self._getRandomCenters(leftTop, rightBottom)
for index in range(len(centers)):
center = centers[index]
regionName = str(expertise) + ' Region ' + str(index)
expertRegion = Region(leftTop, rightBottom, center=center , name=regionName,
isParent=True, expertise=expertise)
expertRegions.append(expertRegion)
# print 'Coordinates : minlatitude = ', minLatiude, ', maxLatitude = ', maxLatitude
# print 'minlongitude = ', minLongitude, ', maxlongitude = ', maxLongitude
self._dictExpertiseRegions[expertise] = expertRegions
'''
Gets the expertise for a bounding region
@param region: The expertise corresponding to the provided bounding Region.
'''
def _getExpertiseForRegion(self, region):
return region.getName().split(' ')[0]
def getModelsForExpertise(self, expertise):
return self._dictExpertModels[expertise]
def getModelsForAllExpertise(self):
return self._dictExpertModels
'''
Methods for Debugging and testing purposes.
'''
def testGoldenSectionSearch(self, regionCenter, expertise):
expertRegion = Region((45, -129), (25, -50),
center=regionCenter , name='Test Region',
isParent=True, expertise=expertise)
self._usersBucket = BucketUsers(expertRegion, Settings.bucketingInterval)
self._usersBucket.printBuckets()
print self._goldenSectionSearch(expertRegion)
def testLikelihood(self, regionCenter, expertise, C, alpha):
expertRegion = Region((45, -129), (25, -50),
center=regionCenter , name='Test Region',
isParent=True, expertise=expertise)
self._usersBucket = BucketUsers(expertRegion, Settings.bucketingInterval)
print 'likelihood value:', self._likelihoodFunction(C, alpha, expertRegion)
def display(self):
print 'Models Created as follows'
pprint(self._dictExpertModels)
def main():
print 'Main'
dataDirectory = 'expertisedata/'
modelGenerator = BackStromExpertiseModelGenerator(dataDirectory)
start = time.time()
#print modelGenerator.testGoldenSectionSearch((33.174, -90.322), 'vc')
#print modelGenerator.testLikelihood(regionCenter = (45.174, -126.322), expertise = 'vc', C = .9 , alpha = .5)
#modelGenerator.generateSingleCenterModel('vc')
modelGenerator.generateModelForAllExpertise()
print 'Time Taken:', time.time() - start, ' seconds'
modelGenerator.display()
if __name__ == "__main__":
main()
<file_sep>'''
Created on Jan 25, 2014
@author: <NAME>
'''
from matplotlib.pyplot import *
from utils import Utils
from operator import itemgetter
from math import log
import matplotlib as mpl
class PlotPlacesTypeDistribution:
def __init__(self, datafile):
self._datafile = datafile
def plot_data(self, pdf_file, image_filename):
place_types = []
reference_counts = []
for data_row in Utils.get_data_vectors(self._datafile, ' '):
place_types.append(data_row[0])
reference_counts.append(int(data_row[1]))
figure(1, figsize = (6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])
# The slices will be ordered and plotted counter-clockwise.
labels = place_types
total_references = sum(reference_counts)
# Eliminate the NA data
index = place_types.index('NotAvailable')
place_types.pop(index)
NA_count = reference_counts.pop(index)
NA_percentage = 100 * NA_count / float(total_references)
total_references -= NA_count
fracs = [count / float(total_references) for count in reference_counts]
explode = (0, 0, 0, 0, 0)
mpl.rcParams['font.size'] = 9.0
pie(fracs, explode = explode, labels = labels, autopct = '%1.1f%%', shadow = False, startangle = 0)
# The default startangle is 0, which would start
# the Frogs slice on the x-axis. With startangle=90,
# everything is rotated counter-clockwise by 90 degrees,
# so the plotting starts on the positive y-axis.
title('Place Type Distribution: ' + str(NA_percentage) +
'% tweets dont have a place type, showing the remaining tweets',
bbox = {'facecolor':'0.8', 'pad':5})
savefig(pdf_file, format = 'pdf')
savefig(image_filename)
clf()
def main():
plotter = PlotPlacesTypeDistribution('/home/himanshu/data/output/place_type_distribution')
plotter.plot_data()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Jan 24, 2014
@author: <NAME>
'''
from os.path import join
from utils import Utils
from matplotlib.backends.backend_pdf import PdfPages
import settings
class PlotsGenerator:
@classmethod
def generate_plots(cls, data_directory, output_directory):
plotters = settings.plotters
output_pdf_file = join(output_directory, settings.plot_pdf_file)
pp = None
try:
pp = PdfPages(output_pdf_file)
for plotclass in plotters:
key = Utils.get_plotclass_key(plotclass)
data_file_name = settings.jobsettings[key]['datafile']
image_file = join(output_directory, settings.jobsettings[key]['plot_image_file'])
data_file_name = join(data_directory, data_file_name)
plotter = plotclass(data_file_name)
plotter.plot_data(pp, image_file)
finally:
pp.close()
def main():
args = Utils.parse_plotter_args()
PlotsGenerator.generate_plots(args.data_directory, args.output_directory)
if __name__ == '__main__':
main()
<file_sep>'''
Created on Apr 11, 2013
@author: <NAME>
'''
from extractdata import DataExtractorFactory
from region import Region
from userdata import UsersData
from utility import Utility
import time
from pprint import pprint
class BucketUsers:
_interval = 5
_center = (0, 0)
_expertCount = 0
_usersData = None
_region = None
_bucketedUserData = {'5-10': {'averageDistance':3.5, 'confidenceSum': .786}}
def __init__(self, region, interval):
self._bucketedUserData.clear()
self._region = region
self._center = self._region.getCenter()
self._interval = interval
self._usersData = UsersData.getUsersData()
self._bucketUserData()
self._normalizeBuckets()
'''
Gets the bucket key for a user located at the given distance.
@param distance: The distance at which the user is located
@return: The corresponding key for the bucket in which the user will be
put in.
'''
def _getBucketKey(self, distance):
index = int(distance / self._interval)
bucketKey = str(self._interval * index) + '-' + str(self._interval * (index + 1))
return bucketKey
'''
Bucket-wise averages the distances of all the expert and non-expert users
'''
def _normalizeBuckets(self):
# Now we average out all the users distances and confidences
# within each bucket
totalNonExpertCount = 0
for bucketKey in self._bucketedUserData:
usersBucket = self._bucketedUserData[bucketKey]
expertUsersBucket = usersBucket['expert']
expertUsersCount = float(expertUsersBucket['usersCount'])
expertUsersDistanceSum = expertUsersBucket.pop('distanceSum')
nonExpertUsersBucket = usersBucket['nonexpert']
nonExpertUsersCount = float(nonExpertUsersBucket['usersCount'])
nonExpertUsersDistanceSum = nonExpertUsersBucket.pop('distanceSum')
totalNonExpertCount += nonExpertUsersCount
if expertUsersCount != 0:
expertUsersBucket['averageDistance'] = expertUsersDistanceSum / expertUsersCount
else:
expertUsersBucket.clear()
if nonExpertUsersCount != 0:
nonExpertUsersBucket['averageDistance'] = nonExpertUsersDistanceSum / nonExpertUsersCount
else:
nonExpertUsersBucket.clear()
# If no experts were found in the bucket clear the dictionary object
if len(expertUsersBucket) == 0:
usersBucket.pop('expert')
# If no non-experts were found in the bucket clear the dictionary object
if len(nonExpertUsersBucket) == 0:
usersBucket.pop('nonexpert')
'''
Returns the pair of keys to be used.
'''
def _getKeys(self, isExpert):
requiredKey = ''
nonRequiredKey = ''
if isExpert:
requiredKey = 'expert'
nonRequiredKey = 'nonexpert'
else:
requiredKey = 'nonexpert'
nonRequiredKey = 'expert'
return requiredKey, nonRequiredKey
'''
Creates the buckets of expert and non expert users based on their
distance from the center of the region under consideration. All the
users who are not in the root region of the current expertise
will be ignored.
'''
def _bucketUserData(self):
#print 'Bucketing ', len(self._usersData), ' users !'
#count = 0
expertise = self._region.getExpertise()
#print 'bucketing for ', self._region.getName()
for userData in self._usersData:
userLocation = (userData[2], userData[3])
# print userData
# The root expertise region from which this child has descended
parentRegion = None
if self._region.isParent():
parentRegion = self._region
else:
parentRegion = self._region.getParent()
if parentRegion.boundsLocation(userData):
#count += 1
# if the user data is corresponding to a location
# belonging to the expertise region only then we include it in
# our calculation
userConfidence = userData[1]
userDistance = Utility.haversine(self._center[1], self._center[0], userLocation[1], userLocation[0])
isExpert = (expertise == userData[4])
distanceBucketKey = self._getBucketKey(userDistance)
requiredKey, nonRequiredKey = self._getKeys(isExpert)
if not distanceBucketKey in self._bucketedUserData:
self._bucketedUserData[distanceBucketKey] = {}
self._bucketedUserData[distanceBucketKey][requiredKey] = {'distanceSum': userDistance,
'confidenceSum': userConfidence,
'usersCount': 1
}
self._bucketedUserData[distanceBucketKey][nonRequiredKey] = {'distanceSum': 0.0,
'confidenceSum': 0.0,
'usersCount': 0
}
else:
# calculating the sum of all users' distance and confidence within a
# certain radius denoted by the bucketKey
#print 'Incrementing------------------------------------'
self._bucketedUserData[distanceBucketKey][requiredKey]['distanceSum'] += userDistance
self._bucketedUserData[distanceBucketKey][requiredKey]['confidenceSum'] += userConfidence
self._bucketedUserData[distanceBucketKey][requiredKey]['usersCount'] += 1
#print count,' users were bucketed'
'''
Returns the bucket dictionary for the users.
'''
def getUsersBucket(self):
return self._bucketedUserData
'''
For testing and debugging purposes.
'''
def printBuckets(self):
totalExpertsCount = 0
totalNonExpertsCount = 0
for bucketKey in self._bucketedUserData:
expertCount = 0
expertConfindenceSum = 0
nonExpertCount = 0
nonExpertConfindenceSum = 0
if 'expert' in self._bucketedUserData[bucketKey]:
expertCount = self._bucketedUserData[bucketKey]['expert']['usersCount']
expertConfindenceSum = self._bucketedUserData[bucketKey]['expert']['confidenceSum']
totalExpertsCount += expertCount
print 'Bucket ', bucketKey,' has ',expertCount, 'experts with expertConfindenceSum = ',expertConfindenceSum
if 'nonexpert' in self._bucketedUserData[bucketKey]:
nonExpertCount = self._bucketedUserData[bucketKey]['nonexpert']['usersCount']
nonExpertConfindenceSum = self._bucketedUserData[bucketKey]['nonexpert']['confidenceSum']
totalNonExpertsCount += nonExpertCount
print 'Bucket ', bucketKey,' has ',nonExpertCount, 'nonexperts with expertConfindenceSum = ',nonExpertConfindenceSum
print 'Total experts:', totalExpertsCount, ' Total non experts:', totalNonExpertsCount
def main():
print 'Main'
dataDirectory = 'data/'
start = time.time()
data = DataExtractorFactory.getDataExtractor('expertisemodel', dataDirectory)
expertUsersData = data.getAllExpertsData()
region = Region((50, -125), (25.255, -60),center = (30,-60) ,expertise='vc')
UsersData.addUserDataToRegions(expertUsersData)
usersBucket = BucketUsers(region, 50)
print time.time() - start,' is the time taken'
usersBucket.printBuckets()
if __name__ == "__main__":
main()
<file_sep>'''
Created on Jan 18, 2014
@author: <NAME>
'''
from mrjob.job import MRJob
from cjson import decode
from common_functions import Utils
class MRUserHomeLocationSharingDistribution(MRJob):
'''
Generates a distribution of users and
home location sharing behavior in a given dataset
generated by dataextractor.TweetParser .
'''
def configure_options(self):
super(MRUserHomeLocationSharingDistribution, self).configure_options()
self.add_file_option('--filter_file', help = 'The file containing'
' the uids, to be applied as filter on the data.')
self.add_passthrough_option('--apply_filter', action = 'store_true',
default = False, dest = 'apply_filter')
def load_options(self, args):
super(MRUserHomeLocationSharingDistribution, self).load_options(args)
filter_filename = self.options.filter_file
if self.options.apply_filter:
self._uids = Utils.get_filter_uids(filter_filename)
def yield_data(self, data):
if data['l'] != '':
yield 'Users_Sharing_Home_Location', 1
else:
yield 'Users_Not_Sharing_Home_Location', 1
def read_data(self, _, line):
data = decode(line)
if self.options.apply_filter:
if data['u'] in self._uids:
return self.yield_data(data)
else:
return self.yield_data(data)
def aggregate_data(self, tweet_type, count):
yield tweet_type, sum(count)
def steps(self):
return [self.mr(mapper = self.read_data,
combiner = self.aggregate_data,
reducer = self.aggregate_data)]
def main():
MRUserHomeLocationSharingDistribution.run()
if __name__ == '__main__':
main()
<file_sep>'''
@author: <NAME>
@revision : <NAME>
'''
# Create your views here.
from django.http import HttpResponse
from django.template import loader, Context
from django.views.generic import View
from expertsmodels.api.experts_api import ExpertsDataAPI
from expertsmodels.api.experts_api import ExpertsSearchAPI
from json import dumps
from rest_framework.decorators import APIView
from rest_framework.response import Response
'''
This view provides the template for expert search page
'''
class ExpertSearchView(View):
def get(self, request):
return self.getExpertSearch(request)
def getExpertSearch(self, request):
template = loader.get_template('expertsearch.html')
return HttpResponse(template.render(Context({'dummy':None})))
'''
This view provides all the web services for the expert search page.
'''
class ExpertSearchService(APIView):
_expertSearchAPI = ExpertsSearchAPI()
def get(self, request):
query = request.REQUEST['query']
userLocation = request.REQUEST['userlocation']
coordinates = userLocation.split(',')
userLocation = (float(coordinates[0]), float(coordinates[1]))
results = self._expertSearchAPI.getExperts(query, userLocation)
jsonData = dumps(results)
return Response(jsonData)
'''
This view serves the page for the heatmap page.
'''
class ExpertsHeatMapView(View):
def get(self, request):
return self.getExpertSearch(request)
def getExpertSearch(self, request):
template = loader.get_template('expertsearch.html')
return HttpResponse(template.render(Context({'dummy':None})))
'''
This view provides all the web services for the expert search page.
'''
class ExpertSearchService(APIView):
_expertSearchAPI = ExpertsSearchAPI()
def get(self, request):
query = request.REQUEST['query']
userLocation = request.REQUEST['userlocation']
coordinates = userLocation.split(',')
userLocation = (float(coordinates[0]), float(coordinates[1]))
results = self._expertSearchAPI.getExperts(query, userLocation)
jsonData = dumps(results)
return Response(jsonData)
'''
This view serves the page for the heatmap page.
'''
class ExpertsHeatMapView(View):
def get(self, request):
return self.getExpertiseHeatmap(request)
def getExpertiseHeatmap(self, request):
template = loader.get_template('heatmap.html')
return HttpResponse(template.render(Context({'dummy':None})))
'''
This view provides the webservices for the heatmap page.
'''
class ExpertsHeatMapService(APIView):
requestType = ''
expertLocationsJson = {}
expertsAPIObject = ExpertsDataAPI()
HEATMAP = 'heatmap:'
def getHeatMapKey(self, expertise, expertId = ''):
return self.HEATMAP + expertise + expertId
def get(self, request):
print 'Got request inside get function'
expertise, expertId = '', ''
if 'expertise' in request.REQUEST:
expertise = request.REQUEST['expertise']
if 'expertId' in request.REQUEST:
expertId = request.REQUEST['expertId']
if self.requestType == 'expertiselocations':
return self.getUserLocationsForExpertise(request, expertise)
if self.requestType == 'expertslocations':
return self.getUserLocationsForExpert(request, expertise, expertId)
def getUserLocationsForExpertise(self, request, expertise):
if self._isAvailableInCache(request, expertise):
cachedData = self._getCacheData(request, expertise)
return Response(cachedData)
else :
print 'Data not found'
print 'Getting expertise heatmap data for ', expertise
expertsLocations = self.expertsAPIObject.getExpertiseHeatmapData(expertise)
jsonData = dumps(expertsLocations)
self._cacheData(request, expertise, jsonData)
return Response(jsonData)
def getUserLocationsForExpert(self, request, expertise, expertId):
print 'Executing -- getUserLocationsForExpert'
if self._isAvailableInCache(request, expertise + expertId):
cachedData = self._getCacheData(request, expertise, expertId)
return Response(cachedData)
else :
print 'Data not found'
print 'Getting expert heatmap data for ', expertise, '-', expertId
expertsLocations = self.expertsAPIObject.getExpertHeatmapData(expertise, expertId)
jsonData = dumps(expertsLocations)
self._cacheData(request, expertise + expertId, jsonData)
return Response(jsonData)
def _isAvailableInCache(self, request, expertise, expertId = ''):
key = self.getHeatMapKey(expertise, expertId)
return key in request.session
def _cacheData(self, request, expertise, data):
key = self.getHeatMapKey(expertise)
print 'Caching data for key', key
request.session[key] = data
def _getCacheData(self, request, expertise, expertId = ''):
key = self.getHeatMapKey(expertise, expertId)
print 'Getting data from cache for key', key
return request.session[key]
<file_sep>'''
Created on Feb 12, 2014
@author: <NAME>
'''
jobsettings = {
# Both the start and end times are in UNIX epoch time.
# These are epoch times with respect to GMT , although
# the tweet timestamps are in local time zone but since we
# are no interested in the daily patterns so we can avoid translating
# the local time to GMT, and thus we will use the GMT epoch times
# for creating buckets.
'ExtractTimeSeries':{'start_timestamp' : 1357083600,
'end_timestamp' : 1357084800,
#Bucket width is in seconds
'bucket_width': 60},
'ExtractPartitionedUsersByCoordinateSharingBehavior':{}
}
<file_sep>'''
Created on Apr 23, 2013
@author: himanshu
'''
class Settings:
'''
BackStrom Model Settings
'''
numberOfIterations = 10
numberOfcenters = 10
bucketingInterval = 10
# min - max values for the C and alpha parameter
alphaMin = 0.01
alphaMax = 9.99
Cmin = 0.001
Cmax = 0.999
# tolerance values for the golden section search algorithm
Ctolerance = .001
alphaTolerance = 0.01
# intial size of each grid
initialChildRegionVerticalSize = 2
initialChildRegionHorizontalSize = 2
# minimum size of grid
minChildRegionSize = .1
'''
Data extractor settings
'''
maxExperts = 5000
topKExpertCount = 10
dataFileNamePartOne = 'expert_locations_for_'
dataFileNamePartTwo = '_full_data.txt'
filterList = [
{
'leftTopCoordinates' : (50, -129),
'rightBottomCoordinates' : (25.255, -60),
'region' : 'USA'
}
]
userDataFileName = 'list_creator_user_location.json'
expertUserListFileName = 'userids.txt'
<file_sep>'''
Created on Jan 31, 2014
@author: <NAME>
'''
from matplotlib.pyplot import *
from utils import Utils
import matplotlib as mpl
class PlotTweetDistribution:
def __init__(self, datafile):
self._datafile = datafile
def plot_data(self, pdf_file, image_filename):
categories = []
tweet_count = []
for data_row in Utils.get_data_vectors(self._datafile, ' '):
categories.append(data_row[0])
tweet_count.append(int(data_row[1]))
figure(1, figsize = (6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])
# The slices will be ordered and plotted counter-clockwise.
labels = categories
total_references = sum(tweet_count)
fracs = [count / float(total_references) for count in tweet_count]
explode = (0, 0)
mpl.rcParams['font.size'] = 12.0
pie(fracs, explode = explode, labels = labels, autopct = '%1.1f%%', shadow = False, startangle = 0)
# The default startangle is 0, which would start
# the Frogs slice on the x-axis. With startangle=90,
# everything is rotated counter-clockwise by 90 degrees,
# so the plotting starts on the positive y-axis.
title('Tweet Distribution for ' + str(total_references) + ' tweets.', bbox = {'facecolor':'0.8', 'pad':5})
savefig(pdf_file, format = 'pdf')
savefig(image_filename)
clf()
def main():
plotter = PlotTweetDistribution('/home/himanshu/data/output/user_home_location_sharing')
plotter.plot_data()
if __name__ == '__main__':
main()
<file_sep>''''
Created on Dec 21, 2013
@author: <NAME>
'''
from mrjob.job import MRJob
from cjson import decode
from common_functions import Utils
class MRSharingDeviceDistribution(MRJob):
'''
Counts the number of tweets location shared by different
devices in a given dataset generated by dataextractor.TweetParser.
'''
def configure_options(self):
super(MRSharingDeviceDistribution, self).configure_options()
self.add_file_option('--filter_file', help = 'The file containing'
' the uids, to be applied as filter on the data.')
self.add_passthrough_option('--apply_filter', action = 'store_true',
default = False, dest = 'apply_filter')
def load_options(self, args):
super(MRSharingDeviceDistribution, self).load_options(args)
filter_filename = self.options.filter_file
if self.options.apply_filter:
self._uids = Utils.get_filter_uids(filter_filename)
def yield_data(self, data):
source = data['src']
if source != 'N':
yield source.replace('|', ''), 1
def read_data(self, _, line):
data = decode(line)
if self.options.apply_filter:
if data['u'] in self._uids:
return self.yield_data(data)
else:
return self.yield_data(data)
def aggregate_data(self, source, count):
source = source.encode('ascii', 'replace')
yield source + '|', sum(count)
def steps(self):
return [self.mr(mapper = self.read_data,
reducer = self.aggregate_data)
]
def main():
MRSharingDeviceDistribution.run()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Mar 29, 2013
@author: himanshu
'''
from django.conf.urls import patterns, url
from expertsmodels.views import ExpertsHeatMapView
from expertsmodels.views import ExpertsHeatMapService
from expertsmodels.views import ExpertSearchService
from expertsmodels.views import ExpertSearchView
urlpatterns = patterns('',
url(r'^$', ExpertsHeatMapView.as_view()),
url(r'^expertSearch', ExpertSearchView.as_view()),
url(r'^getExpertSearchResults', ExpertSearchService.as_view()),
url(r'^getExpertiseHeatmapData$', ExpertsHeatMapService.as_view(requestType = 'expertiselocations')),
url(r'^getExpertHeatmapData$', ExpertsHeatMapService.as_view(requestType = 'expertslocations'))
)<file_sep>'''
Created on Dec 20, 2013
@author: <NAME>
'''
import os, gzip, cjson
import argparse
from library.twitter import TweetFiles, getStringRepresentationForTweetTimestamp, \
getDateTimeObjectFromTweetTimestamp
from library.file_io import FileIO
from library.geo import isWithinBoundingBox, getCenterOfMass, \
getHaversineDistance
from settings import us_boundary
from bs4 import BeautifulSoup
from os.path import exists
from os import walk
import sys
class TweetParser:
'''
Provides the functionality of parsing the files in the hierarchy
of the twitter data at Infolab, extracting the checkin data
and populating it into files such that each file represents monthly data.
'''
@classmethod
def tweetFilesIterator(cls, year, months, input_dir, output_dir):
checkinsFile = output_dir + '%s' % year + '_%s'
bdeDataFolder = input_dir + '%s' % year + '/%s/%s/'
for month in months:
outputFile = checkinsFile % month
for day in range(1, 32):
tweetsDayFolder = bdeDataFolder % (month, day)
if exists(tweetsDayFolder):
for _, _, files in walk(tweetsDayFolder):
for file in files:
yield outputFile, tweetsDayFolder + file
@classmethod
def _get_social_status(cls, data):
social_status = 'N'
# Calculate social status
followers = data['user']['followers_count']
freinds = data['user']['friends_count']
if freinds != 0:
social_status = followers / float(freinds)
return str(social_status)
@classmethod
def _get_coordinates(cls, data):
place_type = 'N'
coordinates = 'N'
try:
# Extract the coordinates of the checkin
if 'geo' in data and data['geo'] != None:
coordinates = data['geo']['coordinates']
elif 'coordinates'in data and data['coordinates'] != None:
coordinates = data['coordinates']
if 'place' in data and data['place'] != None and \
'place_type' in data['place'] and data['place']['place_type'] != None:
# Extract the place_type
place_type = data['place']['place_type']
except:
print 'Error while extracting coordinates'
print 'Data:', data
print sys.exc_info()
return coordinates, place_type
@classmethod
def _get_tweet_source(cls, data):
# Extract the tweet source
soup = BeautifulSoup(data['source'])
source = soup.get_text(',', strip = True)
return source
@classmethod
def getTweetObject(cls, data):
tweet_data = {}
if 'user' not in data:
return 0
social_status = cls._get_social_status(data)
coordinates, place_type = cls._get_coordinates(data)
source = cls._get_tweet_source(data)
timestamp = data['created_at']
# Populate the data into a dictionary
tweet_data['u'] = data['user']['id']
tweet_data['tid'] = data['id']
tweet_data['ss'] = social_status
tweet_data['sc'] = data['user']['statuses_count']
tweet_data['l'] = data['user']['location']
tweet_data['src'] = source
tweet_data['c'] = coordinates
tweet_data['p'] = place_type
tweet_data['t'] = timestamp
tweet_data['ge'] = data['user']['geo_enabled']
tweet_data['uc'] = data['user']['created_at']
# converting to tab separated format
return tweet_data
@classmethod
def parse_args(cls):
parser = argparse.ArgumentParser('The utility parses the tweet data in the'
' infolab servers, for a given range of months of an year'
' and writes them into a file in the given output directory.')
parser.add_argument('-input_directory',
help = 'The input directory where the twitter data is residing.',
default = '/mnt/chevron/bde/Data/TweetData/GeoTweets/')
parser.add_argument('-output_directory',
help = 'The output directory where the parsed twitter data is to be written.',
default = './')
parser.add_argument('-year',
help = 'The year for which the data is to be parsed..',
default = '2013')
parser.add_argument('-months',
help = 'Comma separated months for which the data is to be parsed.',
default = '1,3')
args = parser.parse_args()
return args
def main():
args = TweetParser.parse_args()
months = args.months.split(',')
print 'Starting to parse tweet files...'
for outputFile, file in TweetParser.tweetFilesIterator(args.year, months, args.input_directory, args.output_directory):
print 'Parsing: %s' % file
with gzip.open(file, 'rb') as data_file:
print 'Opened file..'
for line in data_file:
try:
data = cjson.decode(line)
tweet = TweetParser.getTweetObject(data)
if tweet != 0:
FileIO.writeToFileAsJson(tweet, outputFile)
except:
print 'Exception'
print sys.exc_info()
print 'Data extracted ! !'
if __name__ == '__main__':
main()
<file_sep>'''
Created on Sep 2, 2013
@author: himanshu
'''
from httplib import HTTPSConnection, HTTPS_PORT
from urllib2 import quote
from bs4 import BeautifulSoup
from re import compile
class TwitterResultsFetcher:
_locations = [('New York', 15),
('San Francisco', 15),
('Chicago', 15),
('Houston', 15)
]
_topics = [ 'food', 'tech', 'travel', 'entertain']
_twitterURL = 'twitter.com'
_searchParams = '/search?q=topic%20near%3A"location"%20within%3AXXmi&src=typd&mode=users'
_resultsDict = {}
_tagIdRegex = compile('stream-item-user-[\d]+')
def __init__(self):
self._resultsDict = {}
def _fetchHTML(self, searchURL):
connection = HTTPSConnection(self._twitterURL, HTTPS_PORT)
print 'Connection setup done ...'
connection.request("GET", searchURL)
print 'Made request..'
response = connection.getresponse()
print 'Got response ...Status:', response.status
html = response.read()
return html
def _getSearchURL(self, topic, location, radius):
encodedTopic = quote(topic)
encodedLocation = quote(location)
searchURL = self._searchParams.replace('topic', encodedTopic)
searchURL = searchURL.replace('location',encodedLocation)
searchURL = searchURL.replace('XX',str(radius))
print searchURL
return searchURL
def getTwitterResults(self):
for location in self._locations:
for topic in self._topics:
searchURL = self._getSearchURL(topic, location[0], location[1])
resultHTML = self._fetchHTML(searchURL)
print resultHTML
userIds = self.parseUserIds(resultHTML)
self._resultsDict[topic + '-' + location[0]] = userIds
return self._resultsDict
def parseUserIds(self, html):
userIds = []
parser = BeautifulSoup(html)
matchingTags = parser.find_all('li')
for matchingTag in matchingTags:
print matchingTag.attrs
if matchingTag.attrs.has_key('data-item-id'):
userId = matchingTag.attrs['data-item-id']
if userId != None:
userIds.append(userId)
return userIds
def main():
fetcher = TwitterResultsFetcher()
result = fetcher.getTwitterResults()
print result, len(result['tech-New York'])
if __name__ == "__main__":
main()
<file_sep>'''
Created on Jan 25, 2014
@author: <NAME>
'''
import matplotlib.pyplot as P
from utils import Utils
from operator import itemgetter
from math import log
class PlotUserTweetCountDistribution:
def __init__(self, datafile):
self._datafile = datafile
def plot_data(self, pdf_file, image_filename):
data_points = []
total_user_count = 0
total_tweet_count = 0
for data_row in Utils.get_data_vectors(self._datafile, ' '):
num_tweets = int(data_row[0])
user_count = int(data_row[1])
total_user_count += user_count
total_tweet_count += num_tweets
data_points.append((num_tweets, user_count))
bins = []
user_count = []
for data_point in sorted(data_points, key = itemgetter(0)):
bins.append(log(data_point[0] + 1))
user_count.append(log(data_point[1] + 1))
_, axes = P.subplots()
axes.plot(user_count, bins, 'ro')
axes.set_ylabel('log(Tweet Count)')
axes.set_xlabel('log(User Count)')
P.savefig(pdf_file, format = 'pdf')
P.savefig(image_filename)
P.clf()
def main():
plotter = PlotUserTweetCountDistribution('/home/himanshu/data/output/user_tweets_count')
plotter.plot_data()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Jan 14, 2014
@author: <NAME>
'''
from analysis.plots.coordinate_sharing import PlotUserCoordinatesSharingDistribution
from analysis.plots.home_location_sharing import PlotUserHomeLocationSharingDistribution
from analysis.plots.place_type import PlotPlacesTypeDistribution
from analysis.plots.tweet_count_distribution import PlotUserTweetCountDistribution
from analysis.plots.sharing_device_distribution import PlotSharingDeviceDistribution
from analysis.plots.geotweet_count_distribution import PlotUserGeoTweetCountDistribution
from analysis.plots.selective_coordinate_hiding import PlotUserSelectiveCoordinatesHidingDistribution
from analysis.plots.tweet_distribution import PlotTweetDistribution
from analysis.statistics.coordinate_sharing import MRUserCoordinatesSharingDistribution
from analysis.statistics.tweet_distribution import MRTweetDistribution
from analysis.statistics.tweet_count_distribution import MRUserTweetCountDistribution
from analysis.statistics.place_type import MRPlacesTypeDistribution
from analysis.statistics.sharing_device_distribution import MRSharingDeviceDistribution
from analysis.statistics.selective_coordinate_hiding import MRUserSelectiveCoordinatesHidingDistribution
from analysis.statistics.geotweet_count_distribution import MRUserGeoTweetCountDistribution
from analysis.statistics.home_location_sharing import MRUserHomeLocationSharingDistribution
from dataextractor.partition_users_by_coordinate_sharing_behavior import MRExtractPartitionedUsersByCoordinateSharingBehavior
from dataextractor.time_series import MRExtractTimeSeries
# File locations
raw_data_directory = '/home/himanshu/data/raw_data'
stats_data_directory = '/home/himanshu/data/stats/'
plots_directory = '/home/himanshu/data/plots'
plot_pdf_file = 'plots.pdf'
# Modify this to specify which statistics needs to be generated
data_extractors = [
MRExtractPartitionedUsersByCoordinateSharingBehavior,
MRExtractTimeSeries
]
# Modify this to specify which statistics needs to be generated
stats_generators = [
MRUserCoordinatesSharingDistribution,
MRUserSelectiveCoordinatesHidingDistribution,
MRTweetDistribution,
MRUserGeoTweetCountDistribution,
MRUserTweetCountDistribution,
MRPlacesTypeDistribution,
MRSharingDeviceDistribution,
MRUserHomeLocationSharingDistribution
]
# Modify this to specify which plots needs to be generated
plotters = [PlotUserCoordinatesSharingDistribution, PlotPlacesTypeDistribution,
PlotSharingDeviceDistribution, PlotUserHomeLocationSharingDistribution,
PlotUserTweetCountDistribution, PlotUserSelectiveCoordinatesHidingDistribution,
PlotTweetDistribution, PlotUserGeoTweetCountDistribution
]
# Settings for the different statistic tasks. These are used by both the
# stats generator and the plots generator.
jobsettings = {
'UserCoordinatesSharingDistribution' : {'datafile' :'user_coordinates_sharing',
'plot_image_file' :'user_coordinates_sharing'},
'UserSelectiveCoordinatesHidingDistribution' : {'datafile' :'user_selective_coordinates_hiding',
'plot_image_file' :'user_selective_coordinates_hiding'},
'UserHomeLocationSharingDistribution' :{'datafile' : 'user_home_location_sharing',
'plot_image_file' :'user_home_location_sharing.png'},
'PlacesTypeDistribution':{'datafile' :'place_type_distribution',
'plot_image_file' :'place_type_distribution.png'},
'SharingDeviceDistribution':{'datafile' : 'sharing_device_distribution',
'plot_image_file' :'sharing_device_distribution.png'},
'UserTweetCountDistribution':{'datafile' :'user_tweets_count',
'plot_image_file' :'user_tweets_count.png'},
'UserGeoTweetCountDistribution':{'datafile' :'user_geotweets_count',
'plot_image_file' :'user_geotweets_count.png'},
'TweetDistribution':{'datafile' :'tweets_distribution',
'plot_image_file' :'tweets_distribution.png'},
'ExtractTimeSeries':{'datafile':'tweets_timeseries', 'output_format':'json'},
'ExtractPartitionedUsersByCoordinateSharingBehavior':{'datafile': 'user_partition_by_location_sharing_behavior',
'output_format':'raw'}
}
<file_sep>'''
Created on Feb 9, 2014
@author: <NAME>
'''
from utils import Utils
import settings
import sys
class DataExtractor:
@classmethod
def extract_data(cls, args):
data_extractors = settings.data_extractors
runner_args, job_args = Utils.process_args(args)
for data_extractor in data_extractors:
Utils.run_mrjob(data_extractor, runner_args, job_args)
def main():
args = sys.argv
DataExtractor.extract_data(args)
if __name__ == '__main__':
main()
<file_sep>'''
Created on Apr 13, 2013
@author: <NAME>
'''
from operator import itemgetter
from region import Region
from extractdata import DataExtractorFactory
from sklearn.cluster import KMeans
from numpy import asarray, empty, float
class UsersClustering:
_dictExpertUsersData = {'aggie':[(1445345,.6678, 45,-63)]}
_dictClusters = {}
_kmeans = None
def __init__(self, dictExpertUsersData):
print 'instantiated'
self._dictExpertUsersData = dictExpertUsersData
'''
Clusters the users based on their locations using the KMeans clustering algorithm
'''
def _clusterExperts(self, expertise):
self._dictClusters.clear()
usersData = self._dictExpertUsersData[expertise]
data = empty((len(usersData), 2))
numClusters = self._dictClusterNum[expertise]#min(4 , len(usersData))
#print numClusters, ' clusters will be generated'
self._kmeans = KMeans(n_clusters=numClusters)
index = 0
for userData in usersData:
data[index] = asarray([userData[2], userData[3]], dtype=float)
index += 1
self._kmeans.fit(data)
labels = self._kmeans.labels_
index = 0
for label in labels:
clusterName = expertise +' Cluster-' + str(label)
clusterUserData = usersData[index]
if clusterName in self._dictClusters:
self._dictClusters[clusterName].append(clusterUserData)
else:
self._dictClusters[clusterName] = [clusterUserData]
index += 1
#print 'Done clustering', len(data), ' points'
'''
Creates regions corresponding to each expert cluster
predicted by the clustering algorithm.
'''
def getExpertRegions(self, expertise):
#print 'Creating regions for ', expertise
self._clusterExperts(expertise)
expertRegions = []
index = 0
for clusterName in self._dictClusters:
expertUsersData = self._dictClusters[clusterName]
region = self._createExpertRegionWithRandomCenters(expertUsersData, expertise, index)
#print 'Created ', region.getName(),' with center', region.getCenter()
expertRegions.append(region)
index += 1
#print 'created ', len(expertRegions) , ' for ', expertise
return expertRegions
'''
Creates a bounding region for a certain expertise based on the
location information in user data.
@param expertUsersData: The expert users' data for which we want to create a bounding
region.
@return: The bounding region corresponding to the expertise.
'''
def _createExpertRegionWithRandomCenters(self, expertUsersData, expertise, index):
#print expertUsersData
maxLatitude = max(expertUsersData, key=itemgetter(2))[2]
minLatiude = min(expertUsersData, key=itemgetter(2))[2]
maxLongitude = max(expertUsersData, key=itemgetter(3))[3]
minLongitude = min(expertUsersData, key=itemgetter(3))[3]
leftTop = (maxLatitude, minLongitude)
rightBottom = (minLatiude, maxLongitude)
expertRegion = Region(leftTop, rightBottom, expertise + ' Region '+ str(index), isParent=True, expertise = expertise)
#print 'Coordinates : minlatitude = ', minLatiude, ', maxLatitude = ', maxLatitude
#print 'minlongitude = ', minLongitude, ', maxlongitude = ', maxLongitude
return expertRegion
def main():
print 'Main'
data = DataExtractorFactory.getDataExtractor('expertmodel', 'data/')
expertsData = data.getAllExpertsData()
clusterer = UsersClustering(expertsData)
clusterer.getExpertRegions('tech')
'''
clusterer.getExpertRegions('rap')
clusterer.getExpertRegions('dog')
clusterer.getExpertRegions('finance')
'''
if __name__ == "__main__":
main()
<file_sep>'''
Created on Dec 25, 2013
@author: <NAME>
'''
from mrjob.job import MRJob
from cjson import decode
from common_functions import Utils
class MRPlacesTypeDistribution(MRJob):
'''
Generates a distribution of places based on the
place_type in a given dataset
generated by dataextractor.TweetParser .
'''
def configure_options(self):
super(MRPlacesTypeDistribution, self).configure_options()
self.add_file_option('--filter_file', help = 'The file containing'
' the uids, to be applied as filter on the data.')
self.add_passthrough_option('--apply_filter', action = 'store_true',
default = False, dest = 'apply_filter')
def load_options(self, args):
super(MRPlacesTypeDistribution, self).load_options(args)
filter_filename = self.options.filter_file
if self.options.apply_filter:
self._uids = Utils.get_filter_uids(filter_filename)
def yield_data(self, data):
if data['p'] != 'N':
yield data['p'], 1
else:
yield 'NotAvailable', 1
def read_data(self, _, line):
data = decode(line)
if self.options.apply_filter:
if data['u'] in self._uids:
return self.yield_data(data)
else:
return self.yield_data(data)
def aggregate_data(self, place_type, count):
yield place_type, sum(count)
def steps(self):
return [self.mr(mapper = self.read_data,
combiner = self.aggregate_data,
reducer = self.aggregate_data)]
def main():
MRPlacesTypeDistribution().run()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Apr 24, 2013
@author: <NAME>
'''
from pprint import pprint
from operator import itemgetter
from backstrom_model import BackStromExpertiseModelGenerator
from extractdata import DataExtractorFactory
from modelstore import modelsDict
from utility import Utility
from settings import Settings
'''
Reuses all of the functionalities provided by the BackstormModel
'''
class BackstromExpertImpactModelGenerator:
_expertDataExtractor = None
_dataDirectory = ''
_expertImpactModels = {}
def __init__(self, dataDirectory, cachedModelsFileName = ''):
self._cachedModelsFileName = cachedModelsFileName
self._dataDirectory = dataDirectory
self._expertDataExtractor = DataExtractorFactory.getDataExtractor('expertmodel', dataDirectory)
def generateModelForExpertise(self, expertise):
self._expertDataExtractor.populateData(self._dataDirectory, 'all')
self._expertImpactModels[expertise] = {}
print '>>>>>>>>>>> Generating models for ', expertise
self._expertDataExtractor.setCurrentExpertise(expertise)
modelGenerator = BackStromExpertiseModelGenerator(self._dataDirectory, self._expertDataExtractor)
modelGenerator.generateModelForAllExpertise()
self._expertImpactModels[expertise] = modelGenerator.getModelsForAllExpertise()
def generateModelForAllExpertise(self):
expertiseList = self._expertDataExtractor.getExpertiseList()
for expertise in expertiseList:
self.generateModelForExpertise(expertise)
def displayModels(self):
print '------- Models Generated ----'
pprint(self._expertImpactModels)
def loadCachedModels(self):
self._expertImpactModels = modelsDict
def getExpertImpactModels(self):
return self._expertImpactModels
class ExpertImpactAPI:
_expertModelsDict = {}
_modelGenerator = None
def __init__(self, dataDirectory, cacheFileName):
self._modelGenerator = BackstromExpertImpactModelGenerator(dataDirectory, cacheFileName)
def getRankedExperts(self, expertise, userLocation):
if len(self._expertModelsDict) == 0:
self._modelGenerator.loadCachedModels()
self._expertModelsDict = self._modelGenerator.getExpertImpactModels()[expertise]
expertImpactList = []
for expert in self._expertModelsDict:
models = self._expertModelsDict[expert]
modelValue = 0
prevModelValue = 0
for model in models:
modelValue = Utility.getModelValue(model, userLocation, True)
modelValue = max(modelValue, prevModelValue)
prevModelValue = modelValue
expertImpactList.append((modelValue, expert))
rankedExpertsData = sorted(expertImpactList, key = itemgetter(0), reverse = True)
rankedExperts = []
print rankedExpertsData
for rankedExpertData in rankedExpertsData:
rankedExperts.append(rankedExpertData[1])
return rankedExperts
def main():
print 'Main'
dataDirectory = 'expertdata/'
cacheFile = 'models.json'
expertAPI = ExpertImpactAPI(dataDirectory, cacheFile)
#print expertAPI.getRankedExperts('travel', (27, -76))
modelGenerator = BackstromExpertImpactModelGenerator(dataDirectory)
modelGenerator.generateModelForExpertise('travel')
if __name__ == "__main__":
main()
<file_sep>'''
Created on Apr 15, 2013
@author: <NAME>
'''
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from pprint import pprint
from backstorm_model import BackStormModelGenerator
class Model():
c = 0.0
alpha = 0.0
latitude = 0.0
longitude = 0.0
def __init__(self):
pass
def output(self):
print (self.c, self.alpha, self.latitude, self.longitude)
class ModelPlot:
@staticmethod
def plot_peak(model, ax, X, Y, finalZ):
distance = 0.0 + pow((X - model.longitude) ** 2 + (Y - model.latitude) ** 2, 0.5)
Z = np.double(model.c * distance ** model.alpha)
if finalZ == None:
finalZ = Z
i = 0
while (i < len(Z)):
j = 0
while (j < len(Z[i])):
if Z[i][j] >= model.c:
Z[i][j] = model.c
if Z[i][j] > finalZ[i][j]:
finalZ[i][j] = Z[i][j]
j = j + 1
i = i + 1
return finalZ
@staticmethod
def plot_multiple_peaks(models, title):
fig = plt.figure()
ax = Axes3D(fig)
latitude_upper_left = 50
latitude_lower_right = 26
longitude_upper_left = -130
longitude_upper_right = -66
step_latitude = 1.0 * (latitude_upper_left - latitude_lower_right) / 100
step_longitude = 1.0 * (longitude_upper_right - longitude_upper_left) / 100
X = np.arange(longitude_upper_left, longitude_upper_right, step_longitude)
Y = np.arange(latitude_lower_right, latitude_upper_left, step_latitude)
X, Y = np.meshgrid(X, Y)
# normalizing Z
finalZ = None
for model in models:
finalZ = ModelPlot.plot_peak(model, ax, X, Y, finalZ)
finalZ = ModelPlot.normalizing_z_matrix(finalZ)
ax.plot_surface(X, Y, finalZ, rstride=1, cstride=1, cmap=cm.jet)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_zlabel('Probability')
plt.title(title)
plt.show()
@staticmethod
def normalizing_z_matrix(Z):
max_value = 0.0
i = 0
while (i < len(Z)):
j = 0
while (j < len(Z[i])):
if Z[i][j] > max_value:
max_value = Z[i][j]
j = j + 1
i = i + 1
finalZ = Z
i = 0
while (i < len(Z)):
j = 0
while (j < len(Z[i])):
finalZ[i][j] = Z[i][j] / max_value
j = j + 1
i = i + 1
return finalZ
def main():
models = []
dataDirectory = 'data/'
modelGenerator = BackStormModelGenerator(dataDirectory)
# dictModellist = modelGenerator.getModelsForAllExpertise()
dictModellist = {'vc': [{'C': 0.10209873434416397,
'alpha': 0.4099257815602122,
'center': (38.00939497727273, -122.86621224166666),
'regionName': 'vc Region 9'}]}
for expertise in dictModellist:
modellist = dictModellist[expertise]
for modelDict in modellist:
model = Model()
model.latitude = modelDict['center'][0]
model.longitude = modelDict['center'][1]
model.c = modelDict['C']
model.alpha = -modelDict['alpha']
models.append(model)
ModelPlot.plot_multiple_peaks(models, expertise)
if __name__ == "__main__":
main()
<file_sep>'''
Created on Feb 12, 2014
@author: <NAME>
'''
jobsettings = {
'UserCoordinatesSharingDistribution' : {'apply_filter': True},
'UserSelectiveCoordinatesHidingDistribution' : {'apply_filter': True},
'UserHomeLocationSharingDistribution' :{},
'PlacesTypeDistribution':{},
'SharingDeviceDistribution':{},
'UserTweetCountDistribution':{'delta' : 1},
'UserGeoTweetCountDistribution':{'delta' : 1},
'TweetDistribution':{},
}
<file_sep>'''
Created on Apr 13, 2013
@author: himanshu
'''
from math import radians, cos, sin, asin, sqrt
class Utility:
'''
Evaluates the user confidence based on the Backstorm model.
'''
@staticmethod
def getModelValue(model, userLocation, isExpert):
C = model['C']
alpha = model['alpha']
center = model['center']
distance = Utility.haversine(center[0],center[1], userLocation[0], userLocation[1])
value = C * pow(distance + 0.9, -alpha)
if isExpert:
return value
else :
return 1 - value
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
@param longitudeCenter: The longitude of the center
@param latitudeCenter: The longitude of the center
@param longitudeUser: The longitude of the user
@param latitudeUser: The longitude of the user
@return: Haversine distance between the user and the center
"""
@staticmethod
def haversine(longitudeCenter, latitudeCenter, longitudeUser, latitudeUser):
# convert decimal degrees to radians
longitudeCenter, latitudeCenter, longitudeUser, latitudeUser = map(radians, [longitudeCenter,
latitudeCenter,
longitudeUser,
latitudeUser])
# haversine formula
diffLongitude = longitudeUser - longitudeCenter
diffLatitude = latitudeUser - latitudeCenter
a = sin(diffLatitude / 2) ** 2 + cos(latitudeCenter) * cos(latitudeUser) * sin(diffLongitude / 2) ** 2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
<file_sep>'''
Created on Mar 30, 2013
@author: <NAME>
'''
from io import open
from json import loads
from os.path import join
from expertsmodels.lib.extractdata import DataExtractorFactory
from expertsmodels.lib.expert_impact_model import ExpertImpactAPI
class ExpertsDataAPI:
_expertDataDirectory = '/home/himanshu/workspace/infolab/localexperts/expertsmodels/lib/expertdata/'
_expertiseDataDirectory = '/home/himanshu/workspace/infolab/localexperts/expertsmodels/lib/expertisedata/'
def __init__(self):
self._expertiseDataExtractor = DataExtractorFactory.getDataExtractor('expertisemodel', self._expertiseDataDirectory)
self._expertDataExtractor = DataExtractorFactory.getDataExtractor('expertmodel', self._expertDataDirectory)
def getExpertiseHeatmapData(self, expertise):
expertsDataList = self._expertiseDataExtractor.getExpertUsersData(expertise)
print 'No of entries : ', len(expertsDataList)
expertsDataListForHeatmap = []
for expertData in expertsDataList:
expertDataDict = {'lat': expertData[2],'lng':expertData[3], 'count':expertData[1]}
expertsDataListForHeatmap.append(expertDataDict)
return expertsDataListForHeatmap
def getExpertHeatmapData(self, expertise, expertId):
print 'Got request for ', expertId, expertise,'------------------'
expertsDataList = self._expertDataExtractor.getExpertUsersData(int(expertId), expertise)
print 'No of entries : ', len(expertsDataList)
expertsDataListForHeatmap = []
for expertData in expertsDataList:
expertDataDict = {'lat': expertData[2],'lng':expertData[3], 'count':expertData[1]}
expertsDataListForHeatmap.append(expertDataDict)
return expertsDataListForHeatmap
class ExpertsSearchAPI:
_dataDirectory = '/home/himanshu/workspace/infolab/localexperts/expertsmodels/lib/expertdata/'
_cacheFile = 'models.json'
_expertImpactAPI = ExpertImpactAPI(_dataDirectory, _cacheFile)
_profileInfoDict = {}
_profileDataFileName = 'user_profiles.json'
def __init__(self):
self._populateProfileData()
def _populateProfileData(self):
filename = join(self._dataDirectory,self._profileDataFileName)
with open(filename, 'r+') as profilesData:
for profileData in profilesData:
profileData = loads(profileData)
description = profileData['description']
username = profileData['screen_name']
userLocation = profileData['location']
imageUrl = 'http://icons.iconarchive.com/icons/deleket/scrap/256/User-icon.png'
userId = profileData['_id']
userInfoDict = {'user_name': username,
'user_description': description,
'profile_image_url':imageUrl,
'user_location':userLocation}
self._profileInfoDict[userId] = userInfoDict
def getExperts(self, query, queryLocation):
print 'Getting experts for ', query
rankedExpertsList = self._expertImpactAPI.getRankedExperts(query ,queryLocation)
rankedUsersDetails = []
for userId in rankedExpertsList:
userProfileDict = self._profileInfoDict[userId]
rankedUsersDetails.append(userProfileDict)
return rankedUsersDetails
def main():
searchAPI = ExpertsSearchAPI()
if __name__ == "__main__":
main()
<file_sep># This file contains the script to read time series generated by the time_series.py
# and then cluster them according to their seasonal trends.
#
# Author: <NAME>
###############################################################################
require(rjson)
# Function used to trimming the quotes from a given string
Trim <- function (x) gsub("^\\s+|\\s+$", "", x)
# Function used for reading timeseries data from the file.
ReadTimeSeriesData <- function(timeSeriesData) {
timeseriesJsonData <- gsub('\"\"','',timeSeriesData)
timeseriesJsonData <- Trim(timeseriesJsonData)
timeseries <- fromJSON(timeseriesJsonData)
timeseries <- as.numeric(unlist(strsplit(timeseries[[1]], ",") ))
return(timeseries)
}
# This function loads the timeseries data in to a dataframe
LoadTimeSeriesData <- function(filename) {
fileConnection <- file(filename, open = "r")
dataLine <- readLines(fileConnection, n = 1, warn = FALSE)
timeseries = ReadTimeSeriesData(dataLine)
timeseriesLength = length(timeseries)
dataFrame <- as.data.frame(matrix(nrow = 0, ncol = timeseriesLength))
while (length(dataLine <- readLines(fileConnection, n = 1, warn = FALSE)) > 0) {
dataFrame = rbind(dataFrame, timeseries)
timeseries = ReadTimeSeriesData(dataLine)
}
close(fileConnection)
return(dataFrame)
}
dataFrame <- LoadTimeSeriesData('/home/himanshu/data/raw_data/users_checkins_timeseries')
print(dataFrame)
library(dtw)
distMatrix <- dist(dataFrame, method='DTW')
print(distMatrix)
hc <- hclust(distMatrix, method='average')
plot(hc, main='')
<file_sep>'''
Created on Jan 24, 2014
@author: <NAME>
'''
import matplotlib.pyplot as P
import matplotlib as mpl
from utils import Utils
from operator import itemgetter
class PlotUserSelectiveCoordinatesHidingDistribution:
def __init__(self, datafile):
self._datafile = datafile
def plot_data(self, pdf_file, image_filename):
data_points = []
total = 0
for data_row in Utils.get_data_vectors(self._datafile, ' '):
bin = int(float(data_row[0]))
data = int(float(data_row[1]))
total += data
data_points.append((bin, data))
bins = []
data = []
for data_point in sorted(data_points, key = itemgetter(0)):
bins.append(data_point[0])
percentage = 100 * data_point[1] / float(total)
data.append(percentage)
P.bar(bins, data, width = 1, color = 'r')
mpl.rcParams['font.size'] = 10.0
P.xlabel('Selectively Non Geotagged tweet percentage')
P.ylabel('Users percentage')
P.savefig(pdf_file, format = 'pdf')
P.savefig(image_filename)
P.clf()
def main():
plotter = PlotUserSelectiveCoordinatesHidingDistribution('/home/himanshu/data/stats/user_selective_coordinate_sharing')
plotter.plot_data('selective_coordinate_sharing', 'selective_coordinate_sharing.png')
if __name__ == '__main__':
main()
<file_sep>'''
Created on Jan 25, 2014
@author: <NAME>
'''
from matplotlib.pyplot import *
from utils import Utils
import random
from operator import itemgetter
import matplotlib as mpl
class PlotSharingDeviceDistribution:
def __init__(self, datafile):
self._datafile = datafile
def plot_data(self, pdf_file, image_filename):
data_dict = {}
for data_row in Utils.get_data_vectors(self._datafile, '|'):
data_dict[data_row[0]] = int(data_row[1])
fig = figure(1, figsize = (6, 6))
ax = axes([0.2, 0.2, 0.6, 0.6])
# The slices will be ordered and plotted counter-clockwise.
data_dict = sorted(data_dict.iteritems(), key = itemgetter(1), reverse = True)
total_tweet_count_original = sum(float(data[1]) for data in data_dict)
data_dict = data_dict[0:5] + data_dict[10:12] + data_dict[6:9] + data_dict[13:15]
total_tweet_count = sum(float(data[1]) for data in data_dict)
application_names = list(data[0] for data in data_dict)
tweet_percentage = 100 * (total_tweet_count / float(total_tweet_count_original))
fracs = [float(data[1]) / total_tweet_count for data in data_dict]
mpl.rcParams['font.size'] = 6.0
pie(fracs, labels = application_names, autopct = '%1.1f%%', shadow = False, startangle = 0)
title('Tweet sources Distribution: Showing top 15 tweet sources which generate ' +
str(tweet_percentage) +
'% of the total tweets', bbox = {'facecolor':'0.8', 'pad':5})
savefig(pdf_file, format = 'pdf')
savefig(image_filename)
clf()
def main():
plotter = PlotSharingDeviceDistribution('/home/himanshu/data/output/sharing_device_distribution')
plotter.plot_data('sample')
if __name__ == '__main__':
main()
<file_sep>'''
Created on Feb 9, 2014
@author: <NAME>
'''
from mrjob.job import MRJob
from common_functions import CoordinatesSharing
from library.file_io import FileIO
from cjson import encode, decode
class MRExtractPartitionedUsersByCoordinateSharingBehavior(MRJob):
'''
Generates a distribution of users based and
coordinates sharing behavior in a given dataset
generated by dataextractor.TweetParser .
'''
def read_data(self, _, line):
data = decode(line)
return CoordinatesSharing.read_data(data)
def aggregate_data(self, uid, data):
return CoordinatesSharing.aggregate_data(uid, data)
def calculate_user_distribution(self, uid, checkins):
index = self.get_index(checkins)
# Here index tells that what percentage of coordinates are
# shared by the user with user id = 'uid'
if index == 0:
yield 'Non_Sharers', int(uid)
elif index > 0 and index < 100:
yield 'Selective_Sharers', int(uid)
else:
yield 'Full_Sharers', int(uid)
def emit_partition(self, category, uids):
yield category, list(uids)
def get_index(self, checkins):
return CoordinatesSharing.get_index(checkins)
def output_writer(self, key, value, output_filename):
print 'Writing data for ', key, ' to ', output_filename + '_' + key
FileIO.writeToFile(encode({'uids':value}), output_filename + '_' + key)
def steps(self):
return [self.mr(mapper = self.read_data,
reducer = self.aggregate_data),
self.mr(mapper = self.calculate_user_distribution,
reducer = self.emit_partition),
]
def main():
MRExtractPartitionedUsersByCoordinateSharingBehavior().run()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Mar 24, 2013
@author: <NAME>
'''
from userdata import UsersData
class Region:
_name = ''
_leftTop = (0, 0)
_rightBottom = (0, 0)
_horizontalSize = 0
_verticalSize = 0
_center = (0,0)
_expertise = ''
# Distinguishes a parent region
_isParent = True
#_parentRegion for a parentRegion will be None
# All the regions which are formed after segmentation cannot be parent Regions
_parentRegion = None
# A row major matrix for the child regions resulting from segmentation
# of the parent region
_childRegions = []
'''
Instantiates the object of the Region class
@param topLeft: The tuple containing the latitude, longitude for the
topleft point of the bounding region in that order.
@param rightBottom:The tuple containing the latitude, longitude for the
rightBottom point of the bounding region in that order.
@param center: The center of the region. If the value is not provided then the
center is calculated to be the geographical center of the region based on
its latitudinal and longitueinal spam.
@param name: Optional argument which sets the name for the region.
@param isParent: Indicates if this is the root region.
'''
def __init__(self, leftTop, rightBottom,center = None,
name = 'New Region',
isParent = True,
expertise = 'Jacks Of All Trades'):
self._isParent = isParent
self._name = name.strip()
self._rightBottom = rightBottom
self._leftTop = leftTop
self._expertise = expertise
self._validateCoordinates()
self._calculateRegionAttributes()
if center is not None:
self._center = center
'''
Perform calculations for region attirbutes like horizontal size ,
vertical size and center of the region.
'''
def _calculateRegionAttributes(self):
# take the difference between longitude
self._horizontalSize = abs(float(self._rightBottom[1] - self._leftTop[1]))
# take the difference between latitude
self._verticalSize = abs(float(self._rightBottom[0] - self._leftTop[0]))
self._center = (self._leftTop[0] - self._verticalSize / 2, self._leftTop[1] + self._horizontalSize / 2)
def getExpertise(self):
return self._expertise
def getLeftTop(self):
return self._leftTop
def getRightBottom(self):
return self._rightBottom
def setExpertise(self, expertise):
self._expertise = expertise
'''
Checks if the given location is bounded by this region.
@param location: The tuple containing the latitude and longitude of the
location in that order.
@return: True if the given location is bounded by this region, False otherwise.
'''
def boundsLocation(self, userData):
try:
#print 'Checking boundsLocation for :', userData
if UsersData.isPartitioned():
#print 'data is partitioned'
# If the users data has been partitioned and each user has a label that
# corresponds to the region it is assigned to
if userData[4] == self._expertise:
#print 'User is an expert'
# If this user is an expert then it will have the label of the region
# to which it belongs to. So we just compare the label to the name of the current
# region
if userData[5] == self._name:
#print 'User belongs to the region ', self._name
return True
else:
#print 'User does not belong to region', self._name
return False
else:
# If this user is not an expert then we only consider its location
# to judge whether it belongs to the region or not
#print 'User is not an expert'
pass
#print 'Checking location'
location = (userData[2], userData[3])
if location[0] >= self._rightBottom[0] and location[0] <= self._leftTop[0] :
if location[1] <= self._rightBottom[1] and location[1] >= self._leftTop[1]:
#print 'Passed!!'
return True
#print 'Failed!!'
except:
print userData
return False
'''
Checks the provided bounding box coordinates makes sense, raises Runtime error
if the coordinates are invalid
'''
def _validateCoordinates(self):
try:
if not (self._leftTop[0] >= self._rightBottom[0] and self._rightBottom[1] >= self._leftTop[1]):
raise RuntimeError('Invalid bounding region !!')
except:
raise RuntimeError('Invalid bounding region !!')
'''
Gets the location of the center.
@return : A tuple containing the latitude and longitude of the
center in that order.
'''
def getCenter(self):
return self._center
'''
Gets the childRegions of the region.
@return : A list of list of horizontal child regions of the region.
'''
def getChildRegions(self):
return self._childRegions
'''
Gets the child region located at the given indices.
@param horizontalIndex: The column index of the child
@param verticalIndex: The row index of the child
'''
def getChildRegion(self, horizontalIndex, verticalIndex):
if len(self._childRegions) == 0:
return None
if horizontalIndex < len(self._childRegions[0]) and verticalIndex < len(self._childRegions):
return self._childRegions[horizontalIndex][verticalIndex]
return None
'''
Gets the parent or the root region for this region.
@return: The parent Region.
'''
def getParent(self):
return self._parentRegion
'''
Checks if this region is a parent.
@return : True if this region is a parent, False otherwise.
'''
def isParent(self):
return self._isParent
'''
Sets the parent of the given region.
@param region: The parent Region.
'''
def setParentRegion(self, region):
self._isParent= False
self._parentRegion = region
'''
Segments this region in to given number of child Regions of given size.
@param numHorizontalSegments: Number of horizontal segments
@param numVerticalSegments: Number of horizontal segments
@param childRegionHorizontalSize : The horizontal size of each child
@param childRegionVerticalSize : The vertical size of each child
'''
def _segment(self, numHorizontalSegments, numVerticalSegments, childRegionHorizontalSize, childRegionVerticalSize):
#print len(self._childRegions), 'is the number of children columns'
self._childRegions = []
#print 'segmenting ', self._name, ' into ', numHorizontalSegments,'x',numVerticalSegments,'segments'
#print 'with horizontal size :',childRegionHorizontalSize,' with vertical size :', childRegionVerticalSize
latitude = self._leftTop[0]
longitude = self._leftTop[1]
# Segment regions and assign each of them with their
# lefttop and rightbottom
for horizontalSegmentCount in range(numHorizontalSegments):
horizontalChildRegions = []
for verticalSegmentCount in range(numVerticalSegments):
childTopLeft = (latitude - verticalSegmentCount * childRegionVerticalSize,
longitude + childRegionHorizontalSize * horizontalSegmentCount)
childRightBottom = (latitude - (verticalSegmentCount + 1) * childRegionVerticalSize,
longitude + childRegionHorizontalSize * (horizontalSegmentCount + 1))
childRegionName = self._name + '\'s Child : '+ str(verticalSegmentCount) + ',' + str(horizontalSegmentCount)
childRegion = Region(childTopLeft, childRightBottom, None ,childRegionName, False, self.getExpertise())
if self._parentRegion == None:
childRegion.setParentRegion(self)
else:
childRegion.setParentRegion(self.getParent())
horizontalChildRegions.append(childRegion)
self._childRegions.append(horizontalChildRegions)
'''
Segments this region in to given number of child Regions.
@param numHorizontalSegments: Number of horizontal segments
@param numVerticalSegments: Number of horizontal segments
'''
def segmentByChildCount(self, numHorizontalSegments, numVerticalSegments):
childRegionHorizontalSize = self._horizontalSize / numHorizontalSegments
childRegionVerticalSize = self._verticalSize / numVerticalSegments
self._segment(numHorizontalSegments, numVerticalSegments, childRegionHorizontalSize, childRegionVerticalSize)
'''
Segments the region into the number of regions closest to the expected size of
regions.
@param expectedChildRegionHorizontalSize : The expected horizontal size of each child
@param expectedChildRegionVerticalSize : The expected vertical size of each child
'''
def segmentByChildSize(self, expectedChildRegionHorizontalSize , expectedChildRegionVerticalSize):
if (expectedChildRegionHorizontalSize > 0 and expectedChildRegionVerticalSize > 0):
numHorizontalSegments = int(round(self._horizontalSize / expectedChildRegionHorizontalSize))
numVerticalSegments = int(round(self._verticalSize / expectedChildRegionVerticalSize))
if numHorizontalSegments == 0 or numVerticalSegments == 0:
self._childRegions = []
self._childRegions.append([self])
return
residualVerticalSize = self._verticalSize - numVerticalSegments * expectedChildRegionVerticalSize
residualHorizontalSize = self._horizontalSize - numHorizontalSegments * expectedChildRegionHorizontalSize
# Calculating the actual size that each child region should have in order to cover the whole region
childRegionVerticalSize = expectedChildRegionVerticalSize + residualVerticalSize / numVerticalSegments
childRegionHorizontalSize = expectedChildRegionHorizontalSize + residualHorizontalSize / numHorizontalSegments
self._segment(numHorizontalSegments, numVerticalSegments, childRegionHorizontalSize, childRegionVerticalSize)
def getName(self):
return self._name
def main():
print 'Testing Region Class'
region = Region((57.93, -116.98), (43.2, -73.15), 'Test Region')
print 'Region _center is ', region.getCenter()
region.segmentByChildSize(5, 8)
Region.addUserData([23,9,85,84,'aggie'])
child = region.getChildRegion(0,0)
child.segmentByChildSize(2,2)
print 'Centres for the regions:'
for children in child.getChildRegions():
for childRegion in children:
print childRegion._name,' center :', childRegion.getCenter(), 'leftTop: ', childRegion._leftTop, 'rightBottom: ', childRegion._rightBottom,'userdata: ', childRegion.getUsersData()
if __name__ == "__main__":
main()
<file_sep>'''
Created on Feb 9, 2014
@author: <NAME>
'''
from math import ceil
from cjson import decode
class Utils:
@classmethod
def get_filter_uids(cls, filter_filename):
with open(filter_filename, 'r') as file:
uids = decode(file.read())
return set(uids['uids'])
@classmethod
def get_mrjob_class_key(cls, mrJobClass):
return mrJobClass.__name__.replace('MR', '')
class SelectiveCoordinateHiding:
@classmethod
def get_index(cls, checkins):
total_tweets = checkins['y'] + checkins['n'] + checkins['g']
selectively_non_geo_tweet_percentage = 100 * (checkins['g'] / float(total_tweets))
index = int(ceil(selectively_non_geo_tweet_percentage))
if index > 100:
index = 100
return index
class CoordinatesSharing:
@classmethod
def get_index(cls, checkins):
total_tweets = checkins['y'] + checkins['n'] + checkins['g']
coordinates_sharing_tweets_percentage = 100 * (checkins['y'] / float(total_tweets))
index = int(ceil(coordinates_sharing_tweets_percentage))
if index > 100:
index = 100
return index
@classmethod
def read_data(cls, data):
if data['c'] != 'N' and data['c'] != [0.0, 0.0]:
yield str(data['u']) , '1-y'
elif data['ge']:
yield str(data['u']) , '1-g'
else:
yield str(data['u']) , '1-n'
@classmethod
def aggregate_data(cls, uid, data):
yes_count = 0
no_count = 0
ge_count = 0
for line in data:
line = line.split('-')
count = int(line[0])
has_coordinates = line[1]
if has_coordinates == 'n':
no_count += count
elif has_coordinates == 'y':
yes_count += count
elif has_coordinates == 'g':
ge_count += count
yield uid, {'y':yes_count, 'n': no_count, 'g':ge_count}
<file_sep>'''
Created on Jan 24, 2014
@author: himanshu
'''
import csv
import argparse
class Utils:
@classmethod
def get_data_vectors(cls, data_file, delimiter):
with open(data_file, 'r') as file:
data_reader = csv.reader(file, delimiter = delimiter)
for row in data_reader:
yield row
<file_sep>'''
Created on Apr 16, 2013
@author: <NAME>
'''
'''
The purpose of this class is to hold the userdata do some operations on them.
'''
from operator import itemgetter
from utility import Utility
class UsersData:
# contains lists containing userid, user confidence, latitude , longitude,
# expertise (True if the user belongs the expertise of this region) in that order
# e.g [77463542,0.98,67.9,-76.9,'aggie']
_usersData = []
_isPartitioned = False
@staticmethod
def isPartitioned():
return UsersData._isPartitioned
'''
For every user belonging to the given expertise the value of confidence is computed
using the multiple centre model and user is assigned to the model giving it the maximum
value of confidence.
@param expertise: The expertise for which the models have been generated.
@param expertModels: The models generated for the given expertise.
'''
@staticmethod
def partitionUsers(expertModels, expertise):
for userData in UsersData._usersData:
pValues = []
for expertModel in expertModels:
userLocation = (userData[2], userData[3])
isExpert = userData[4] == expertise
p = Utility.getModelValue(expertModel, userLocation, isExpert)
pValues.append((p, expertModel['regionName']))
maxPRegion = max(pValues, key = itemgetter(0))[1]
if len(userData) == 5:
userData.append(maxPRegion)
else:
userData[5] = maxPRegion
UsersData._isPartitioned = True
@staticmethod
def addUserData(userData):
UsersData._usersData.append(userData)
@staticmethod
def getUsersData():
return UsersData._usersData
@staticmethod
def clearUsersData():
UsersData._usersData = []
'''
Adds the extracted user data to the expert regions
'''
@staticmethod
def addUserDataToRegions(usersDataForAllExpertise):
# Add all the user data to the region
_usersData = []
print 'Adding all the user data to Region'
for expertise in usersDataForAllExpertise:
for userData in usersDataForAllExpertise[expertise]:
UsersData.addUserData([userData[0], userData[1], userData[2], userData[3], userData[4]])
print 'Added total ', len(UsersData.getUsersData()), ' entries to Region user data'
<file_sep>'''
Created on Apr 18, 2013
@author: himanshu
'''
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import time
def draw_screen_poly( lats, lons, m, color = 'yellow'):
x, y = m( lons, lats )
xy = zip(x,y)
poly = Polygon( xy, facecolor= color, alpha=0.4 )
plt.gca().add_patch(poly)
def plotRegion(expertiseRegions, models):
colors = ['red', 'aqua','blue','green','yellow','magenta','purple', 'grey', 'violet', 'white']
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# lat_ts is the latitude of true scale.
# resolution = 'c' means use crude resolution coastlines.
m = Basemap(projection='merc',llcrnrlon=-129,llcrnrlat=27,urcrnrlon=-60,urcrnrlat=50,
lat_ts=20,resolution='c')
m.drawcoastlines()
m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawstates()
lon = -125.3318
lat = 37.0799
x,y = m(lon, lat)
index = 0
for region in expertiseRegions:
lats = [ region._leftTop[0], region._rightBottom[0], region._rightBottom[0], region._leftTop[0] ]
lons = [ region._leftTop[1], region._leftTop[1], region._rightBottom[1], region._rightBottom[1] ]
draw_screen_poly( lats, lons, m, color = colors[index])
for model in models:
x = model['center'][0]
y = model['center'][1]
m.plot(x, y, 'bo', markersize=10)
m.drawmapboundary(fill_color='aqua')
plt.title("Expert Regions")
plt.savefig('region.png')
plt.clf()
<file_sep># This script decomposes a times series into seasonal, cyclic and residual components.
#
# Author: <NAME>
###############################################################################
<file_sep>'''
Created on Dec 27, 2013
@author: <NAME>
'''
from mrjob.job import MRJob
from cjson import decode
from library.twitter import getDateTimeObjectFromTweetTimestamp
from time import mktime
from operator import itemgetter
from math import ceil
from common_functions import Utils
from settings import jobsettings
class MRExtractTimeSeries(MRJob):
'''
Generates a time series of number of daily checkins by the users in the
data set generated by the TweetsParser.
'''
def load_options(self, args):
super(MRExtractTimeSeries, self).load_options(args)
key = Utils.get_mrjob_class_key(self.__class__)
self._start_timestamp = jobsettings[key]['start_timestamp']
self._end_timestamp = jobsettings[key]['end_timestamp']
self._bucket_width = jobsettings[key]['bucket_width']
def __init__(self, *args, **kwargs):
super(MRExtractTimeSeries, self).__init__(*args, **kwargs)
def read_checkins(self, _, line):
if line != '':
data = decode(line)
# If the tweet is geolocated with valid coordinates
# then we put it in the checkins bucket for the
# corresponding user
if data['c'] != 'N' and data['c'] != [0.0, 0.0]:
timestamp = data['t']
date_time_object = getDateTimeObjectFromTweetTimestamp(timestamp)
timestamp = mktime(date_time_object.timetuple())
tweet_id = data['tid']
checkin = {'tid' : str(tweet_id) , 't' : timestamp}
yield data['u'], checkin
def create_timeseries(self, uid, checkins):
checkins_list = list(checkins)
if len(checkins_list) > 15:
yield uid, checkins_list
def bucket_time_series(self, uid, time_series):
sorted_time_series = sorted(time_series, key = itemgetter('t'))
# Each bucket is for the count of tweets posted by a user in a day.
# The size of each bucket should be specified in seconds
number_of_buckets = ((self._end_timestamp - self._start_timestamp) / self._bucket_width)
if number_of_buckets == 0:
raise Exception("Please check the bucket settings.")
bucketed_time_series = [0] * number_of_buckets
for checkin in sorted_time_series:
time_since_starting_time = checkin['t'] - self._start_timestamp
bucket_index = int(ceil(time_since_starting_time / self._bucket_width)) - 1
if bucket_index < number_of_buckets:
bucketed_time_series[bucket_index] += 1
yield None, {uid:bucketed_time_series}
def steps(self):
return [
self.mr(mapper = self.read_checkins,
reducer = self.create_timeseries),
self.mr(mapper = self.bucket_time_series)
]
def main():
MRExtractTimeSeries().run()
if __name__ == '__main__':
main()
<file_sep>'''
Created on May 26, 2013
@author: himanshu
'''
from math import pow, log
from pprint import pprint
from extractdata import DataExtractorFactory
from utility import Utility
class SimpleProbabilisticExpertModel(object):
'''
This class implements the simple probabilistic expert model.
For example: for user A: a guy in SF lists him as tech expert,
two guys in NYC list him as tech expert, and 1 guy lists him
as a tech expert in Austin. Then the probability for the guy
being a tech expert in SF, NYC, and Austin are 0.25, 0.5, 0.25
respectively.
'''
_dataDirectory = ''
_dataExtractor = None
_Dmin = 16
_alpha = 1.75
_labelerStatsDict = {}
'''
Warning : These regions should not be overlapping otherwise the
whole thing does not make sense
'''
_regions = {
'SF':{'center': (37.7750, -122.4183), 'radius': 20, 'population':825000},
'NYC': {'center': (40.7142, -74.0064), 'radius': 20, 'population':8300000},
'Austin': {'center': (30.2669, -97.7428), 'radius': 20, 'population':842000},
'College Station': {'center': (30.6278, -96.3342), 'radius': 10, 'population':95000},
}
# Contains the names of the expertise which are under consideration
_expertiseList = ['tech', 'travel']
# This dictionary will contain the scores for all the expert user
# based on our calculation.
_expertsScoreDict = {}
def __init__(self, dataDirectory):
'''
Constructor
'''
self._dataDirectory = dataDirectory
self._dataExtractor = DataExtractorFactory.getDataExtractor('expertmodel', dataDirectory)
def _getEffectiveRadius(self, regionName):
return (self._Dmin * log(self._regions[regionName]['population'], 10))
def _getScore(self, userData, regionName):
'''
Calculates the score for an expert given by a user
the score is discounted using the log10(distance)
therefore the user far away from the expertise location
of the expert will be ble to assign a lower score for
that expertise.
'''
userLocation = userData[2], userData[3]
regionCenter = self._regions[regionName]['center']
distance = Utility.haversine(regionCenter[0], regionCenter[1], userLocation[0], userLocation[1])
# This is the equation used for calculating the score for the
# expert.
score = self._getEffectiveRadius(regionName)/ (self._Dmin + distance)
score = pow(score, self._alpha)
return score
def updateScore(self, expertise, expertId, userData):
'''
Updates the score in the score dictionary
'''
for expertRegionName in self._regions:
score = self._getScore(userData, expertRegionName)
self._updateLabelersStats(expertise, expertId, expertRegionName, userData)
if expertise not in self._expertsScoreDict:
self._expertsScoreDict[expertise] = {}
if expertId not in self._expertsScoreDict[expertise]:
self._expertsScoreDict[expertise][expertId] = {}
regionScoreDict = self._expertsScoreDict[expertise][expertId]
if expertRegionName not in regionScoreDict:
regionScoreDict[expertRegionName] = score
else:
regionScoreDict[expertRegionName] += score
def generateDistanceScoreModel(self):
'''
Iterates the userdata and calculates the probability values
for all the experts.
'''
# Get all the user data from the data extractor.
self._dataExtractor.populateData(self._dataDirectory)
allExpertsData = self._dataExtractor.getDataCopy()
# Iterate through the data and calculate the score for
# each expert
for expertise in self._expertiseList:
expertUserData = allExpertsData[expertise]
self._expertsScoreDict[expertise] = {}
for expertId in expertUserData:
for labelingUserData in expertUserData[expertId]:
self.updateScore(expertise, expertId, labelingUserData)
def _updateLabelersStats(self, expertise, expertId, regionName, userData):
'''
Generates the statistics for the labeling users
Calculates that what percentage of the labeling
users lie in a certain city within in a given
radius.
'''
userLocation = userData[2], userData[3]
region = self._regions[regionName]
regionCenter = region['center']
distance = Utility.haversine(regionCenter[0], regionCenter[1], userLocation[0], userLocation[1])
if expertise not in self._labelerStatsDict:
self._labelerStatsDict[expertise] = {}
if expertId not in self._labelerStatsDict[expertise]:
self._labelerStatsDict[expertise][expertId] = {}
for regionName in self._regions:
self._labelerStatsDict[expertise][expertId][regionName] = {}
self._labelerStatsDict[expertise][expertId][regionName]['inside'] = 0
self._labelerStatsDict[expertise][expertId][regionName]['outside'] = 0
if distance < self._getEffectiveRadius(regionName):
self._labelerStatsDict[expertise][expertId][regionName]['inside'] += 1
else:
self._labelerStatsDict[expertise][expertId][regionName]['outside'] += 1
def generateLabelerStatsBasedModel(self):
for expertise in self._labelerStatsDict:
for expertId in self._labelerStatsDict[expertise]:
for regionName in self._labelerStatsDict[expertise][expertId]:
regionStats = self._labelerStatsDict[expertise][expertId][regionName]
insideLabelersCount = regionStats['inside']
outsideLabelersCount = regionStats['outside']
regionStats['regionscore'] = float(insideLabelersCount) / (insideLabelersCount + outsideLabelersCount)
# TODO: Complete it !!
def rankExpertsByDistanceScore(self):
expertRankDict = {}
for expertise in self._expertsScoreDict:
expertRankDict[expertise] = []
for expertId in self._expertsScoreDict[expertise]:
for regionName in self._expertsScoreDict[expertise][expertId]:
score = self._expertsScoreDict[expertise][expertId][regionName]
expertRankDict[expertise].append(expertId, score)
def main():
print 'Main'
dataDirectory = 'expertdata/'
modelGenerator = SimpleProbabilisticExpertModel(dataDirectory)
modelGenerator.generateDistanceScoreModel()
modelGenerator.generateLabelerStatsBasedModel()
pprint(modelGenerator._expertsScoreDict)
pprint(modelGenerator._labelerStatsDict)
if __name__ == "__main__":
main()
<file_sep>'''
Created on Jan 24, 2014
@author: <NAME>
'''
from library.file_io import FileIO
import argparse
import settings
from os.path import join
class Utils:
@classmethod
def process_args(cls, args):
output_directory = ''
if args[4] == '-output_dir':
args.pop(0)
args.pop(3)
output_directory = args.pop(3)
else:
output_directory = settings.stats_data_directory
job_args = {'output_directory' : output_directory}
return args, job_args
@classmethod
def get_plotclass_key(cls, plotclass):
return plotclass.__name__.replace('Plot', '')
@classmethod
def get_mrjob_class_key(cls, mrJobClass):
return mrJobClass.__name__.replace('MR', '')
@classmethod
def parse_plotter_args(cls):
parser = argparse.ArgumentParser('The utility generates plots using the data'
' data generated by the statistics module. The utility requires'
'the path of the data file')
parser.add_argument('-data_directory',
help = 'The path of the data directory',
default = settings.stats_data_directory)
parser.add_argument('-output_directory',
help = 'The path of the output directory',
default = settings.plots_directory)
parser.add_argument('-jobargs')
args = parser.parse_args()
return args
@classmethod
def _write_raw_output(cls, output_filename, key, mr_job, runner):
for line in runner.stream_output():
key, value = mr_job.parse_output_line(line)
if hasattr(mr_job, 'output_writer'):
mr_job.output_writer(key, value, output_filename)
else:
key = str(key)
value = str(value)
FileIO.writeToFile(key + ' ' + value, output_filename)
@classmethod
def _write_json_output(cls, output_filename, key, mr_job, runner):
for line in runner.stream_output():
key, value = mr_job.parse_output_line(line)
if hasattr(mr_job, 'output_writer'):
mr_job.output_writer(key, value, output_filename)
else:
key = str(key)
value = str(value)
FileIO.writeToFile(key + ' ' + value, output_filename)
@classmethod
def _write_output(cls, output_filename, key, mr_job, runner, output_format):
if output_format == 'raw':
cls._write_raw_output(output_filename, key, mr_job, runner)
elif output_format == 'json':
cls._write_json_output(output_filename, key, mr_job, runner)
@classmethod
def run_mrjob(cls, mr_job_class, runner_args, job_args):
'''
Runs the MapReduce job provided as 'mr_job_class'
with given input files list and the runner arguments
and writes the output to the provided output file.
'''
key = (Utils.get_mrjob_class_key(mr_job_class))
output_filename = settings.jobsettings[key]['datafile']
# The full path of the output file
output_filename = join(job_args['output_directory'], output_filename)
# default output format is raw
output_format = 'raw'
if 'output_format' in settings.jobsettings[key]:
# If the output format is specified in the settings then use it.
output_format = settings.jobsettings[key]['output_format']
mr_job = mr_job_class(args = runner_args)
with mr_job.make_runner() as runner:
runner.run()
print 'Writing data for ', mr_job_class.__name__, ' to ', output_filename
cls._write_output(output_filename, key, mr_job, runner, output_format)
<file_sep>'''
Created on Feb 1, 2014
@author: <NAME>
'''
from mrjob.job import MRJob
from common_functions import SelectiveCoordinateHiding, CoordinatesSharing, Utils
from settings import jobsettings
from cjson import decode
class MRUserSelectiveCoordinatesHidingDistribution(MRJob):
'''
Generates a distribution of users based and
coordinates sharing behavior in a given dataset
generated by dataextractor.TweetParser .
'''
def configure_options(self):
super(MRUserSelectiveCoordinatesHidingDistribution, self).configure_options()
self.add_file_option('--filter_file', help = 'The file containing'
' the uids, to be applied as filter on the data.')
self.add_passthrough_option('--apply_filter', action = 'store_true',
default = False, dest = 'apply_filter')
def load_options(self, args):
super(MRUserSelectiveCoordinatesHidingDistribution, self).load_options(args)
filter_filename = self.options.filter_file
if self.options.apply_filter:
self._uids = Utils.get_filter_uids(filter_filename)
def read_data(self, _, line):
data = decode(line)
if self.options.apply_filter:
if data['u'] in self._uids:
return CoordinatesSharing.read_data(data)
else:
return CoordinatesSharing.read_data(data)
def aggregate_data(self, uid, data):
return CoordinatesSharing.aggregate_data(uid, data)
def calculate_user_distribution(self, uid, checkins):
index = self.get_index(checkins)
yield index, 1
def emit_distribution(self, index, count):
yield index, sum(count)
def get_index(self, checkins):
return SelectiveCoordinateHiding.get_index(checkins)
def steps(self):
# Here we use all the methods from the base class
return [self.mr(mapper = self.read_data,
reducer = self.aggregate_data),
self.mr(mapper = self.calculate_user_distribution,
reducer = self.emit_distribution),
]
def main():
MRUserSelectiveCoordinatesHidingDistribution.run()
if __name__ == '__main__':
main()
<file_sep>'''
Created on Jan 14, 2014
@author: <NAME>
'''
from utils import Utils
import settings
import sys
class StatisticsGenerator:
@classmethod
def generate_stats(cls, args):
runner_args, job_args = Utils.process_args(args)
stats_generators = settings.stats_generators
for stat_generator in stats_generators:
Utils.run_mrjob(stat_generator, runner_args, job_args)
def main():
args = sys.argv
StatisticsGenerator.generate_stats(args)
if __name__ == '__main__':
main()
<file_sep>'''
Created on Mar 24, 2013
@author: <NAME>
'''
from copy import copy
from collections import defaultdict, OrderedDict
from json import loads
from operator import itemgetter
from os import listdir
from os.path import isfile, join, dirname, exists
from pickle import load, dump
from pprint import pprint
from stemming import porter2
from copy import deepcopy
from settings import Settings
'''
Factory for data extractors.
'''
class DataExtractorFactory(object):
@staticmethod
def getDataExtractor(extractorType, dataDirectory):
##############################################################################################
'''
This is a helper class used by the data extractor classes.
'''
class CommonUtils:
'''
Generates the file name from the expertise
It assumes a pattern in the filenames
@param expertise: The expertise for which we want to generate the filename
@return: The filename corresponding to the expertise
'''
@staticmethod
def getFileNameFromExpertise(dataDirectory, expertise):
filename = Settings.dataFileNamePartOne + expertise + Settings.dataFileNamePartTwo
return join(dataDirectory, filename)
'''
Extracts the expertise from a given filename
@return: The expertise corresponding to the filename
'''
@staticmethod
def extractExpertise(filename):
filename = filename.replace(dirname(filename) + '/', '')
filename = filename.replace(Settings.dataFileNamePartOne, '')
expertise = filename.replace(Settings.dataFileNamePartTwo, '')
return expertise
'''
Checks if a location belongs to the US region.
@param userData: The user data for which we want to test whether it lies in US
@return: True if the user lies in the US, False otherwise.
'''
@staticmethod
def isFilterable(userData):
for filterCoordinates in Settings.filterList:
rightBottomCoordinates = filterCoordinates['rightBottomCoordinates']
leftTopCoordinates = filterCoordinates['leftTopCoordinates']
if userData[2] >= rightBottomCoordinates[0] and userData[2] <= leftTopCoordinates[0]:
if userData[3] <= rightBottomCoordinates[1] and userData[3] >= leftTopCoordinates[1]:
return True
return False
'''
Data extractor for generating models for different expertise topics.
'''
class ExpertiseModelDataExtractor:
# { expertise :[( userId, confidence, latitude, longitude),(..)..]}
_expertUsersData = {'tech' : [[23423523, .98763, -98.466 , 97.577]]}
_dataDirectory = ''
_dictRegionUserDistribution = {}
'''
Instantiates the object for DataExtractor
@param dataDirectory: The directory in which the data files are residing
'''
def __init__(self, dataDirectory):
self._expertUsersData.clear()
self._dataDirectory = dataDirectory
# filters the user data for United States only
'''
Initializes the dictRegionUserDistribution dictionary mainly used for
debugging purposes.
'''
def _initializeRegionDistributionDict(self, expertise):
dictRegionUserDistribution = {}
for filterCoordinates in Settings.filterList:
region = filterCoordinates['region']
dictRegionUserDistribution[region] = 0
self._dictRegionUserDistribution[expertise] = dictRegionUserDistribution
'''
Checks if a location belongs to the US region.
@param userData: The user data for which we want to test whether it lies in US
@return: True if the user lies in the US, False otherwise.
'''
def _isFilterable(self, userData):
for filterCoordinates in Settings.filterList:
rightBottomCoordinates = filterCoordinates['rightBottomCoordinates']
leftTopCoordinates = filterCoordinates['leftTopCoordinates']
region = filterCoordinates['region']
if userData[2] >= rightBottomCoordinates[0] and userData[2] <= leftTopCoordinates[0]:
if userData[3] <= rightBottomCoordinates[1] and userData[3] >= leftTopCoordinates[1]:
self._dictRegionUserDistribution[userData[4]][region] += 1
return True
return False
'''
Populates data for a given expertise from the data files.
@param dataDirectory: the directory in which the data files reside
@param expertise: the expertise for which we want to populate the data if expertise = "all"
then the data will be populated for all the possible expertise values
'''
def populateData(self, dataDirectory, expertise='all'):
if expertise == 'all':
filenames = []
# getting the filenames of all the files with the user expertise geographical data
for f in listdir(dataDirectory):
if isfile(join(dataDirectory, f)) and '.txt' in join(dataDirectory, f):
filenames.append(join(dataDirectory, f))
# extracting the data from each file corresponding to an expertise
for filename in filenames:
self._populateDataFromFile(filename)
else :
self._populateDataForExpertise(expertise)
'''
Populates the data for a given expertise
@param expertise: the expertise for which we want to populate the data if expertise = "all"
then the data will be populated for all the possible expertise values
'''
def _populateDataForExpertise(self, expertise):
filename = CommonUtils.getFileNameFromExpertise(self._dataDirectory, expertise)
self._populateDataFromFile(filename)
'''
Populates the data from file
@param filename: The filename from which the data is to be extracted
'''
def _populateDataFromFile(self, filename):
# extracting the expertise from filename
expertise = CommonUtils.extractExpertise(filename)
self._initializeRegionDistributionDict(expertise)
expertsDataList = []
count = 0
with open(filename) as expertsData:
for expertData in expertsData:
if count == Settings.maxExperts:
break
rawData = expertData.split('\t')
userId = rawData[0].strip()
expertRank = rawData[1].strip()
latitude = rawData[2].strip()
longitude = rawData[3].strip()
userData = [int(userId), float(expertRank), float(latitude), float(longitude), expertise]
# We restrict our study to United States only
if self._isFilterable(userData):
expertsDataList.append(userData)
count += 1
if len(expertsDataList) > 0:
self._expertUsersData[expertise] = expertsDataList
#print 'The region distribution of the points for ', expertise , ' is :', self._dictRegionUserDistribution[expertise]
'''
Displays the extracted data
'''
def displayData(self, expertise):
print '------------------'
print self._expertUsersData[expertise]
'''
Gets the expertusers data
@param expertise: The expertise for which the usersdata is to be returned
@return: userdata corresponding to the given expertise
'''
def getExpertUsersData(self, expertise):
if expertise not in self._expertUsersData:
self.populateData(self._dataDirectory, expertise)
return self._expertUsersData[expertise]
return self._expertUsersData[expertise]
'''
Gets all the expertusers data
@return: The dictionary containing usersdata for all the expertise
'''
def getAllExpertsData(self):
if len(self._expertUsersData) == 0:
self.populateData(self._dataDirectory, expertise='all')
return self._expertUsersData
##############################################################################################
'''
Data extractor for generating models for individual experts.
'''
class ExpertModelDataExtractor:
_dataDirectory = ''
_dictRegionUserDistribution = {}
_userExpertiseDict = defaultdict()
_dictionaryDumpFileName = 'userDataDict'
_currentExpertise = ''
'''
Instantiates the object for DataExtractor
@param dataDirectory: The directory in which the data files are residing
'''
def __init__(self, dataDirectory):
self._dataDirectory = dataDirectory
def getExpertIdsList(self, expertise):
return self._userExpertiseDict[expertise].keys()
def getExpertiseList(self):
return self._userExpertiseDict.keys()
def setCurrentExpertise(self, expertise):
self._currentExpertise = expertise
def _pruneData(self):
print 'Pruning the data set'
for expertise in self.getExpertiseList():
for expertUserId in self.getExpertIdsList(expertise):
if len(self._userExpertiseDict[expertise][expertUserId]) <= 20:
self._userExpertiseDict[expertise].pop(expertUserId)
if len(self._userExpertiseDict[expertise]) == 0:
self._userExpertiseDict.pop(expertise)
def _filterTopExperts(self):
tempDict = defaultdict()
for expertise in self._userExpertiseDict:
sortedExpertIds = self._getSortedExperts(expertise)[:Settings.topKExpertCount]
tempDict[expertise] = OrderedDict()
for expertId in sortedExpertIds:
tempDict[expertise][expertId] = self._userExpertiseDict[expertise][expertId]
self._userExpertiseDict = tempDict
'''
Populates the expertise from filename
@param filename: The filename from which the expertise is to be extracted
'''
def _populateExpertiseFromFile(self, filename):
'''
FIXME : This is a really stupid way of extracting the expertise
under consideration
'''
# extracting the expertise from filename
expertise = CommonUtils.extractExpertise(filename)
self._userExpertiseDict[expertise] = defaultdict()
'''
Populates data for a given expertise from the data files.
@param dataDirectory: the directory in which the data files reside
@param expertise: the expertise for which we want to populate the data if expertise = "all"
then the data will be populated for all the possible expertise values
'''
def _populateExpertUserIds(self, dataDirectory, expertise='all'):
if expertise == 'all':
filenames = []
# getting the filenames of all the files with the user expertise geographical data
for f in listdir(dataDirectory):
if isfile(join(dataDirectory, f)) and '.txt' in join(dataDirectory, f):
filenames.append(join(dataDirectory, f))
# extracting the data from each file corresponding to an expertise
for filename in filenames:
self._populateExpertiseFromFile(filename)
else :
self._userExpertiseDict[expertise] = defaultdict()
'''
Populates data for a given expertise from the data files.
@param dataDirectory: the directory in which the data files reside
@param expertise: the expertise for which we want to populate the data if expertise = "all"
then the data will be populated for all the possible expertise values
'''
def populateData(self, dataDirectory, expertise = None):
dumpFile = join(dataDirectory, self._dictionaryDumpFileName)
if exists(dumpFile):
self._userExpertiseDict = load(open(dumpFile,'rb'))
self._filterTopExperts()
return
self._populateExpertUserIds(dataDirectory, expertise)
print self._userExpertiseDict.keys(), ' are the expertises'
self._populateUserDataFromFile()
self._pruneData()
dump(self._userExpertiseDict, open(dumpFile, 'wb'))
'''
Populates the data from file
@param filename: The filename from which the data is to be extracted
'''
def _populateUserDataFromFile(self):
filename = join(self._dataDirectory, Settings.userDataFileName)
with open(filename) as expertsData:
for expertData in expertsData:
jsonData = loads(expertData)
userId = jsonData['list_creator_id']
expertRank = 1
latitude = jsonData['list_creator_lat']
longitude = jsonData['list_creator_lng']
expertUserId = jsonData['user_id']
listName = jsonData['list_name'].strip()
expertise = porter2.stem(listName)
#print expertise , ' is the expertise'
if expertise in self._userExpertiseDict:
# We restrict our study to restricted regions defined by filters in Settings.py
userData = [int(userId), float(expertRank), float(latitude), float(longitude), expertUserId]
if CommonUtils.isFilterable(userData):
if expertUserId in self._userExpertiseDict[expertise]:
self._userExpertiseDict[expertise][expertUserId].append(userData)
else:
self._userExpertiseDict[expertise][expertUserId] = [userData]
'''
Gets the expertusers data
@param expertise: The expertise for which the usersdata is to be returned
@return: userdata corresponding to the given expertise
'''
def getExpertUsersData(self, expertUserId, expertise = ''):
if expertise == '':
expertise = self._currentExpertise
if expertise not in self._userExpertiseDict:
self.populateData(self._dataDirectory, expertise)
def getDataCopy(self):
return deepcopy(self._userExpertiseDict)
'''
Gets the expertusers data
@param expertise: The expertise for which the usersdata is to be returned
@return: userdata corresponding to the given expertise
'''
def getAllExpertsData(self, expertise = ''):
if expertise == '':
expertise = self._currentExpertise
if expertise in self._userExpertiseDict:
dictUserData = {}
for expertUserId in self._userExpertiseDict[expertise]:
usersData = self._userExpertiseDict[expertise][expertUserId]
dictUserData[expertUserId] = [userData for userData in usersData]
return dictUserData
def _getSortedExperts(self, expertise):
sortedExperts = []
for expertUserId in self._userExpertiseDict[expertise]:
userList = self._userExpertiseDict[expertise][expertUserId]
numberOfUsers = len(userList)
sortedExperts.append((expertUserId, numberOfUsers))
sortedExperts = sorted(sortedExperts, key=itemgetter(1), reverse=True)
sortedExperts = [expertInfo[0] for expertInfo in sortedExperts]
return sortedExperts
'''
Displays the extracted data
'''
def displayData(self):
for expertise in self._userExpertiseDict:
print '-----', expertise, '------'
for expertId in self._userExpertiseDict[expertise]:
print expertId,' has ', len(self._userExpertiseDict[expertise][expertId]), ' users'
#################################################################################################################
if extractorType == 'expertisemodel':
return ExpertiseModelDataExtractor(dataDirectory)
elif extractorType == 'expertmodel':
return ExpertModelDataExtractor(dataDirectory)
else:
raise RuntimeError("No suitable extractor found for " + type + ' type')
def main():
print 'Main'
dataDirectory = 'expertdata/'
dataExtractor = DataExtractorFactory.getDataExtractor('expertmodel', dataDirectory)
dataExtractor.populateData(dataDirectory, 'all')
print dataExtractor.displayData()
if __name__ == "__main__":
main()
<file_sep>sudo rm /tmp/session* -v;
sudo python manage.py runserver 8081;
|
fcd51666f037a185f212f4bcf2613930001d7ae7
|
[
"JavaScript",
"Python",
"R",
"Shell"
] | 42
|
Python
|
hbarthwal/infolab
|
312687947487a31f4b9837bcbff549163221b8b1
|
56d499e6b1edca639bba5b1a6e165d0e87bf4978
|
refs/heads/master
|
<repo_name>luizlab/iBus<file_sep>/app.js
var express = require('express');
var app = express();
var db_string = 'mongodb://127.0.0.1/screencast-restful-master';
var mongoose = require('mongoose').connect(db_string);
var db = mongoose.connection;
var User;
db.on('error', console.error.bind(console, 'Erro ao conectar no banco'));
db.once('open', function() {
var userSchema = mongoose.Schema({
fullname: String,
email: String,
password: String,
credits: Number,
created_at: Date
});
User = mongoose.model('User',userSchema);
});
app.listen(5000);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Set config CORS (habilita o CORS no servidor)
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Metodos GET POST DELETE PUT
app.get('/', function(req, res) {
res.end('Servidor ON!');
});
app.get('/users', function(req, res) {
User.find({}, function(error, users) {
if(error) {
res.json({error: 'Não foi possivel retornar os usuários'});
} else {
res.json(users);
}
});
});
app.get('/users/:id/:password', function(req, res) {
var id = req.params.id;
var password = req.params.password;
User.findById(id, function(error, user) {
try {
if (error) {
res.json({error: 'Não foi possivel retornar o usuário'});
} else {
if (password == user.password) {
res.json(user);
} else {
res.json({error: 'Erro de autenticação'});
}
}
}
catch(err) {
res.json({error: err});
}
});
});
// ** Criar um novo usuário **//
app.post('/users', function(req, res) {
var fullname = req.body.fullname;
var email = req.body.email;
var password = <PASSWORD>;
var credits = req.body.credits;
/* SHA1 da senha */
//var sha1 = require('sha1');
try {
new User({
'fullname': fullname,
'email': email,
'password': <PASSWORD>, //sha1(password),
'credits': credits,
'created_at': new Date()
}).save(function(error, user) {
if (error) {
res.json({error: 'Não foi possivel salvar o usuário'});
} else {
res.json(user);
}
});
} catch (err) {
res.json({error: err});
}
});
// ** Alterar dados do usuário **//
app.put('/users', function(req, res) {
var id = req.body.id;
var fullname = req.body.fullname;
var email = req.body.email;
var password = <PASSWORD>;
var credits = req.body.credits;
/* SHA1 da senha */
//var sha1 = require('sha1');
User.findById(id, function(error, user) {
try {
if (error) {
res.json({error: 'Usuário não encontrado'})
} else {
//if (sha1(password) == user.password) {
if (password == user.password) {
if(fullname) {
user.fullname = fullname;
}
if(email) {
user.email = email;
}
if(password) {
user.password = <PASSWORD>;
}
if(credits) {
user.credits = credits;
}
user.save(function(error, user) {
if (error) {
res.json({error: 'Não foi possivel salvar o usuário'});
} else {
res.json(user);
}
});
} else {
res.json({error: 'Erro de autenticação'})
}
}
} catch (err) {
res.json({error: err});
}
});
});
// ** Validação do ticket **//
app.put('/users/credits', function(req, res) {
var id = req.body.id;
var password = req.body.password;
var dateQCode = req.body.created_at;
User.findById(id, function(error, user) {
try {
if (error) {
res.json({error: 'Usuário não encontrado'})
} else {
if (password == user.password) {
var current_date = new Date(); //user.created_at;
var diffDate = Math.abs((new Date(current_date) - new Date(dateQCode))/60000);
//res.json({'data at': current_date, 'data_qr': dateQCode, 'diff': diffDate})
if (diffDate < 5)
{
var credits = user.credits;
var numCredits = parseInt(credits);
if (numCredits > 0) {
numCredits = numCredits - 1;
user.credits = numCredits.toString();
user.created_at = current_date;
user.save(function(error, user) {
if (error) {
res.json({error: 'Não foi possivel salvar o usuário'});
} else {
res.json(user);
}
});
} else {
res.json({error: 'Saldo insuficiente - Saldo: 0'})
}
} else {
res.json({error: 'Este crédito expirou!'})
}
} else {
res.json({error: 'Erro de autenticação'})
}
}
} catch (err) {
res.json({error: err});
}
});
});
app.delete('/users/:id', function(req, res) {
var id = req.params.id;
User.findById(id, function(error, user) {
try {
if (error) {
res.json({error: 'Não foi possivel retornar o usuário'});
} else {
user.remove(function(error) {
if (!error) {
res.json({response: 'Usuário excluido com sucesso'});
}
});
}
}
catch(err) {
res.json({response: 'Exceção - ' + err});
}
});
});
|
f0c43a5671fe7767bae5fc35b60ee40f70c673d7
|
[
"JavaScript"
] | 1
|
JavaScript
|
luizlab/iBus
|
da7c280123ffa3a005763e3e404c93c3f1743fab
|
42d597dd9ed4d19928200f94ed9e1582736aec03
|
refs/heads/master
|
<file_sep>package com.kodilla.calculator;
public class Calculator {
public static int addAToB(int a, int b) {
return a+b;
}
public static int substractAFromB(int a, int b) {
return a-b;
}
public static void main(String[] args) {
addAToB(5, 3);
System.out.println(addAToB(5, 3));
}
}
|
a0c273dd3c52d4f59cef31e8c1ae72836bfe0893
|
[
"Java"
] | 1
|
Java
|
Anka89/Calculator
|
b50f81185dc07d02b490c31bc7f4d5d16caa280d
|
84327630dad90ce65fad0c5f1d9ee41569e039a3
|
refs/heads/master
|
<repo_name>rntk/http_mystem<file_sep>/http_mystem.go
package http_mystem
import (
"fmt"
"net/http"
"os"
"os/exec"
"io"
"encoding/json"
"log"
//"time"
"strings"
//"math/rand"
"regexp"
"runtime"
)
var HEADER_CONTENT_TYPES map[string]string = map[string]string{
"json": "javascript/json;charset=utf-8",
"text": "text/plain;charset=utf-8",
"xml": "text/xml;charset=utf-8",
}
var IGNORE_OPTIONS map[string]bool = map[string]bool{
"-e": true,
"-c": true,
"-d": true,
}
const DEFAULT_FORMAT string = "text"
type Config struct {
Host string
Port int
Reg_filter string
Mystem_path string
Mystem_options []string
Mystem_workers int
Mystem_answer_size int
Channel_buffer int
Max_word_length int
Max_words int
format string
is_d bool
}
type Answer struct {
data string
err error
}
type Data struct {
word string
channel chan Answer
}
var for_process chan Data
var reg_filter *regexp.Regexp
var config Config
func ProcessMystemOptions(in_opts []string) (out_opts []string, format string, err error) {
var opts_arr []string
var approved bool = false
var exists bool = false
var n_exists = false
for _, opt := range in_opts {
approved = false
opt = strings.TrimSpace(opt)
opt = strings.ToLower(opt)
if strings.Index(opt, " ") == -1 {
opts_arr = make([]string, 1)
opts_arr[0] = opt
if !bool(IGNORE_OPTIONS[opt]) {
approved = true
}
if (!n_exists) && (opt == "-n") {
n_exists = true
}
} else {
opts_arr = make([]string, 2)
opts_arr = strings.Split(opt, " ")
if opts_arr[0] == "--format" {
_, exists = HEADER_CONTENT_TYPES[opts_arr[1]]
if exists {
format = opts_arr[1]
} else {
format = DEFAULT_FORMAT
opts_arr[1] = format
log.Printf("Mystem option '%v' was replaced by default value. Because contain error", opt)
}
approved = true
} else if !bool(IGNORE_OPTIONS[opts_arr[0]]) {
approved = true
}
}
if approved {
out_opts = append(out_opts, opts_arr...)
} else {
log.Printf("Mystem option '%v' was ignored or replaced by default value. Because wrong or unnecessary", opt)
}
}
if !n_exists {
out_opts = append(out_opts, "-n")
log.Print("Added mystem option '-n'. It need for normal work.\n")
}
if format == "" {
format = DEFAULT_FORMAT
}
return out_opts, format, err
}
func loadConfig() (cfg Config, err error) {
var f_name string = "http_mystem.json"
if (len(os.Args) > 1) {
f_name = os.Args[1]
}
file, err := os.Open(f_name)
defer file.Close()
if err == nil {
f_stat, _ := file.Stat()
raw_json := make([]byte, f_stat.Size())
_, err = file.Read(raw_json)
if err == nil {
err = json.Unmarshal(raw_json, &cfg)
if err == nil {
cfg.Mystem_options, cfg.format, err = ProcessMystemOptions(cfg.Mystem_options)
//cfg.Mystem_answer_size = cfg.Max_word_length * 500
}
}
}
return cfg, err
}
func writeStringToPipe(for_write string, pipe io.WriteCloser) (n int, err error) {
defer func() {
result := recover()
if result != nil {
log.Fatalf("Recover say: %v", result)
}
}()
n, err = pipe.Write([]byte(for_write + "\n"))
if err != nil {
log.Panicf("Can't send word to mystem: %v", err)
}
return n, err
}
func readStringFromPipe(for_read *string, pipe io.ReadCloser) (n int, err error) {
defer func() {
result := recover()
if result != nil {
log.Fatalf("Recover say: %v", result)
}
}()
buf := make([]byte, config.Mystem_answer_size)
n, err = pipe.Read(buf)
if err == nil {
*for_read = strings.TrimSpace(string(buf[:n]))
} else {
log.Panicf("Can't send word to mystem: %v", err)
}
return n, err
}
func readXMLTrash(number int, pipe io.ReadCloser) {
var data string = ""
var err error
for i := 0; i < number; i++ {
for data == "" {
_, err = readStringFromPipe(&data, pipe)
if err != nil {
log.Fatalf("Can't start: %v", err)
}
}
data = ""
}
}
func workerMystem(for_process chan Data, mystem_path string) {
//name := rand.Int()
//log.Print("Mystem started ", name)
mystem := exec.Command(mystem_path, config.Mystem_options...)
mystem_writer, err_w := mystem.StdinPipe()
mystem_reader, err_r := mystem.StdoutPipe()
err := mystem.Start()
if (err_w != nil) || (err_r != nil) {
log.Fatalf("Can't start: \n%v\n%v", err_w, err_r)
}
if err != nil {
log.Fatalf("Can't start: %v", err)
} else {
var data Data
var answer Answer
if config.format == "xml" {
readXMLTrash(2, mystem_reader)
_, err = writeStringToPipe("тест", mystem_writer)
if err != nil {
panic("")
}
readXMLTrash(2, mystem_reader)
} else {
_, err = writeStringToPipe("тест", mystem_writer)
if err != nil {
panic("")
}
_, err = readStringFromPipe(&answer.data, mystem_reader)
if err != nil {
panic("")
}
}
for {
data = <- for_process
_, err = writeStringToPipe(data.word, mystem_writer)
answer.err = err
if config.format != "xml" {
_, err = readStringFromPipe(&answer.data, mystem_reader)
if err != nil {
answer.err = err
break
}
} else {
for answer.data == "" {
_, err = readStringFromPipe(&answer.data, mystem_reader)
if err != nil {
answer.err = err
break
}
}
}
data.channel <- answer
answer.data = ""
answer.err = nil
}
}
}
func checkInput(req *http.Request, words *[]string, ) (code int) {
var words_count int = len(req.Form["words[]"])
if words_count == 0 {
code = http.StatusNotAcceptable
} else if words_count > int(config.Max_words) {
code = http.StatusRequestEntityTooLarge
} else {
var w string = ""
for _, word := range req.Form["words[]"] {
w = strings.TrimSpace(word)
if len(w) > int(config.Max_word_length) {
w = word[:int(config.Max_word_length)]
}
if w != "" {
*words = append(*words, w)
}
}
}
return code
}
func processWords(resp http.ResponseWriter, req *http.Request) {
var data Data
var answer Answer
var answers []string
var request_answer string = ""
req.ParseForm()
var words []string
var tmp_answer string = ""
status_code := checkInput(req, &words)
var words_count int = len(words)
resp.Header().Set("Content-Type", HEADER_CONTENT_TYPES[config.format])
//resp.Header().Set("Content-Type", "text/plain;charset=utf-8")
if words_count > 0 {
var err error
var local_channel chan Answer = make(chan Answer, words_count)
data.channel = local_channel
var start int = 0
for _, word := range words {
err = nil
if reg_filter.MatchString(word) {
data.word = word
for_process <- data
} else {
start++
switch config.format {
case "json": {
tmp_answer = fmt.Sprintf(`{"analysis":[], "text":"%v"}`, word)
}
case "xml": {
tmp_answer = "<w>" + word + "</w>"
}
case "text": {
tmp_answer = word
}
}
answers = append(answers, tmp_answer)
}
}
for i := start; i < words_count; i++ {
answer = <- local_channel
if answer.err != nil {
err = answer.err
}
answers = append(answers, answer.data)
}
if err == nil {
switch config.format {
case "json": {
request_answer = "[" + strings.Join(answers, ",") + "]"
}
case "xml": {
request_answer = `<?xml version="1.0" encoding="utf-8"?><html><body><se>` + strings.Join(answers, "\n") + "</se></body></html>"
}
case "text": {
request_answer = strings.Join(answers, "\n")
}
}
} else {
//request_answer = fmt.Sprintf(`{"status": %v, "reason": "%v"}`, status_code, http.StatusText(http.StatusInternalServerError)
resp.WriteHeader(http.StatusInternalServerError)
}
close(local_channel)
} else {
//request_answer = fmt.Sprintf(`{"status": %v, "reason": "%v"}`, status_code, http.StatusText(status_code))
resp.WriteHeader(status_code)
}
resp.Write([]byte(request_answer))
}
func main() {
var err error = nil
config, err = loadConfig()
if err != nil {
log.Fatalf("Can't load config: %v", err)
} else {
reg_filter, err = regexp.Compile(config.Reg_filter)
if err != nil {
log.Fatalf("Can`t compile regular expression: %v", err)
}
_, err = os.Open(config.Mystem_path)
if err != nil {
log.Fatal("Can't find mystem: %v", err)
}
var i int
if config.Channel_buffer > 0 {
for_process = make(chan Data, int(config.Channel_buffer))
} else {
for_process = make(chan Data)
}
log.Print("Config load successful")
if config.Mystem_workers == 0 {
var num_cpu int = runtime.NumCPU()
runtime.GOMAXPROCS(num_cpu)
config.Mystem_workers = num_cpu
log.Printf("Found %[1]v cores of CPU. Number of workers will be %[1]v", num_cpu)
}
for i = 0; i < int(config.Mystem_workers); i++ {
go workerMystem(for_process, config.Mystem_path)
}
http.HandleFunc("/", processWords)
log.Printf("Server start on: %v:%v", config.Host, config.Port)
err = http.ListenAndServe(fmt.Sprintf("%v:%v", config.Host, config.Port), nil)
if err != nil {
log.Fatalf("Can't start http server: %v", err)
}
}
}<file_sep>/README.md
# http_mystem
HTTP сервер вокруг программы Mystem от Яндекса (https://tech.yandex.ru/mystem/). Этот сервер был написан в качестве практики при изучении языка GO.
##Как это запустить
1. Скопилировать программу: **go build http_mystem.go**
2. Скачать [mystem](https://tech.yandex.ru/mystem/)
3. Скопировать/переименовать файл **http_mystem.json.example** в **http_mystem.json** и установить необходимые наcтройки
4. Запустить программу: **./http_mystem** . Путь к файлу с настройками можно указать в качестве первого параметра, при запуске сервера, например: **./http_mystem /user/configs/http_mystem.json** . Если путь не указан, будет ипользован http_mystem.json из текущего каталога.
##Параметры конфигурационного файла
**host** - адрес интерфейса, на котором будет запущен сервер, например: **127.0.0.1**.
**port** - порт, на котором сервер будет принимать запросы, например: **8989**.
**reg_filter** - фильтрующее регулярное выражение, например: **^[-а-яёА-ЯЁ]*$**.
Если слово не подходит под регулярное выражение, то оно не обрабатывается. Это сделано потому, что на "некорректные" слова,
например - "тест1", mystem может не ответить и тогда весь "поток", работающий с этой запущенной версией программы, зависнет в ожидании ответа.
**mystem_path** - путь к исполняемому файлу mystem, например: **mystem/mystem.exe**.
**mystem_options** - опции с которыми будет запущена mystem, например:
```json
[
"-n",
"--format json"
]
```
Опция **--format** так же влияет формат ответа сервера, т.е. если задана опция **--format json**, то и сервер ответит в формате json.
- Если формат **text**, то результат - это строка где данные для каждого слова отделяются символом конца строки("\n").
- Если формат **json**, то результат - это массив с данными по каждому слову.
- Если формат **xml**, то результат - это xml документ, с элементам **<w>** на каждое слово.
- Опции **-e** игнорируется, используется кодировка - UTF-8.
- Опции **-d** игнорируется, т.к. сервер обрабатывает только слова, а не предложения/словосочетания. И возможно "зависание" потока.
- Опции **-с** игнорируется, по той же причине, почему игнорируется "-d". Так же, возможно, некорректное получение ответа от mystem.
- Опция **-n** будет добавлена автоматически, т.к. нужна для того, чтобы сервер мог получать ответы от mystem.
**mystem_workers** - сколько версий программы запустить для обработки запросов, например: **2**.
**mystem_answer_size** - размер ответа mystem в байтах, например: **10000**. Может быть больше чем размер ответа mystem, но не меньше, лучше ставить с запасом.
Если будет задано меньшее количество байт, чем размер ответа mystem, то будет считан не весь результат работы mystem.
Соответственно будет возвращен некорректный результат и дальнейшие ответы этого "потока" будут некорректными, так как в следующих ответах могут содержаться
куски результата предыдущего запроса.
**channel_buffer** - размер буфера очереди слов для обработки, например: **10**. Т.е. сколько слов может быть добавлено в очередь без ожидания.
**max_word_length** - максимальная длина слова, например: **50**. Если слово длинее, то оно будет усечено до указанной длины.
**max_words** - максимальное количество слов для обработки в одном запросе, например: **100**. Если слов больше, сервер вернет http код 413.
##Как работать
POST или GET запросом шлем, в переменной **words[]**, слово для обработки.
##Пример
```
curl http://127.0.0.1:8989 --data-urlencode words[]=проверяли --data-urlencode words[]=тестировали
```
Сервер запущен со следующими настройками:
```json
{
"host": "127.0.0.1",
"port": 8989,
"reg_filter": "^[-а-яёА-ЯЁ]*$",
"mystem_path": "mystem/mystem",
"mystem_options": [
"-n",
"--format text",
"-w",
"-i",
"-g",
"-s",
"--generate-all",
"--weight"
],
"mystem_workers": 2,
"mystem_answer_size": 10000,
"channel_buffer": 10,
"max_word_length": 50,
"max_words": 100
}
```
Результат в формате text:
```
проверяли{проверять:1.00=V,пе=прош,мн,изъяв,несов}
тестировали{тестировать:1.00=V,несов=прош,мн,изъяв,пе}
```
Результат в формате json:
```json
[{
"analysis": [{
"lex":"проверять",
"wt":1,
"gr":"V,пе=прош,мн,изъяв,несов"
}],
"text":"проверяли"
},
{
"analysis": [{
"lex":"тестировать",
"wt":1,
"gr":"V,несов=прош,мн,изъяв,пе"
}],
"text":"тестировали"
}]
```
Результат в формате xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<html>
<body>
<se>
<w>
проверяли<ana lex="проверять" wt="1" gr="V,пе=прош,мн,изъяв,несов" />
</w>
<w>
тестировали<ana lex="тестировать" wt="1" gr="V,несов=прош,мн,изъяв,пе" />
</w>
</se>
</body>
</html>
```
#Тесты
Уже в процессе<file_sep>/http_mystem_test.go
package http_mystem
import (
"testing"
"strings"
)
func TestProcessMystemOptions(t *testing.T) {
type TStruct struct{
opts []string
ok_opts string
ok_format string
}
var t_data = []TStruct{
{[]string{"-c", "-s", "-d", "-e cp1251"}, "-s -n", "text"},
{[]string{"-n", "--format json"}, "-n --format json", "json"},
{[]string{"-n", "-w", "-l", "-i", "--eng-gr", "--format xml"}, "-n -w -l -i --eng-gr --format xml", "xml"},
}
for i, t_item := range t_data {
opt, format, err := ProcessMystemOptions(t_item.opts)
j_opt := strings.Join(opt, " ")
if (j_opt != t_item.ok_opts) || (format != t_item.ok_format) || (err != nil) {
t.Errorf("Failed on %v %v", i, t_item)
}
}
}
|
c10767da19be06790adfda1e96aee8094b293151
|
[
"Markdown",
"Go"
] | 3
|
Go
|
rntk/http_mystem
|
6d7d693f5053d545389308934bc98e82ab0c5160
|
3c81dde3011cc21a2d6ed033a1d146aeae108dcd
|
refs/heads/master
|
<file_sep>set(CPACK_WIX_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/mywix.template.in")
add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
include(CPack)<file_sep>list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}")
add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
include(CPack)<file_sep>install(FILES CMakeLists.txt DESTINATION src)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_SOURCE_DIR}/patch.xml")
include(CPack)
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/license.txt")
include(CPack)<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_SOURCE_DIR}/patch.xml")
set(CPACK_WIX_EXTRA_SOURCES
"${CMAKE_CURRENT_SOURCE_DIR}/features.wxs"
"${CMAKE_CURRENT_SOURCE_DIR}/extra.foo.wxs"
"${CMAKE_CURRENT_SOURCE_DIR}/extra.bar.wxs"
)
include(CPack)
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_PACKAGE_INSTALL_DIRECTORY "CMakeWiXTestsuite/${CMAKE_PROJECT_NAME}")
include(CPack)
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_WIX_CULTURES "ja-JP")
include(CPack)<file_sep>cmake_minimum_required(VERSION 3.6)
include(CPackComponent)
install(FILES my_component.txt DESTINATION doc1 COMPONENT my_component1)
install(FILES my_component.txt DESTINATION doc2 COMPONENT my_component2)
cpack_add_component(my_component1
DISPLAY_NAME "My Component 1"
DESCRIPTION "My Component Description 1"
GROUP "MyGroup"
)
cpack_add_component(my_component2
DISPLAY_NAME "My Component 2"
DESCRIPTION "My Component Description 2"
GROUP "MyGroup"
)
cpack_add_component_group(MyGroup
DESCRIPTION "My Component Group Description"
)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_SOURCE_DIR}/patch.xml")
include(CPack)
<file_sep>#include <windows.h>
#include <sstream>
int main(int argc, char* argv[])
{
std::stringstream tmp;
for(int i = 1; i < argc; ++i)
{
tmp << i << ": " << argv[i] << std::endl;
}
std::string text = tmp.str();
MessageBox(NULL, text.c_str(), "Hello World", MB_OK);
}
<file_sep>#ifndef FANCY_HPP
#define FANCY_HPP
void fancy_lib();
#endif // FANCY_HPP
<file_sep>install(FILES icon.ico DESTINATION .)
set(MY_ICON "${CMAKE_CURRENT_SOURCE_DIR}/icon.ico")
configure_file(patch.xml.in patch.xml)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_BINARY_DIR}/patch.xml")
set(CPACK_WIX_PROPERTY_ARPPRODUCTICON "my_icon_id")
include(CPack)
<file_sep>install(FILES never_overwrite.txt DESTINATION test1)
install(FILES permanent.txt DESTINATION test2)
install(FILES permanent_and_never_overwrite.txt DESTINATION test3)
install(FILES
acl_generic_all.txt
acl_generic_write.txt
acl_mixed.txt
DESTINATION acl
)
install(
DIRECTORY
empty_directory_with_property
non_empty_directory_with_property
empty_directory
non_empty_directory
DESTINATION ./
PATTERN "ignore.me" EXCLUDE
)
set_property(INSTALL
test1/never_overwrite.txt
test3/permanent_and_never_overwrite.txt
PROPERTY CPACK_NEVER_OVERWRITE ON
)
set_property(INSTALL
test2/permanent.txt
test3/permanent_and_never_overwrite.txt
PROPERTY CPACK_PERMANENT ON
)
set_property(INSTALL
acl/acl_generic_all.txt
PROPERTY CPACK_WIX_ACL "Everyone=GenericAll"
)
set_property(INSTALL
acl/acl_generic_write.txt
PROPERTY CPACK_WIX_ACL "Everyone=GenericWrite"
)
set_property(INSTALL
acl/acl_mixed.txt
PROPERTY CPACK_WIX_ACL "Everyone=GenericRead,Read,ReadPermission,Delete"
)
set_property(INSTALL
empty_directory_with_property
non_empty_directory_with_property
PROPERTY CPACK_WIX_ACL "Everyone=GenericRead,GenericWrite,CreateFile"
)
include(CPack)
<file_sep>project(FancyWiXLib)
add_library(fancy_wix fancy.cpp fancy.hpp)
install(TARGETS fancy_wix ARCHIVE DESTINATION lib)
install(FILES fancy.hpp DESTINATION include)
install(FILES FancyWiXLibConfig.cmake DESTINATION .)
set(CPACK_WIX_CMAKE_PACKAGE_REGISTRY "FancyWiXLib")
include(CPack)
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_SOURCE_DIR}/patch.xml")
install(FILES hw.cpp DESTINATION src)
include(CPack)<file_sep>set(FOREIGN_CMAKE_COMMAND "${CMAKE_BIN_DIR}/cmake")
set(FOREIGN_CPACK_COMMAND "${CMAKE_BIN_DIR}/cpack")
if(EXISTS "${BIN_DIR}")
file(REMOVE_RECURSE "${BIN_DIR}")
endif()
file(MAKE_DIRECTORY "${BIN_DIR}")
execute_process(COMMAND "${FOREIGN_CMAKE_COMMAND}"
-G Ninja
"-DCMAKE_PROJECT_NAME=WiX-${TEST_NAME}"
"-DCPACK_GENERATOR=WIX" "${SRC_DIR}"
WORKING_DIRECTORY "${BIN_DIR}"
RESULT_VARIABLE CMAKE_RESULT
OUTPUT_VARIABLE CMAKE_OUTPUT
ERROR_VARIABLE CMAKE_OUTPUT
)
if(NOT "${CMAKE_RESULT}" STREQUAL "0")
message(FATAL_ERROR
"[${TEST_NAME}] CMake failed (${CMAKE_RESULT}) : [${CMAKE_OUTPUT}]")
endif()
execute_process(COMMAND "${FOREIGN_CMAKE_COMMAND}" --build .
WORKING_DIRECTORY "${BIN_DIR}"
RESULT_VARIABLE CMAKE_RESULT
OUTPUT_VARIABLE CMAKE_OUTPUT
ERROR_VARIABLE CMAKE_OUTPUT
)
file(WRITE ${BIN_DIR}/cmake.log "${CMAKE_OUTPUT}")
if(NOT "${CMAKE_RESULT}" STREQUAL "0")
message(FATAL_ERROR
"[${TEST_NAME}] CMake failed (${CMAKE_RESULT}) : [${CMAKE_OUTPUT}]")
endif()
execute_process(COMMAND "${FOREIGN_CPACK_COMMAND}"
WORKING_DIRECTORY "${BIN_DIR}"
RESULT_VARIABLE CPACK_RESULT
OUTPUT_VARIABLE CPACK_OUTPUT
ERROR_VARIABLE CPACK_OUTPUT
)
file(WRITE ${BIN_DIR}/cpack.log "${CPACK_OUTPUT}")
if(NOT "${CPACK_RESULT}" STREQUAL "0")
message(FATAL_ERROR
"[${TEST_NAME}] CPack failed (${CPACK_RESULT}) : [${CPACK_OUTPUT}]")
endif()
file(MAKE_DIRECTORY ${INSTALLER_DIR})
file(GLOB INSTALLER "${BIN_DIR}/WiX-${TEST_NAME}*")
get_filename_component(INSTALLER_FILENAME "${INSTALLER}" NAME)
set(OUTPUT_INSTALLER ${INSTALLER_DIR}/${INSTALLER_FILENAME})
execute_process(COMMAND "${CMAKE_COMMAND}" -E copy_if_different
"${INSTALLER}"
"${OUTPUT_INSTALLER}"
RESULT_VARIABLE COPY_RESULT
OUTPUT_VARIABLE COPY_OUTPUT
ERROR_VARIABLE COPY_OUTPUT
)
message("copy from [${INSTALLER}] to [${OUTPUT_INSTALLER}]")
if(NOT "${COPY_RESULT}" STREQUAL "0")
message(FATAL_ERROR
"[${TEST_NAME}] copy failed (${COPY_RESULT}) : [${COPY_OUTPUT}]")
endif()
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_WIX_PROPERTY_ARPCOMMENTS "My Comment")
include(CPack)
<file_sep>void newlib();
<file_sep>add_executable(h-w hw.cpp)
install(TARGETS h-w DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_CREATE_DESKTOP_LINKS h-w)
set(CPACK_PACKAGE_EXECUTABLES h-w "Hello World")
include(CPack)
<file_sep>add_executable(h-w hw.cpp)
install(TARGETS h-w DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_PACKAGE_EXECUTABLES h-w "Hello World")
set(CPACK_WIX_PROGRAM_MENU_FOLDER "custom_menu")
include(CPack)
<file_sep>set(FancyWiXLib_LIBRARIES "${FancyWiXLib_DIR}/lib/fancy_wix.lib")
set(FancyWiXLib_INCLUDE_DIRS "${FancyWiXLib_DIR}/include")
<file_sep>cmake_minimum_required(VERSION 2.8)
add_executable(myapp myapp.cpp)
install(TARGETS myapp RUNTIME DESTINATION bin COMPONENT foo)
install(FILES myapp.cpp DESTINATION src COMPONENT bar)
include(CPackComponent)
cpack_add_component(foo DISPLAY_NAME "My Foo Display Name"
DESCRIPTION "My Foo Description")
cpack_add_component(bar DISPLAY_NAME "My Bar Display Name"
DESCRIPTION "My Bar Description")
include(CPack)
<file_sep># Projeto Cmake, CPAK com WIX gerando MSI
[ LinkedIn](https://www.linkedin.com/in/miguel-penteado-760486a9/)
[ GitHub](https://github.com/miguel7penteado)
# Equivalencia de versões de pacotes Debian x Ubuntu:
| Ubuntu | Debian |
|----------------|--------------------|
| 22.10 kinetic | bookworm/ sid - 12 |
| 22.04 jammy | bookworm/ sid |
| 21.10 impish | bullseye/ sid - 11 |
| 21.04 hirsute | bullseye/ sid |
| 20.10 groovy | bullseye/ sid |
| 20.04 focal | bullseye/ sid |
| 19.10 eoan | buster / sid - 10 |
| 19.04 disco | buster / sid |
| 18.10 cosmic | buster / sid |
| 18.04 bionic | buster / sid |
| 17.10 artful | stretch / sid - 9 |
| 17.04 zesty | stretch / sid |
| 16.10 yakkety | stretch / sid |
| 16.04 xenial | stretch / sid |
| 15.10 wily | jessie / sid - 8 |
| 15.04 vivid | jessie / sid |
| 14.10 utopic | jessie / sid |
| 14.04 trusty | jessie / sid |
| 13.10 saucy | wheezy / sid - 7 |
| 13.04 raring | wheezy / sid |
| 12.10 quantal | wheezy / sid |
| 12.04 precise | wheezy / sid |
| 11.10 oneiric | wheezy / sid |
| 11.04 natty | squeeze / sid - 6 |
| 10.10 maverick | squeeze / sid |
| 10.04 lucid | squeeze / sid |
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src
PERMISSIONS OWNER_READ
)
include(CPack)<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_WIX_PRODUCT_ICON "${CMAKE_CURRENT_SOURCE_DIR}/icon.ico")
set(CPACK_WIX_UI_BANNER "${CMAKE_CURRENT_SOURCE_DIR}/banner.bmp")
set(CPACK_WIX_UI_DIALOG "${CMAKE_CURRENT_SOURCE_DIR}/dialog.bmp")
include(CPack)
<file_sep>add_executable(h-w hw.cpp)
install(TARGETS h-w DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set_property(INSTALL "bin/$<TARGET_FILE_NAME:h-w>"
PROPERTY CPACK_STARTUP_SHORTCUTS "Hello World"
)
set_property(INSTALL "src/hw.cpp"
PROPERTY CPACK_STARTUP_SHORTCUTS "Source Code" "Same Source Code"
)
include(CPack)
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
install(FILES hw.cpp DESTINATION src)
set(CPACK_WIX_UPGRADE_GUID "F9AAAAE2-D6AF-4EA4-BF46-B3E265400CC7")
include(CPack)
<file_sep>add_executable("h w" "h w.cpp")
install(TARGETS "h w" DESTINATION "my bin")
install(FILES "h w.cpp" DESTINATION "my src")
include(CPack)<file_sep>cmake_minimum_required(VERSION 2.8.12)
project(CMakeWiXTestsuite)
enable_testing()
set(REFERENCE_CMAKE_BIN_DIR "$ENV{WIX_REFERENCE_CMAKE_BIN_DIR}"
CACHE PATH "bin directory of the cmake build being tested")
function(add_packaging_test NAME)
set(TEST_BUILD_DIRECTORY
"${CMAKE_CURRENT_BINARY_DIR}/${NAME}")
add_test(NAME "${NAME}"
WORKING_DIRECTORY "${TEST_BUILD_DIRECTORY}"
COMMAND "${CMAKE_COMMAND}"
"-DTEST_NAME=${NAME}"
"-DCMAKE_BIN_DIR=${REFERENCE_CMAKE_BIN_DIR}"
"-DBIN_DIR=${TEST_BUILD_DIRECTORY}"
"-DSRC_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${NAME}"
"-DINSTALLER_DIR=${CMAKE_CURRENT_BINARY_DIR}/installers"
-P "${CMAKE_CURRENT_SOURCE_DIR}/test_wrapper.cmake"
)
add_custom_target("${NAME}" SOURCES "${NAME}/CMakeLists.txt")
endfunction()
add_custom_target(test_wrapper SOURCES test_wrapper.cmake)
add_packaging_test(basic)
add_packaging_test(space_in_path)
add_packaging_test(umlaut_in_path)
add_packaging_test(wix_cultures)
add_packaging_test(package_executables)
add_packaging_test(components)
add_packaging_test(two_components)
add_packaging_test(custom_template_in_module_path)
add_packaging_test(custom_template_by_variable)
add_packaging_test(ui_bitmaps_and_icon)
add_packaging_test(custom_program_menu_folder)
add_packaging_test(wix_util_extension)
add_packaging_test(fragment_injection)
add_packaging_test(fragment_injection_with_bad_id)
set_property(TEST fragment_injection_with_bad_id
PROPERTY PASS_REGULAR_EXPRESSION
"Some XML patch fragments did not have matching IDs")
add_packaging_test(package_install_directory)
add_packaging_test(read_only)
add_packaging_test(rtf_writer_unicode)
add_packaging_test(package_registry)
add_packaging_test(package_registry2)
add_packaging_test(desktop_shortcut)
add_packaging_test(properties)
add_packaging_test(arp_properties)
add_packaging_test(product_fragment_injection)
add_packaging_test(property_start_menu_shortcuts)
add_packaging_test(property_desktop_shortcuts)
add_packaging_test(property_startup_shortcuts)
add_packaging_test(extra_sources)
add_packaging_test(custom_action_with_condition)
add_packaging_test(feature_ref_in_product)
add_packaging_test(feature_patch)
<file_sep>cmake_minimum_required(VERSION 2.8.12)
include(CPackComponent)
add_library(mylib mylib.cpp)
add_executable(mylibapp mylibapp.cpp)
target_link_libraries(mylibapp mylib)
install(TARGETS mylib ARCHIVE DESTINATION lib COMPONENT libraries)
install(TARGETS mylibapp RUNTIME DESTINATION bin COMPONENT applications)
install(FILES mylib.h DESTINATION include COMPONENT headers)
install(FILES free.txt DESTINATION doc)
#set(CPACK_COMPONENTS_ALL applications libraries headers)
cpack_add_component(applications
DISPLAY_NAME "MyLib Application"
DESCRIPTION "An extremely useful application that makes use of MyLib"
GROUP "Runtime"
)
cpack_add_component(libraries
DISPLAY_NAME "Libraries"
DESCRIPTION "Static libraries used to build programs with MyLib"
HIDDEN
GROUP "Development"
)
cpack_add_component(headers
DISPLAY_NAME "C++ Headers"
DESCRIPTION "C/C++ header files for use with MyLib"
DEPENDS libraries
GROUP "Development"
)
cpack_add_component_group(Runtime)
cpack_add_component_group(Development
DESCRIPTION "All of the tools you'll ever need to develop software"
)
set(CPACK_COMPONENT_GROUP_DEVELOPMENT_PARENT_GROUP "Runtime")
#unset(CPACK_COMPONENT_APPLICATIONS_REQUIRED)
set(CPACK_ALL_INSTALL_TYPES Full Developer)
set(CPACK_COMPONENT_LIBRARIES_INSTALL_TYPES Developer Full)
set(CPACK_COMPONENT_HEADERS_INSTALL_TYPES Developer Full)
set(CPACK_COMPONENT_APPLICATIONS_INSTALL_TYPES Full)
include(CPack)
<file_sep>void newlib() {}
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bin)
set(CPACK_WIX_PATCH_FILE "${CMAKE_CURRENT_SOURCE_DIR}/patch.xml")
install(FILES hw.cpp DESTINATION src)
include(CPack)<file_sep>project(FancyWiXUser)
find_package(FancyWiXLib)
include(CPack)
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/FancyWiXLib.txt
"FancyWiXLib_DIR [${FancyWiXLib_DIR}]\n"
"FancyWiXLib_FOUND [${FancyWiXLib_FOUND}]"
)
<file_sep>#include "fancy.hpp"
#include <iostream>
void fancy_lib()
{
std::cout << "I am a fancy Library!" << std::endl;
}
<file_sep>add_executable(hw hw.cpp)
install(TARGETS hw DESTINATION bün)
install(FILES hw.cpp töst.txt DESTINATION süc)
include(CPack)
|
2e9d4fc0868509eb57727423be9fefa0937cb224
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 34
|
CMake
|
miguel7penteado/cmake-cpak-wix
|
2082fb9c3aaac0475397a413b65651a516789e40
|
f554c48cfb61c15114a5d1acc5bf10d85a5c7392
|
refs/heads/main
|
<repo_name>PoojaMallikarjun/OnlineCollaborativeWordProcessor<file_sep>/server/server.js
const mongoose = require('mongoose');
const Document = require('./Document')
mongoose.connect("mongodb://localhost/google-docs-clone", {
useNewUrlParser: true,
useUnifiedTopology: true,
// useFindAndModify: false,
// useCreateIndex: true,
})
const defaultValue = "";
const io = require('socket.io')(3001,{
cors: {
origin: 'http://localhost:3000',
methods:['GET','POST']
}
})
io.on("connection",socket => {
socket.on('get-doc',async docId=>{
const doc = await findOrCreateDoc(docId)
socket.join(docId)
socket.emit("load-doc",doc.data)
socket.on('send-changes',delta => {
socket.broadcast.to(docId).emit("receive-changes",delta);
})
socket.on('save-doc',async data =>{
await Document.findByIdAndUpdate(docId,{data})
})
})
})
async function findOrCreateDoc(id){
if(id == null) return;
const doc = await Document.findById(id);
if(doc){
return doc;
}
return await Document.create({_id:id,data:defaultValue});
}
|
4a1392a7df6ebf7327b9c9c21b31b7445fc340a1
|
[
"JavaScript"
] | 1
|
JavaScript
|
PoojaMallikarjun/OnlineCollaborativeWordProcessor
|
eef19cc46c68a1c8b210f7176558ad77881bf195
|
c157d49ce16feaa03b936391cfcc584c4a3754a0
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<!--
Exercici 1: Crea un array numèric de 10 elements i reassigna
els seus index per a que vagin des de l’u fins al deu.
-->
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="assets/css/main.css" />
<title>
</title>
</head>
<body>
<?php
$llista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
foreach ($llista as $key => $cont) {
$llista2[$key + 1] = $llista[$key];
}
echo '<pre>', print_r($llista2, 1), '</pre>';
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>showDate.php
</title>
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<!--Exercici 5: Crea un array amb les claus i el contingut de dos arrays existents.
$ordre = array (1,2,3,4,5,6,7,8,9,10);
$ingredients = array( "garrofó", "bajoqueta", "arròs", "pollastre", "conill", "safrà", "tomaca", "oli", "ceba", "aigua" );
-->
<h3>Exercici 5: Crea un array amb les claus i
<br>el contingut de dos arrays existents.
</h3>
<?php
$ordre = array (1,2,3,4,5,6,7,8,9,10);
$ingredients = array( "garrofó", "bajoqueta", "arròs", "pollastre", "conill", "safrà", "tomaca", "oli", "ceba", "aigua" );
foreach ($ingredients as $key => $cont) {
$llista[$ingredients[$key]] = $ordre[$key];
}
echo'<pre>', print_r($llista,1),'</pre>'
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>BINGO</title>
</head>
<body>
<img src="reload.png" height="75" width="75" onClick="window.location.reload()">
<h1>BINGO 2017</h1>
<style>
table, th, td {
border: 1px solid black;
padding: 30px;
text-align: center;
}
table {
border-spacing: 2px;
}
h1 {
margin-top: 0px;
color: #fff;
font-size: 10em;
font-weight: bold;
font-family: Helvetica;
text-shadow: 0 1px 0 #ccc, 0 2px 0 #c9c9c9, 0 3px 0 #bbb, 0 4px 0 #b9b9b9, 0 5px 0 #aaa, 0 6px 1px rgba(0,0,0,.1), 0 0 5px rgba(0,0,0,.1), 0 1px 3px rgba(0,0,0,.3), 0 3px 5px rgba(0,0,0,.2), 0 5px 10px rgba(0,0,0,.25), 0 10px 10px rgba(0,0,0,.2), 0 20px 20px rgba(0,0,0,.15);
}
h1 {
text-align: center;
}
body {
background-color: #f1f1f1;
}
img:hover{
cursor: pointer;
}
</style>
<?php
function aleatori($matriu) {
$num = rand(1, 99);
while (in_array($num, $matriu[0]) || in_array($num, $matriu[1]) || in_array($num, $matriu[2])) {
$num = rand(1, 99);
}
return $num;
}
function blancs($buits) {
$num = rand(0, 8);
while (in_array($num, $buits)) {
$num = rand(0, 8);
}
return $num;
}
$matriu = array(array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
for ($i = 0; $i < count($matriu); $i++) {
for ($j = 0; $j < count($matriu[$i]); $j++) {
$matriu[$i][$j] = aleatori($matriu);
}
}
for ($i = 0; $i < count($matriu); $i++) {
sort($matriu[$i]);
}
$buits = array(9, 9, 9, 9);
for ($i = 0; $i < count($matriu); $i++) {
for ($j = 0; $j < count($buits); $j++) {
$buits[$j] = blancs($buits);
$matriu[$i][$buits[$j]] = " ";
}
$buits = array(9, 9, 9, 9);
}
echo '<table align="center">';
for ($i = 0; $i < count($matriu); $i++) {
echo "<tr>";
for ($x = 0; $x < count($matriu[$i]); $x++) {
echo "<td>" . $matriu[$i][$x] . "</td>";
}
echo"</tr>";
}
echo "</table>";
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Exerici 6</title>
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<!--$array1 = array( "green", "red", "blue", "red", "purple", "black", "orange", "white");
$array2 = array( "green", "yellow", "red");
$array3 = array( "pink", "white", "blue", "red");
-->
<h3>Exercici 6: Mostra la intersecció dels següents arrays.
</h3>
<?php
$array1 = array( "green", "black", "white", "red", "pink");
$array2 = array( "white","pink", "yellow", "red");
$array3 = array( "red","black", "green", "blue", "pink");
$result = array_intersect($array1, $array2, $array3);
print_r($result);
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<!--
Exercici 2: Converteix el vector de l’exercici anterior en un vector
associatiu on els índexs són el mateix número però escrit amb lletres.
-->
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="assets/css/main.css" />
<title></title>
</head>
<body>
<?php
$llista = [1,2,3,4,5,6,7,8,9,10];
$lletres = ["un", "dos", "tres", "quatre", "cinc", "sis", "set", "vuit",
"nou", "deu"];
foreach ($llista as $key => $cont) {
$llista2[$lletres[$key]] = $llista[$key];
}
echo '<pre>',print_r($llista2,1),'</pre>';
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Joc de la mona</title>
</head>
<body>
<?php
$suits = array(
"Spades", "Hearts", "Clubs", "Diamonds"
);
$faces = array(
"Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King", "Ace"
);
$player01 = array();
$player02 = array();
$player03 = array();
$deck = array();
foreach ($suits as $suit) {
foreach ($faces as $face) {
$deck[] = array("face" => $face, "suit" => $suit);
}
}
$i = 0;
$find = false;
while ($i < count($deck) or find == TRUE) {
if ($deck[$i] == 'Five of Diamonds') {
unset($deck[50]);
}
}
print_r($deck);
shuffle($deck);
$card = array_shift($deck);
echo $card['face'] . ' of ' . $card['suit'];
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Exerici 7</title>
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<!--Exercici 7: Crea una funció que accepti dos paràmetres keyini i keyfin que
indicaran l’index d’inici i final del array i genere un array de números
sencers aleatoris. Mostra el contingut en un html.
-->
<h3>Exercici 7: Crea una funció que accepti dos paràmetres keyini i <br>
keyfin que indicaran l’index d’inici i final del array i genere un<br>
array de números sencers aleatoris. Mostra el contingut en un html.
</h3>
<?php
function RandNumbers($Keyinici, $Keyfinal){
$randnum = array();
for($x = $Keyinici; $x < $Keyfinal;$x++){
$randnum[$x] = rand();
}
return $randnum;
}
$result = RandNumbers(0,5);
print_r( $result );
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<!--
Exercici 4: Mostra en una taula HTML de 2x2 el contingut del següent
array numèric.
$H2oVcia = array ("Suc <NAME>", "Cava", "Vodka", "cointreau");
-->
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="assets/css/main.css" />
<title></title>
</head>
<body>
<?php
$H2oVc9a = array("Suc <NAME>", "Cava", "Vodka", "Cointeau",
"Vi Blanc");
echo("<table border=2>");
for($i = 0; $i < count($H2oVc9a); $i +=2){
echo("<tr>");
echo("<td> $H2oVc9a[$i] </td>");
$x = $i + 1;
echo("<td>$H2oVc9a[$x]</td>");
echo("</tr>");
}
echo("</table>");
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<!--
Exercici 3: Mostra en la teua pàgina web el contingut del següent array
associatiu (clau i contingut) fent ús de la instrucció foreach.
< $paella = array( "garrofó" => 1, "bajoqueta" => 1, "arròs" => 2,
"pollastre" => 2, "conill" => 1, "safrà" => 1, "tomaca" => 1, "oli" => 1,
"aigua" => 2 );
-->
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="assets/css/main.css" />
<title>
</title>
</head>
<body>
<?php
$paella = array( "garrofó" => 1, "bajoqueta" => 1, "arròs" => 2,
"pollastre" => 2, "conill" => 1, "safrà" => 1, "tomaca" => 1,
"oli" => 1, "aigua" => 2 );
foreach ($paella as $key => $value) {
echo"<strong><i>{$key}</strong></i> => <font color='red'>{$value}"
. "</font> <br />";
}
?>
<div id="wrapper">
<header id="header">
<nav>
<ul>
<li>
<a href="index.html">Menu
</a>
</li>
</ul>
</nav>
</header>
</div>
</body>
</html>
|
d0d3b84c131d49689f2cf2a89312e289fcb6301f
|
[
"PHP"
] | 9
|
PHP
|
lavjitsingh/M07
|
1df626b2b94e491994e8715754c8d78831b3a4ec
|
8c524ae64b65dbe1c6807defdad6692af96f3ccb
|
refs/heads/master
|
<file_sep># ExpressionPlotter
A library for evaluating expressions and a control for drawing expression graphs
<file_sep>using System;
using System.Collections.Generic;
namespace ExpressionPlotterControl
{
public class Expression : IEvaluatable
{
/// <summary>
/// klfjksefklfjkljfklfklsdfjklsdfjkl
/// </summary>
private readonly char charX = 'x';
private readonly Dictionary<string, double> constants;
private bool isValid;
private string text = "";
private string textInternal = "";
public Expression(string expressionText)
{
this.constants = new Dictionary<string, double>();
this.constants.Add("pi", Math.PI);
this.constants.Add("e", Math.E);
this.ExpressionText = expressionText;
}
#region Public Properties for IEvaluatable
public string ExpressionText
{
get
{
return this.text;
}
set
{
this.text = value;
this.textInternal = $"({value})";
this.textInternal = InsertPrecedenceBrackets().Trim();
this.Validate();
}
}
public bool IsValid => this.isValid;
#endregion Public Properties for IEvaluatable
#region Public Methods for IEvaluatable
public double Evaluate(double dvalueX)
{
if (!this.isValid)
{
return double.NaN;
}
int temp;
return EvaluateInternal(dvalueX, 0, out temp);
}
public double EvaluateInternal(double dvalueX, int startIndex, out int endIndex)
{
//exceptions are bubbled up
//dAnswer is the running total
double dAnswer = 0, dOperand = 0;
char chCurrentChar, chOperator = '+';
string strAngleOperator;
for (int i = startIndex + 1; i < textInternal.Length; i++)
{
startIndex = i;
chCurrentChar = textInternal[startIndex];
// if found a number, update dOperand
if (char.IsDigit(chCurrentChar))
{
while (char.IsDigit(textInternal[i]) || textInternal[i] == '.')
{
i++;
}
dOperand = Convert.ToDouble(textInternal.Substring(startIndex, i - startIndex));
i--;
}
//if found an operator
else if (IsOperator(chCurrentChar))
{
dAnswer = DoOperation(dAnswer, dOperand, chOperator);
chOperator = chCurrentChar;
}
//if found independent variable
else if (char.ToLower(chCurrentChar) == charX)
{
dOperand = dvalueX;
}
//if found a bracket, solve it first
else if (chCurrentChar == '(')
{
dOperand = EvaluateInternal(dvalueX, i, out endIndex);
i = endIndex;
}
//if found closing bracket, return result
else if (chCurrentChar == ')')
{
dAnswer = DoOperation(dAnswer, dOperand, chOperator);
endIndex = i;
return dAnswer;
}
else //could be any function e.g. "sin" or any constant e.g "pi"
{
while (char.IsLetter(textInternal[i]))
{
i++;
}
//if we got letters followed by "(", we've got a function else a constant
if (textInternal[i] == '(')
{
strAngleOperator = textInternal.Substring(startIndex, i - startIndex).ToLower();
dOperand = EvaluateInternal(dvalueX, i, out endIndex);
i = endIndex;
dOperand = DoAngleOperation(dOperand, strAngleOperator);
}
else //constant
{
dOperand = this.constants[textInternal.Substring(startIndex, i - startIndex).ToLower()];
i--;
}
}
if (double.IsNaN(dAnswer) || double.IsNaN(dOperand))
{
endIndex = i;
return double.NaN;
}
}
endIndex = textInternal.Length;
return 0;
}
//this function contains definitions for supported functions, we can add more also.
private static double DoAngleOperation(double dOperand, string strOperator)
{
strOperator = strOperator.ToLower();
switch (strOperator)
{
case "abs":
{
return Math.Abs(dOperand);
}
case "sin":
{
return Math.Sin(dOperand);
}
case "cos":
{
return Math.Cos(dOperand);
}
case "tan":
{
return Math.Tan(dOperand);
}
case "sec":
{
return 1.0 / Math.Cos(dOperand);
}
case "cosec":
{
return 1.0 / Math.Sin(dOperand);
}
case "cot":
{
return 1.0 / Math.Tan(dOperand);
}
case "arcsin":
{
return Math.Asin(dOperand);
}
case "arccos":
{
return Math.Acos(dOperand);
}
case "arctan":
{
return Math.Atan(dOperand);
}
case "exp":
{
return Math.Exp(dOperand);
}
case "ln":
{
return Math.Log(dOperand);
}
case "log":
{
return Math.Log10(dOperand);
}
case "antilog":
{
return Math.Pow(10, dOperand);
}
case "sqrt":
{
return Math.Sqrt(dOperand);
}
case "sinh":
{
return Math.Sinh(dOperand);
}
case "cosh":
{
return Math.Cosh(dOperand);
}
case "tanh":
{
return Math.Tanh(dOperand);
}
case "arcsinh":
{
return Math.Log(dOperand + Math.Sqrt(dOperand * dOperand + 1));
}
case "arccosh":
{
return Math.Log(dOperand + Math.Sqrt(dOperand * dOperand - 1));
}
case "arctanh":
{
return Math.Log((1 + dOperand) / (1 - dOperand)) / 2;
}
default:
{
// throw new ArgumentException("InvalidAngleOperatorException")
return double.NaN;
}
}
}
// returns dOperant1 (op) dOperand2
private static double DoOperation(double dOperand1, double dOperand2, char chOperator)
{
switch (chOperator)
{
case '+':
{
return dOperand1 + dOperand2;
}
case '-':
{
return dOperand1 - dOperand2;
}
case '*':
{
return dOperand1 * dOperand2;
}
case '/':
{
return dOperand1 / dOperand2;
}
case '^':
{
return Math.Pow(dOperand1, dOperand2);
}
case '%':
{
return dOperand1 % dOperand2;
}
}
return double.NaN;
}
private static double GetR(double X, double Y) => Math.Sqrt(X * X + Y * Y);
private static double GetTheta(double X, double Y)
{
const double EPSILON = 0.00000000001;
double dTheta;
if (Math.Abs(X) < EPSILON)
{
dTheta = Y > 0 ? Math.PI / 2 : -Math.PI / 2;
}
else
{
dTheta = Math.Atan(Y / X);
}
//actual range of theta is from 0 to 2PI
if (X < 0)
{
dTheta = dTheta + Math.PI;
}
else if (Y < 0)
{
dTheta = dTheta + 2 * Math.PI;
}
return dTheta;
}
private static bool IsOperator(char character)
{
return character == '+' || character == '-' || character == '*'
|| character == '/' || character == '^' || character == '%';
}
//insert brackets at appropriate positions since the evaluation function
// only evaluates from Left To Right considering only bracket's precedence
private string InsertPrecedenceBrackets()
{
var i = 0;
var j = 0;
var iBrackets = 0;
var bReplace = false;
int iLengthExpression;
var strExpression = this.textInternal;
//Precedence for * && /
i = 1;
iLengthExpression = strExpression.Length;
while (i <= iLengthExpression)
{
if (strExpression.Substring(-1 + i, 1) == "*" || strExpression.Substring(-1 + i, 1) == "/")
{
for (j = i - 1; j > 0; j--)
{
if (strExpression.Substring(-1 + j, 1) == ")")
{
iBrackets = iBrackets + 1;
}
if (strExpression.Substring(-1 + j, 1) == "(")
{
iBrackets = iBrackets - 1;
}
if (iBrackets < 0)
{
break;
}
if (iBrackets == 0 && (strExpression.Substring(-1 + j, 1) == "+" || strExpression.Substring(-1 + j, 1) == "-"))
{
strExpression = $"{strExpression.Substring(-1 + 1, j)}({strExpression.Substring(-1 + j + 1)}";
bReplace = true;
i = i + 1;
break;
}
}
iBrackets = 0;
j = i;
i = i + 1;
while (bReplace)
{
j = j + 1;
if (strExpression.Substring(-1 + j, 1) == "(")
{
iBrackets = iBrackets + 1;
}
if (strExpression.Substring(-1 + j, 1) == ")")
{
if (iBrackets == 0)
{
strExpression = $"{strExpression.Substring(-1 + 1, j - 1)}){strExpression.Substring(-1 + j)}";
bReplace = false;
i = i + 1;
break;
}
iBrackets = iBrackets - 1;
}
if (strExpression.Substring(-1 + j, 1) == "+" || strExpression.Substring(-1 + j, 1) == "-")
{
strExpression = $"{strExpression.Substring(-1 + 1, j - 1)}){strExpression.Substring(-1 + j)}";
bReplace = false;
i = i + 1;
break;
}
}
}
iLengthExpression = strExpression.Length;
i = i + 1;
}
//Precedence for ^ && %
i = 1;
iLengthExpression = strExpression.Length;
while (i <= iLengthExpression)
{
if (strExpression.Substring(-1 + i, 1) == "^" || strExpression.Substring(-1 + i, 1) == "%")
{
for (j = i - 1; j > 0; j--)
{
if (strExpression.Substring(-1 + j, 1) == ")")
{
iBrackets = iBrackets + 1;
}
if (strExpression.Substring(-1 + j, 1) == "(")
{
iBrackets = iBrackets - 1;
}
if (iBrackets < 0)
{
break;
}
if (iBrackets == 0 && (strExpression.Substring(-1 + j, 1) == "+"
|| strExpression.Substring(-1 + j, 1) == "-"
|| strExpression.Substring(-1 + j, 1) == "*"
|| strExpression.Substring(-1 + j, 1) == "/"))
{
strExpression = $"{strExpression.Substring(-1 + 1, j)}({strExpression.Substring(-1 + j + 1)}";
bReplace = true;
i = i + 1;
break;
}
}
iBrackets = 0;
j = i;
i = i + 1;
while (bReplace)
{
j = j + 1;
if (strExpression.Substring(-1 + j, 1) == "(")
{
iBrackets = iBrackets + 1;
}
if (strExpression.Substring(-1 + j, 1) == ")")
{
if (iBrackets == 0)
{
strExpression = $"{strExpression.Substring(-1 + 1, j - 1)}){strExpression.Substring(-1 + j)}";
bReplace = false;
i = i + 1;
break;
}
iBrackets = iBrackets - 1;
}
if (strExpression.Substring(-1 + j, 1) == "+" || strExpression.Substring(-1 + j, 1) == "-"
|| strExpression.Substring(-1 + j, 1) == "*" || strExpression.Substring(-1 + j, 1) == "/")
{
strExpression = $"{strExpression.Substring(-1 + 1, j - 1)}){strExpression.Substring(-1 + j)}";
bReplace = false;
i = i + 1;
break;
}
}
}
iLengthExpression = strExpression.Length;
i = i + 1;
}
return strExpression;
}
#endregion Public Methods for IEvaluatable
#region Private Methods
private void Validate()
{
try
{
int temp;
// if expression does not throw an exception when evaluated at "1", we assume it to be valid
EvaluateInternal(1, 0, out temp);
this.isValid = true;
}
catch (FormatException)
{
this.isValid = false;
}
catch (KeyNotFoundException)
{
this.isValid = false;
}
}
#endregion Private Methods
}
}<file_sep>/*
* Expression Plotter Control
* Copyright 2007 by <NAME> <<EMAIL>>
* This code can be used freely as long as you keep these comments
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace ExpressionPlotterControl
{
public enum GraphMode
{ Rectangular, Polar };
[ToolboxBitmap("graph.bmp")]
public partial class ExpressionPlotter : Control
{
private double dScaleX = 10, dScaleY = 10; //base scale for graph
private readonly double EPSILON = 0.000000000001;
private readonly List<Color> expColors;
private readonly List<IEvaluatable> expressions;
private readonly List<bool> expVisible;
private int iDivisionsX = 5, iDivisionsY = 5;
private int iLengthBoxX;
private int iLengthBoxY;
#region MemberVariables
private int iLengthScaleX; //represents no. of pixels for x-axis
private int iLengthScaleY; //represents no. of pixels for y-axis
private int iOriginX, iOriginY; //represents the location of origin
private int iPolarSensitivity = 100;
private int iPrintStepX = 1;
private int iPrintStepY = 1;
private PrintDocument printDoc;
#endregion MemberVariables
#region Control specific functions
public ExpressionPlotter()
{
this.expressions = new List<IEvaluatable>();
this.expColors = new List<Color>();
this.expVisible = new List<bool>();
InitializeComponent();
}
public bool DisplayText { get; set; } = true;
#endregion Control specific functions
#region Properties
public int DivisionsX
{
get { return this.iDivisionsX; }
set { if (value > 0) this.iDivisionsX = value; }
}
public int DivisionsY
{
get { return this.iDivisionsY; }
set { if (value > 0) this.iDivisionsY = value; }
}
public double ForwardX { get; set; }
public double ForwardY { get; set; }
public GraphMode GraphMode { get; set; } = GraphMode.Rectangular;
public bool Grids { get; set; }
public int PenWidth { get; set; } = 1;
public int PolarSensitivity
{
get { return this.iPolarSensitivity; }
set { if (value > 0) this.iPolarSensitivity = value; }
}
public int PrintStepX
{
get { return this.iPrintStepX; }
set { if (value > 0) this.iPrintStepX = value; }
}
public int PrintStepY
{
get { return this.iPrintStepY; }
set { if (value > 0) this.iPrintStepY = value; }
}
public double ScaleX
{
get { return this.dScaleX; }
set { if (Math.Abs(value) > EPSILON) this.dScaleX = value; }
}
public double ScaleY
{
get { return this.dScaleY; }
set { if (Math.Abs(value) > EPSILON) this.dScaleY = value; }
}
#endregion Properties
#region Public functions for expression management
public void AddExpression(IEvaluatable expression, Color color, bool visible)
{
expressions.Add(expression);
expColors.Add(color);
expVisible.Add(visible);
}
public void CopyToClipboard()
{
Clipboard.SetImage(GetGraphBitmap());
}
public IEvaluatable GetExpression(int index) => expressions[index];
public Color GetExpressionColor(int index) => expColors[index];
public bool GetExpressionVisibility(int index) => expVisible[index];
public Bitmap GetGraphBitmap()
{
var bmpSnap = new Bitmap(this.Width, this.Height);
DrawToBitmap(bmpSnap, new Rectangle(0, 0, this.Width, this.Height));
return bmpSnap;
}
public double[] GetValues(double x)
{
var result = new double[expressions.Count];
for (int i = 0; i < this.expressions.Count; i++)
{
if (this.expressions[i].IsValid)
{
result[i] = this.expressions[i].Evaluate(x);
}
}
return result;
}
public void MoveDown(int divisions)
{
this.ForwardY -= divisions * this.dScaleY / this.iDivisionsY;
}
public void MoveLeft(int divisions)
{
this.ForwardX -= divisions * this.dScaleX / this.iDivisionsX;
}
public void MoveRight(int divisions)
{
this.ForwardX += divisions * this.dScaleX / this.iDivisionsX;
}
public void MoveUp(int divisions)
{
this.ForwardY += divisions * this.dScaleY / this.iDivisionsY;
}
public void RemoveAllExpressions()
{
this.expressions.Clear();
this.expColors.Clear();
this.expVisible.Clear();
}
public bool RemoveExpression(IEvaluatable expression)
{
var index = expressions.IndexOf(expression);
if (index == -1)
{
return false;
}
expressions.RemoveAt(index);
expColors.RemoveAt(index);
expVisible.RemoveAt(index);
return true;
}
public void RemoveExpressionAt(int index)
{
// can throw OutOfRangeException
expressions.RemoveAt(index);
expColors.RemoveAt(index);
expVisible.RemoveAt(index);
}
public void RestoreDefaults()
{
this.dScaleX = this.dScaleY = 10;
this.ForwardX = this.ForwardY = 0;
this.iDivisionsX = this.iDivisionsY = 5;
this.iPrintStepX = this.iPrintStepY = 1;
this.Grids = false;
this.iPolarSensitivity = 100;
}
public void SetExpression(int index, IEvaluatable expression)
{
// can throw OutOfRangeException
this.expressions[index] = expression;
}
public void SetExpressionColor(int index, Color color)
{
// can throw OutOfRangeException
this.expColors[index] = color;
}
public void SetExpressionVisibility(int index, bool visibility)
{
// can throw OutOfRangeException
this.expVisible[index] = visibility;
}
#endregion Public functions for expression management
#region Public functions for graph management
public void SetRangeX(double startX, double endX)
{
this.dScaleX = (endX - startX) / 2;
this.ForwardX = (endX + startX) / 2;
}
public void SetRangeY(double startY, double endY)
{
this.dScaleY = (endY - startY) / 2;
this.ForwardY = (endY + startY) / 2;
}
public void ToggleGrids()
{
this.Grids = (!Grids);
}
public void ZoomIn()
{
ZoomInX();
ZoomInY();
}
public void ZoomInX()
{
this.dScaleX = DecreaseScale(this.dScaleX);
}
public void ZoomInY()
{
this.dScaleY = DecreaseScale(this.dScaleY);
}
public void ZoomOut()
{
ZoomOutX();
ZoomOutY();
}
public void ZoomOutX()
{
this.dScaleX = IncreaseScale(this.dScaleX);
}
public void ZoomOutY()
{
this.dScaleY = IncreaseScale(this.dScaleY);
}
protected override void OnPaint(PaintEventArgs e)
{
// update internal variables
UpdateVariables();
e.Graphics.Clear(Color.White);
e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
PlotGraph(e.Graphics);
// Calling the base class OnPaint
base.OnPaint(e);
}
private static double DecreaseScale(double scale)
{
var absScale = Math.Round(Math.Abs(scale), 3);
double newScale;
newScale = absScale > 100 ? (absScale - 100) : absScale > 10 ? (absScale - 10) : absScale > 1 ? (absScale - 1) : absScale > .1 ? (absScale - .1) : absScale > .01 ? (absScale - .01) : absScale;
return newScale * Math.Sign(scale);
}
private static double IncreaseScale(double scale)
{
var absScale = Math.Round(Math.Abs(scale), 3);
double newScale;
newScale = absScale >= 100 ? (absScale + 100) : absScale >= 10 ? (absScale + 10) : absScale >= 1 ? (absScale + 1) : absScale >= .10 ? (absScale + .10) : (absScale + .010);
return newScale * Math.Sign(scale);
}
private void DisplayExpressionsText(Graphics g)
{
var line = 0;
for (int i = 0; i < this.expressions.Count; i++)
{
if (expVisible[i])
{
if (expressions[i].IsValid)
{
using (var solidBrush = new SolidBrush(expColors[i]))
{
using (var font = new Font("Arial", 8))
{
g.DrawString(expressions[i].ExpressionText, font, solidBrush, 10, 10 + 10 * line);
}
}
}
else
{
using (var solidBrush = new SolidBrush(expColors[i]))
{
using (var font = new Font("Arial", 8))
{
g.DrawString($"ERROR: {expressions[i].ExpressionText}", font, solidBrush, 10, 10 + 10 * line);
}
}
}
line++;
}
}
}
private void DisplayScale(Graphics g)
{
//axes lines
using (var pen = new Pen(Color.Black, 1))
{
//axes lines
g.DrawLine(pen, new Point(iOriginX - iLengthScaleX, iOriginY), new Point(iOriginX + iLengthScaleX, iOriginY));
}
using (var pen = new Pen(Color.Black, 1))
{
g.DrawLine(pen, new Point(iOriginX, iOriginY - iLengthScaleY), new Point(iOriginX, iOriginY + iLengthScaleY));
}
int i;
double dValue;
string strValue;
float cordX, cordY;
//X-axis values
dValue = -dScaleX + ForwardX;
for (i = -iDivisionsX; i <= iDivisionsX; i++)
{
using (var pen = new Pen(Color.Gray, 1))
{
g.DrawLine(pen, new PointF((float)(iOriginX + (dValue - ForwardX) * iLengthScaleX / dScaleX), iOriginY - iLengthBoxY), new PointF((float)(iOriginX + (dValue - ForwardX) * iLengthScaleX / dScaleX), iOriginY + iLengthBoxY));
}
if (i % iPrintStepX == 0 && i != 0)
{
strValue = Math.Round(dValue, 3).ToString();
cordX = (float)(iOriginX + (dValue - ForwardX) * iLengthScaleX / dScaleX - 6 - (strValue.Length - 2) * 5);
cordY = (float)(iOriginY + 10);
using (var solidBrush = new SolidBrush(Color.Black))
{
using (var font = new Font("Arial", 8))
{
g.DrawString(strValue, font, solidBrush, cordX, cordY);
}
}
}
dValue = dValue + dScaleX / iDivisionsX;
}
//Y-axis values
dValue = -dScaleY + ForwardY;
for (i = -iDivisionsY; i <= iDivisionsY; i++)
{
using (var pen = new Pen(Color.Gray, 1))
{
g.DrawLine(pen, new PointF(iOriginX - iLengthBoxX, (float)(iOriginY + (dValue - ForwardY) * iLengthScaleY / dScaleY)), new PointF(iOriginX + iLengthBoxX, (float)(iOriginY + (dValue - ForwardY) * iLengthScaleY / dScaleY)));
}
if (i % iPrintStepY == 0 && i != 0)
{
strValue = Math.Round(dValue, 3).ToString();
cordX = (float)(iOriginX - 20 - (strValue.Length) * 4);
cordY = (float)(iOriginY - (dValue - ForwardY) * iLengthScaleY / dScaleY - 7);
if (this.iLengthBoxY == this.iLengthScaleY)
{
cordY += 6;
}
using (var solidBrush = new SolidBrush(Color.Black))
{
using (var font = new Font("Arial", 8))
{
g.DrawString(strValue, font, solidBrush, cordX, cordY);
}
}
}
dValue = dValue + dScaleY / iDivisionsY;
}
if (GraphMode == GraphMode.Polar)
{
using (var pen = new Pen(Color.Black, 1))
{
g.DrawEllipse(pen, iOriginX - iLengthScaleX, iOriginY - (float)(iLengthScaleY * dScaleX / dScaleY), iLengthScaleX * 2, (float)(iLengthScaleY * dScaleX / dScaleY) * 2);
}
for (dValue = 0; dValue <= 2 * Math.PI; dValue += Math.PI / 6)
{
using (var pen = new Pen(Color.Gray, 1))
{
g.DrawLine(pen, new Point(iOriginX, iOriginY), new PointF((float)(iOriginX + iLengthScaleX * Math.Cos(dValue)), (float)(iOriginY + iLengthScaleY * Math.Sin(dValue))));
}
}
}
}
private void ExpressionPlotter_Resize(object sender, EventArgs e)
{
this.Refresh();
//removed code that was keeping the control's height and width same
}
private void InitializePrintDoc()
{
this.printDoc = new PrintDocument();
this.printDoc.OriginAtMargins = true;
this.printDoc.DefaultPageSettings.Margins.Left = 200;
this.printDoc.DefaultPageSettings.Margins.Top = 100;
this.printDoc.DocumentName = "Graph Plotter by <NAME>";
this.printDoc.PrintPage += delegate (object sender, PrintPageEventArgs e) { PlotGraph(e.Graphics); };
}
#endregion Public functions for graph management
#region Plotting Functions
private void PlotGraph(Graphics g)
{
DisplayScale(g);
if (this.DisplayText)
{
DisplayExpressionsText(g);
}
double X, Y;
double dPointX, dPointY;
double dLeastStepX, dLeastStepY;
double dMin, dMax, dStep;
int i;
//(X1,Y1) is the previous point ploted, (X2,Y2) is the current point to plot. (we will join both to have our
// graph continuous).
float X1 = 0, Y1 = 0, X2 = 0, Y2 = 0;
//This variable controls whether our graph should be continuous or not
var bContinuity = false;
//divide scale with its length(pixels) to get increment per pixel
dLeastStepX = dScaleX / iLengthScaleX;
dLeastStepY = dScaleY / iLengthScaleY;
//prepare variables for loop
if (GraphMode == GraphMode.Polar)
{
dMin = -Math.PI;
dMax = Math.PI;
dStep = dScaleX / iPolarSensitivity;
}
else //if (Rectangular Mode)
{
dStep = dLeastStepX;
dMin = -dScaleX + ForwardX;
dMax = dScaleX + ForwardX;
}
for (i = 0; i < this.expressions.Count; i++)
{
//check if expression needs to be drawn and is valid
if (expVisible[i] && expressions[i].IsValid)
{
bContinuity = false;
for (X = dMin; Math.Abs(X - dMax) > EPSILON; X += dStep)
{
if (dScaleX < 0 && X < dMax)
{
break;
}
if (dScaleX > 0 && X > dMax)
{
break;
}
try
{
//evaluate expression[i] at point: X
Y = expressions[i].Evaluate(X);
if (double.IsNaN(Y))
{
//break continuity in graph if expression returned a NaN
bContinuity = false;
continue;
}
//get points to plot
if (GraphMode == GraphMode.Polar)
{
dPointX = Y * Math.Cos(X) / dLeastStepX;
dPointY = Y * Math.Sin(X) / dLeastStepY;
}
else // if (Rectangular mode
{
dPointX = X / dLeastStepX;
dPointY = Y / dLeastStepY;
}
//check if the point to be plotted lies inside our visible area(i.e. inside our current axes ranges)
if ((iOriginY - dPointY + ForwardY / dLeastStepY) < iOriginY - iLengthScaleY
|| (iOriginY - dPointY + ForwardY / dLeastStepY) > iOriginY + iLengthScaleY
|| (iOriginX + dPointX - ForwardX / dLeastStepX) < iOriginX - iLengthScaleX
|| (iOriginX + dPointX - ForwardX / dLeastStepX) > iOriginX + iLengthScaleX)
{
//the point lies outside our current scale so break continuity
bContinuity = false;
continue;
}
//get coordinates for currently evaluated point
X2 = (float)(iOriginX + dPointX - ForwardX / dLeastStepX);
Y2 = (float)(iOriginY - dPointY + ForwardY / dLeastStepY);
//if graph should not be continuous
if (!bContinuity)
{
X1 = X2;
Y1 = Y2;
// the graph should be continuous afterwards since the current evaluated value is valid
// and can be plot within our axes range
bContinuity = true;
}
//join points (X1,Y1) and (X2,Y2)
using (var pen = new Pen(expColors[i], PenWidth))
{
//join points (X1,Y1) and (X2,Y2)
g.DrawLine(pen, new PointF(X1, Y1), new PointF(X2, Y2));
}
//get current values into X1,Y1
X1 = X2;
Y1 = Y2;
}
catch (Exception)
{
bContinuity = false;
continue;
}
}
}
}
}
private void UpdateVariables()
{
iLengthScaleX = (int)(this.Width / 2.25);
iLengthScaleY = (int)(this.Height / 2.25);
iOriginX = (this.Width) / 2;
iOriginY = (this.Height) / 2;
if (Grids)
{
this.iLengthBoxX = this.iLengthScaleX;
this.iLengthBoxY = this.iLengthScaleY;
}
else
{
this.iLengthBoxX = (int)(this.iLengthScaleX * 0.025);
this.iLengthBoxY = (int)(this.iLengthScaleY * 0.025);
}
}
#endregion Plotting Functions
}
}<file_sep>namespace ExpressionPlotterControl
{
public interface IEvaluatable
{
/// <summary>
/// Should return text for the expression
/// </summary>
string ExpressionText
{
get;
set;
}
/// <summary>
/// Should return true if the expression is valid and can be evaluated
/// </summary>
bool IsValid
{
get;
}
///<summary>This method should evaluate the expression and return the result as double. It should return double.NaN in the case the expression cant be evaluated e.g. log( -ve no. )</summary>
///<param name="dvalueX">The value of X at which we want to evaluate the expression</param>
///<returns>The result of expression evaluation as a double</returns>
double Evaluate(double dvalueX);
}
}
|
99121eb7dcf9f43d45d2fa717a2a8613b81603da
|
[
"Markdown",
"C#"
] | 4
|
Markdown
|
LongDuongBIT/ExpressionPlotter
|
306b8bcade08f1b647900bd881d3c3135c1f9fa8
|
62a16b870108cd459283b7e07d3655630e4e4a26
|
refs/heads/master
|
<repo_name>shahinahmadi/Magnetic_field_calculation<file_sep>/Magneticfield1.C
// This code is written to calculate the magnitude of magnetic field in the vicinity of the square Helmholtz coil
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <cstdio>
#include "TGraph.h"
#include <iostream>
#include<math.h>
#include "TH2.h"
#include "TMath.h"
using namespace std;
void Graph(){
double x, dx;
double y, dy;
double constant,z,L;
constant=1;
dx=0.1;
dy=0.1;
z=10;
L=1;
vector<double>myvector;
vector<double>myxposition;
vector<double>myyposition;
for (x=0.01; x<0.4; x+=dx){
myxposition.push_back(x);}
for (y=0.01; y<0.4; y+=dy){
myyposition.push_back(y);}
for(x=0.1; x<0.4; x+=dx){
for(y=0.1;y<0.4; y+=dy){
double k=constant*(x*y);
myvector.push_back(k);
}
}
int n=myvector.size();
double B[n];
double P[n];
double T[n];
TH2D* h = new TH2D("MagnetPlot","The magnitude of the magnetic feild produced by the coils ; X;Y",50,0,50,50,0,50);
for(int i=0; i<myxposition.size();i++){P[i]=myxposition.at(i);}
for(int i=0;i<myyposition.size();i++){T[i]=myyposition.at(i);}
for (int i=0;i<myvector.size();i++){
B[i]=myvector.at(i);
cout<<B[i]<<endl;
}
// Calculation of the magnetic field caused by a wire
double_t B1,B2,B3,B4,B_total;
double I=1;
double l=50;
double Pi=3.14;
int N=100;
double mu_0=1.25663743*pow(10,-6);
for(int x=1;x<50; x++){
for(int y=1; y<50; y++){
B1=(mu_0*I*N/4*Pi*sqrt(pow(y,2)+pow(z,2)))*(sin(atan(sqrt(pow(x,2)+pow(y,2))/z))+sin(atan(sqrt(pow((l-x),2)+pow(y,2))/z)));
B2=(mu_0*I*N/4*Pi*sqrt(pow((l-x),2)+pow(z,2)))*(sin(atan(sqrt(pow(y,2)+pow((l-x),2)))/z)+sin(atan(sqrt(pow((l-y),2)+pow((l-x),2))/z)));
B3=(mu_0*I*N/4*Pi*sqrt(pow((l-y),2)+pow(z,2)))*(sin(atan(sqrt(pow((l-x),2)+pow((l-y),2))/z))+sin(atan(sqrt(pow(x,2)+pow((l-y),2))/z)));
B4=(mu_0*I*N/4*Pi*sqrt(pow(x,2)+pow(z,2)))*(sin(atan(sqrt(pow((l-y),2)+pow(x,2)))/z)+sin(atan(sqrt(pow(y,2)+pow(x,2))/z)));
B_total=B1+B2+B3+B4;
h->Fill(x,y,B_total);
}
}
h->Draw("colz");
}
<file_sep>/Magneticfield2.C
// This code is written to calculate the magnitude of magnetic field in the vicinity of the square Helmholtz coil
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <cstdio>
#include "TGraph.h"
#include <iostream>
#include<math.h>
#include "TH2.h"
#include "TMath.h"
using namespace std;
void Graph2D(){
double x, dx;
double y, dy;
double constant,z,L;
constant=1;
dx=0.1;
dy=0.1;
z=1000;
L=1;
vector<double>myvector;
vector<double>myxposition;
vector<double>myyposition;
for (x=0.01; x<0.4; x+=dx){
myxposition.push_back(x);}
for (y=0.01; y<0.4; y+=dy){
myyposition.push_back(y);}
for(x=0.1; x<0.4; x+=dx){
for(y=0.1;y<0.4; y+=dy){
double k=constant*(x*y);
myvector.push_back(k);
}
}
int n=myvector.size();
double B[n];
double P[n];
double T[n];
TH2D* h = new TH2D("MagnetPlot","The magnitude of the magnetic feild produced by the coils ; X;Y",50,0,50,50,0,50);
for(int i=0; i<myxposition.size();i++){P[i]=myxposition.at(i);}
for(int i=0;i<myyposition.size();i++){T[i]=myyposition.at(i);}
for (int i=0;i<myvector.size();i++){
B[i]=myvector.at(i);
cout<<B[i]<<endl;
}
// Calculation of the magnetic field caused by a wire
double_t B1,B2,B3,B4,B_total;
double I=1;
double l=50;
double Pi=3.14;
int N=100;
double mu_0=1.25663743*pow(10,-6);
for(int x=1;x<50; x++){
for(int y=1; y<50; y++){
//b=((mu_0*I*y*l)/(4*Pi*pow((y*y+z*z),1.5)))*(sin(x/y)+sin(x/(2*y)));
B1=(mu_0*I*N/4*Pi*y)*(sin(atan(x/y))+sin(atan((l-x)/y)));
B2=(mu_0*I*N/4*Pi*(l-x))*(sin(atan(y/(l-x)))+sin(atan((l-y)/(l-x))));
B3=(mu_0*I*N/4*Pi*(l-y))*(sin(atan((l-x)/(l-y)))+sin(atan(x/(l-y))));
B4=(mu_0*I*N/4*Pi*x)*(sin(atan((l-y)/x))+sin(atan(y/x)));
B_total=B1+B2+B3+B4;
h->Fill(x,y,B_total);
}
}
h->Draw("colz");
}
|
20ee575d2d0f43e6a408df71368b59f288e2b293
|
[
"C"
] | 2
|
C
|
shahinahmadi/Magnetic_field_calculation
|
16ff71e755cf1ff4e3f603d216bf1bcccf6000a2
|
207c9158c58839f28bb6a48ce9a1d62e9e91f8b9
|
refs/heads/master
|
<repo_name>sayadaazami/phpspec-test<file_sep>/phpspec-test/src/Calculator.php
<?php
namespace Predmond\Calculator;
use Predmond\Calculator\DivisionByZeroException;
class Calculator
{
public function add($x, $y){
return $x + $y;
}
public function divide($x, $y)
{
if ($y === 0) {
throw new DivisionByZeroException();
}
return $x / $y;
}
}
<file_sep>/phpspec-test/README.md
[Documentation](https://laravel-news.com/testing-with-phpspec)
### Install PHPSPEC
```bash
$ composer init
$ composer require --dev phpspec/phpspec
```
#### Add Autoloader To ***composer.json***
```json
{
"name": "predmond/calculator-phpspec",
"require": {},
"require-dev": {
"phpspec/phpspec": "^4.0"
},
"autoload": {
"psr-4": {
"Predmond\\Calculator\\": "src/"
}
}
}
```
#### Config Suite
```yaml
suites:
default:
namespace: Predmond\Calculator
psr4_prefix: Predmond\Calculator
formatter.name: pretty
```
### The Workflow
> Our workflow with PhpSpec will typically look like the following steps:
1. Describe a Specification
2. Run the Specification (Create the class if it doesn’t exist)
3. Write an expected behavior
4. Run the specification (create the method if it doesn’t exist)
5. Write the implementation
6. Verify the behavior
7. Repeat
#### Create Suite
> ./vendor/bin/phpspec describe Predmond/Calculator/Calculator
#### Run Test
> ./vendor/bin/phpspec run
|
a17aa54541929119e24a0472b291e73106d25491
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
sayadaazami/phpspec-test
|
b3e782f8557116fca8532cb69fba27012cff52fe
|
7dc5a0e8fe2d2ee723561beec7a5d73aa67332d3
|
refs/heads/master
|
<repo_name>W3Max/koco-router<file_sep>/src/router.js
// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
define(['jquery', 'knockout-utilities', 'knockout', 'lodash', 'byroads', 'router-state', './router-event',
'./context', './route'
],
function($, koUtilities, ko, _, byroads, RouterState, RouterEvent, Context, Route) {
'use strict';
function Router() {
var self = this;
//TODO: Créer une instance de byroads au lieu d'utiliser la static...
koUtilities.registerComponent('router', {
basePath: 'bower_components/koco-router/src'
});
self.context = ko.observable(null);
self._pages = {};
self.navigating = new RouterEvent();
self.cachedPages = {};
self._navigatingTask = null;
self._internalNavigatingTask = null;
self.isNavigating = ko.observable(false);
self.isActivating = ko.observable(false);
configureRouting(self);
self.settings = {
baseUrl: '/'
};
self.routerState = new RouterState(self);
}
Router.prototype.init = function(settings) {
var self = this;
self.settings = $.extend({}, self.settings, settings || {});
self.$document = $(document);
return self.routerState.init();
};
Router.prototype.registerPage = function(name, pageConfig) {
var self = this;
pageConfig = pageConfig || {};
if (!name) {
throw new Error('Router.registerPage - Argument missing exception: name');
}
if (self.isRegisteredPage(name)) {
throw new Error('Router.registerPage - Duplicate page: ' + name);
}
var page = {
withActivator: false,
activatorPath: '',
name: name,
title: pageConfig.title || ''
};
if (pageConfig.hasOwnProperty('withActivator') && typeof pageConfig.withActivator === 'boolean') {
page.withActivator = pageConfig.withActivator;
}
if (pageConfig.hasOwnProperty('activatorPath') && typeof pageConfig.activatorPath === 'string') {
page.activatorPath = pageConfig.activatorPath;
}
var componentConfig = buildComponentConfigFromPageConfig(name, pageConfig);
var koConfig = koUtilities.registerComponent(componentConfig.name, componentConfig);
page.componentName = componentConfig.name;
page.require = koConfig.require;
this._pages[name] = page;
};
Router.prototype.isRegisteredPage = function(name) {
return name in this._pages;
};
Router.prototype._getRegisteredPage = function(name) {
return this._pages[name];
};
Router.prototype.addRoute = function(pattern, routeConfig) {
var self = this;
routeConfig = routeConfig || {};
//TODO: Valider que page exist else throw...
var params = {}; //Not to be confused with url params extrated by byroads.js
var pageName = pattern;
var pageTitle = '';
var cached = false;
if (routeConfig.hasOwnProperty('cached') && typeof routeConfig.cached === 'boolean') {
cached = routeConfig.cached;
}
if (routeConfig.hasOwnProperty('pageTitle') &&
(typeof routeConfig.pageTitle === 'string' || routeConfig.pageTitle instanceof String)) {
pageTitle = routeConfig.pageTitle;
}
if (routeConfig.hasOwnProperty('params') &&
(typeof routeConfig.params === 'object' ||
routeConfig.params instanceof Object)) {
params = routeConfig.params;
}
if (routeConfig.hasOwnProperty('pageName') &&
(typeof routeConfig.pageName === 'string' || routeConfig.pageName instanceof String)) {
pageName = routeConfig.pageName;
}
if (!self.isRegisteredPage(pageName)) {
throw new Error('Router.addRoute - The page \'' + pageName + '\' is not registered. Please register the page before adding a route that refers to it.');
}
var priority;
if (routeConfig && routeConfig.priority) {
priority = routeConfig.priority;
}
var route = byroads.addRoute(pattern, priority);
//TODO: Lier la page tout de suite au lieu de le faire à chaque fois qu'on crée un Route
route.params = params;
route.pageName = pageName;
route.pageTitle = pageTitle;
route.cached = cached;
};
//Cette méthode peut être overriden au besoin par le end user
Router.prototype.unknownRouteHandler = function() {
//var self = this;
//TODO: Bon format d'url - ou ca prend le #/ ???
//self.navigate('page-non-trouvee');
alert('404 - Please override the router.unknownRouteHandler function to handle unknown routes.');
};
//Cette méthode peut être overriden au besoin par le end user
Router.prototype.fail = function() {
//var self = this;
alert('404 - Please override the router.fail function to handle routing failure.');
};
//Cette méthode peut être overriden au besoin par le end user
Router.prototype.guardRoute = function( /*matchedRoute, newUrl*/ ) {
//var self = this;
return true;
};
//Cette méthode peut être overriden au besoin par le end user
Router.prototype.getPrioritizedRoute = function(matchedRoutes /*, newUrl*/ ) {
//var self = this;
return matchedRoutes[0];
};
Router.prototype.setPageTitle = function(pageTitle) {
var self = this;
self.$document[0].title = pageTitle;
};
Router.prototype.setUrlSilently = function(options) {
var self = this;
self.routerState.pushState(options);
};
//stateChanged option - for back and foward buttons (and onbeforeunload eventually)
//Dans le cas du back or forward button, l'url doit etre remise sur la stack dans resetUrl
Router.prototype.navigate = function(url, options) {
var self = this;
//so on était déjà en train de naviguer on hijack la premiere navigation (récupère le dfd) et on kill le internalDefered
if (self._internalNavigatingTask && self._internalNavigatingTask.dfd && self._internalNavigatingTask.dfd.state() === 'pending') {
self._internalNavigatingTask.dfd.reject('navigation hijacked');
} else {
self._navigatingTask = new $.Deferred();
}
// return new $.Deferred(function(dfd) {
// try {
// } catch (err) {
// dfd.reject(err);
// }
// }).promise();
setTimeout(function() {
var defaultOptions = {
replace: false,
stateChanged: false,
force: false
};
options = $.extend(defaultOptions, options || {});
self._internalNavigatingTask = {
dfd: new $.Deferred(),
options: options
};
self._internalNavigatingTask.dfd
.done(function(context) {
if (context) {
var pushStateOptions = toPushStateOptions(self, context, self._internalNavigatingTask.options);
self.routerState.pushState(pushStateOptions);
var previousContext = self.context();
if (previousContext && previousContext.route.cached) {
self.cachedPages[previousContext.route.url] = previousContext;
}
context.isDialog = false;
self.context(context);
self.setPageTitle(context.pageTitle);
}
self._navigatingTask.resolve.apply(this, arguments);
self._navigatingTask = null;
self._internalNavigatingTask = null;
self.isNavigating(false);
})
.fail(function(reason) {
if (reason !== 'navigation hijacked') {
resetUrl(self);
self._navigatingTask.reject.apply(this, arguments);
self._navigatingTask = null;
self._internalNavigatingTask = null;
self.isNavigating(false);
if (reason == '404') {
//covention pour les 404
//TODO: passer plus d'info... ex. url demandée originalement, url finale tenant comptre de guardRoute
self.unknownRouteHandler();
}
}
});
if (options.force) {
self.isNavigating(true);
self._navigateInner(url, self._internalNavigatingTask.dfd, options);
} else {
self.navigating.canRoute().then(function(can) {
if (can) {
self.isNavigating(true);
self._navigateInner(url, self._internalNavigatingTask.dfd, options);
} else {
resetUrl(self);
self._internalNavigatingTask.dfd.reject('routing cancelled by router.navigating.canRoute');
}
}, function() {
self._internalNavigatingTask.dfd.reject.apply(this, arguments);
});
}
}, 0);
//TODO: S'assurer que canRoute() === false, remet l'url précédente sur back/foward button
return self._navigatingTask.promise();
};
Router.prototype._navigateInner = function(newUrl, dfd, options, context) {
var self = this;
var defaultOptions = {
force: false
};
options = $.extend(defaultOptions, options || {});
if (!context) {
context = new Context();
}
//Replace all (/.../g) leading slash (^\/) or (|) trailing slash (\/$) with an empty string.
var cleanedUrl = newUrl.replace(/^\/|\/$/g, '');
// Remove hash
cleanedUrl = cleanedUrl.replace(/#.*$/g, '');
if (byroads.getNumRoutes() === 0) {
dfd.reject('No route has been added to the router yet.');
return;
}
var matchedRoutes = byroads.getMatchedRoutes(cleanedUrl, true);
var matchedRoute = null;
if (matchedRoutes.length > 0) {
matchedRoute = self.getPrioritizedRoute(convertMatchedRoutes(self, matchedRoutes, newUrl), newUrl);
context.addMatchedRoute(matchedRoute);
}
var guardRouteResult = true;
if (!options.force) {
guardRouteResult = self.guardRoute(matchedRoute, newUrl);
}
if (guardRouteResult === false) {
dfd.reject('guardRoute has blocked navigation.');
return;
} else if (guardRouteResult === true) {
//continue
} else if (typeof guardRouteResult === 'string' || guardRouteResult instanceof String) {
self._navigateInner(guardRouteResult, dfd, options, context);
return;
} else {
dfd.reject('guardRoute has returned an invalid value. Only string or boolean are supported.');
return;
}
if (matchedRoute) {
var previousContext = self.cachedPages[newUrl];
if (previousContext) {
dfd.resolve(previousContext);
} else {
activate(self, context)
.then(function(activatedContext) {
dfd.resolve(activatedContext);
})
.fail(function() {
dfd.reject.apply(this, arguments);
});
}
} else {
dfd.reject('404');
}
};
Router.prototype.currentUrl = function() {
//var self = this;
return window.location.pathname + window.location.search + window.location.hash;
};
function toPushStateOptions(self, context, options) {
if (!context) {
throw new Error('router.toPushStateOptions - context is mandatory');
}
if (!context.route) {
throw new Error('router.toPushStateOptions - context.route is mandatory');
}
return {
url: context.route.url,
pageTitle: context.pageTitle,
stateObject: options.stateObject || {},
replace: options.replace || false
};
}
function resetUrl(self) {
var context = self.context();
if (context) {
var pushStateOptions = toPushStateOptions(self, context, {
replace: !self._internalNavigatingTask.options.stateChanged
});
self.routerState.pushState(pushStateOptions);
}
}
function activate(self, context) {
return new $.Deferred(function(dfd) {
try {
var registeredPage = context.route.page;
if (registeredPage.withActivator) {
getWithRequire(registeredPage.activatorPath || (registeredPage.require + '-activator'), function(activator) {
if (_.isFunction(activator)) {
activator = new activator(context);
}
self.isActivating(true);
activator.activate(context)
.then(function() {
dfd.resolve(context);
})
.fail(function(reason) {
dfd.reject(reason);
})
.always(function() {
self.isActivating(false);
});
});
} else {
dfd.resolve(context);
}
} catch (err) {
dfd.reject(err);
}
}).promise();
}
function configureRouting( /*self*/ ) {
//TODO: Utile?
byroads.normalizeFn = byroads.NORM_AS_OBJECT;
}
//TODO: Allow overriding page-activator in route config
function getWithRequire(moduleName, callback) {
require([moduleName], function(a) {
if (a) {
// dev mode -- one define per file = module
callback(a);
} else {
// optimized file -- 2nd request yields a Require module
require([moduleName], function(x) {
callback(x);
});
}
});
}
function buildComponentConfigFromPageConfig(name, pageConfig) {
var componentConfig = {
name: name + '-page',
type: 'page'
};
if (pageConfig) {
componentConfig.htmlOnly = pageConfig.htmlOnly;
componentConfig.basePath = pageConfig.basePath;
componentConfig.isBower = pageConfig.isBower;
}
return componentConfig;
}
function convertMatchedRoutes(self, matchedRoutes, url) {
var result = [];
for (var i = 0; i < matchedRoutes.length; i++) {
var matchedRoute = matchedRoutes[i];
var page = self._getRegisteredPage(matchedRoute.route.pageName);
var route = new Route(url, matchedRoute, page);
result.push(route);
}
return result;
}
return new Router();
});
|
66fd3c4d0b555300bd28ff95633c26443f2b248e
|
[
"JavaScript"
] | 1
|
JavaScript
|
W3Max/koco-router
|
f359761439801d31e8239474c215c482057fc696
|
6eb964e9e678fba46fc748720858affb829514d5
|
refs/heads/master
|
<file_sep># Go get the data of 9 tables from postgresql into the python kernel as dataframes
# Join all the dataframes as needed
# Dump the final dataframe into a table in the olist_staging schema
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
import logging as logger
def initial_load():
logger.info("Trying to connect to the database")
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@localhost:5032/airflow')
customers_sql = 'select * from olist.orskl_customers'
customers = pd.read_sql(customers_sql, pg_engine)
gelocations_sql = 'select * from olist.orskl_geolocations'
geolocations = pd.read_sql(gelocations_sql, pg_engine)
order_items_sql = 'select * from olist.orskl_order_items'
order_items = pd.read_sql(order_items_sql, pg_engine)
order_payments_sql ='select * from olist.orskl_order_payments'
order_payments = pd.read_sql(order_payments_sql, pg_engine)
order_reviews_sql = 'select * from olist.orskl_order_reviews'
order_reviews = pd.read_sql(order_reviews_sql, pg_engine)
orders_sql = 'select * from olist.orskl_orders'
orders = pd.read_sql(orders_sql, pg_engine)
logger.info(f'The number of records in the order table is {orders}'.format(orders=len(orders)))
products_sql = 'select * from olist.orskl_products'
products = pd.read_sql(products_sql, pg_engine)
sellers_sql = 'select * from olist.orskl_sellers'
sellers = pd.read_sql(sellers_sql, pg_engine)
translation_sql = 'select * from olist.orskl_translation'
translation = pd.read_sql(translation_sql, pg_engine)
olist_final = orders.join(order_items.set_index('order_id'), on='order_id', how='left').\
join(products.set_index('product_id'), on='product_id', how='left').\
join(translation.set_index('product_category_name'), on='product_category_name', how='left').\
join(order_payments.set_index('order_id'), on='order_id', how='left').\
join(customers.set_index('customer_id'), on='customer_id', how='left').\
join(sellers.set_index('seller_id'), on='seller_id', how='left')
geolocations_unique = geolocations[['geolocation_zip_code_prefix','geolocation_lat','geolocation_lng']].\
groupby('geolocation_zip_code_prefix').agg({'geolocation_lat': 'min', 'geolocation_lng':'min'}).reset_index()
olist_final = orders.join(order_items.set_index('order_id'), on='order_id', how='left').\
join(products.set_index('product_id'), on='product_id', how='left').\
join(translation.set_index('product_category_name'), on='product_category_name', how='left').\
join(order_payments.set_index('order_id'), on='order_id', how='left').\
join(customers.set_index('customer_id'), on='customer_id', how='left').\
join(sellers.set_index('seller_id'), on='seller_id', how='left').\
merge(geolocations_unique, how='left', left_on='customer_zip_code_prefix', right_on='geolocation_zip_code_prefix',
suffixes=("_x","_y")).\
merge(geolocations_unique, how='left', left_on='seller_zip_code_prefix', right_on='geolocation_zip_code_prefix').\
merge(order_reviews, how='left', on='order_id')
olist_final.to_sql("orskl_staging_rawdata", con=conn, schema='olist_staging', index=False)
def raw_data_job1_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
customers_sql = 'select * from olist.orskl_customers'
customers = pd.read_sql(customers_sql, pg_engine)
gelocations_sql = 'select * from olist.orskl_geolocations'
geolocations = pd.read_sql(gelocations_sql, pg_engine)
products_sql = 'select * from olist.orskl_products'
products = pd.read_sql(products_sql, pg_engine)
sellers_sql = 'select * from olist.orskl_sellers'
sellers = pd.read_sql(sellers_sql, pg_engine)
translation_sql = 'select * from olist.orskl_translation'
translation = pd.read_sql(translation_sql, pg_engine)
order_max_timestamp_sql = 'select max(order_purchase_timestamp) from olist_staging.orskl_staging_rawdata'
order_max_timestamp = pd.read_sql(order_max_timestamp_sql, pg_engine)
order_max_time = order_max_timestamp['max'][0]
orders_sql = "select * from olist.orskl_orders where order_purchase_timestamp > '"+str(order_max_time)+"'"
orders = pd.read_sql(orders_sql, pg_engine)
order_items_sql = "select * from olist.orskl_order_items where order_id in (select order_id from olist.orskl_orders where order_purchase_timestamp > '"+str(order_max_time)+"')"
order_items = pd.read_sql(order_items_sql, pg_engine)
order_payments_sql = "select * from olist.orskl_order_payments where order_id in (select order_id from olist.orskl_orders where order_purchase_timestamp > '"+str(order_max_time)+"')"
order_payments = pd.read_sql(order_payments_sql, pg_engine)
order_reviews_sql = "select * from olist.orskl_order_reviews where order_id in (select order_id from olist.orskl_orders where order_purchase_timestamp > '"+str(order_max_time)+"')"
order_reviews = pd.read_sql(order_reviews_sql, pg_engine)
geolocations_unique = geolocations[['geolocation_zip_code_prefix', 'geolocation_lat', 'geolocation_lng']]. \
groupby('geolocation_zip_code_prefix').agg({'geolocation_lat': 'min', 'geolocation_lng': 'min'}).reset_index()
olist_final = orders.join(order_items.set_index('order_id'), on='order_id', how='left'). \
join(products.set_index('product_id'), on='product_id', how='left'). \
join(translation.set_index('product_category_name'), on='product_category_name', how='left'). \
join(order_payments.set_index('order_id'), on='order_id', how='left'). \
join(customers.set_index('customer_id'), on='customer_id', how='left'). \
join(sellers.set_index('seller_id'), on='seller_id', how='left'). \
merge(geolocations_unique, how='left', left_on='customer_zip_code_prefix',
right_on='geolocation_zip_code_prefix',
suffixes=("_x", "_y")). \
merge(geolocations_unique, how='left', left_on='seller_zip_code_prefix',
right_on='geolocation_zip_code_prefix'). \
merge(order_reviews, how='left', on='order_id')
olist_final.to_sql("orskl_staging_rawdata", con=conn, schema='olist_staging', index=False, if_exists='append')
olist_attributes = {'earlier_max_timestamp': [order_max_time]}
pd.DataFrame(olist_attributes).to_sql("pipelinetimestamp", con=conn, schema='olist_staging', index=False, if_exists='replace')
# Table 1
# Col1 Col2 Col3
# A B C
# B
#
# Table 2
# Col1 Col4 Col5
# A E F
# A 1 2
# A
# B
# B
# B
# B
#
# Table 1 left join table 2 on col1
#
# col1 col2 col3 col4 col5
# A B C E F
# A B C 1 2
<file_sep># You might install new packages or new infra setup
# python version
# psycopg2
# sqlalchemy
# pandas
# haversine
<file_sep>import pandas as pd
from sqlalchemy import create_engine
import psycopg2
def job7_table1():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
raw_data_sql = 'select * from olist_staging.orskl_staging_rawdata'
raw_data = pd.read_sql(raw_data_sql, pg_engine)
reviews_data = raw_data.groupby(['product_category_name_english']).\
agg({'review_score':'mean', 'order_purchase_timestamp':'max'}).reset_index()
reviews_data.to_sql('orskl_olist_reviews_tab1', con=conn, schema='olist_review_mart',index=False)
def job7_table1_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
get_max_time_sql = 'select * from olist_staging.pipelinetimestamp'
max_date = pd.read_sql(get_max_time_sql, pg_engine)
order_max_time = max_date['earlier_max_timestamp'][0]
raw_data_sql = "select * from olist_staging.orskl_staging_rawdata where order_purchase_timestamp > '" + str(
order_max_time) + "'"
raw_data = pd.read_sql(raw_data_sql, pg_engine)
reviews_data = raw_data.groupby(['product_category_name_english']).\
agg({'review_score':'mean', 'order_purchase_timestamp':'max'}).reset_index()
reviews_data.to_sql('orskl_olist_reviews_tab1', con=conn, schema='olist_review_mart',index=False, if_exists='append')
<file_sep>import pandas as pd
from sqlalchemy import create_engine
import psycopg2
from haversine import haversine
def job6_table1():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
raw_data_sql = 'select * from olist_staging.orskl_staging_rawdata'
raw_data = pd.read_sql(raw_data_sql, pg_engine)
raw_data['distance'] = raw_data[['order_id','seller_id','customer_id','geolocation_lat_x',
'geolocation_lat_y', 'geolocation_lng_x','geolocation_lng_y']].\
apply(lambda x: haversine((float(x['geolocation_lat_x']),float(x['geolocation_lng_x'])),
(float(x['geolocation_lat_y']),float(x['geolocation_lng_y'])))
if (x['geolocation_lat_x'] and x['geolocation_lng_x'] and x['geolocation_lat_y'] and x['geolocation_lng_y']) else ''
,axis=1)
raw_data[['order_id','seller_id','customer_id','distance']].to_sql('orskl_olist_geo_tab1', con=conn, schema='olist_geo_mart',index=False)
def job6_table1_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
get_max_time_sql = 'select * from olist_staging.pipelinetimestamp'
max_date = pd.read_sql(get_max_time_sql, pg_engine)
order_max_time = max_date['earlier_max_timestamp'][0]
raw_data_sql = "select * from olist_staging.orskl_staging_rawdata where order_purchase_timestamp > '" + str(
order_max_time) + "'"
raw_data = pd.read_sql(raw_data_sql, pg_engine)
# Below distance computation should be done only if raw_data dataframe is non empty.
# This will avoid the errors we have seen when the pipeline was executed & there is no new data to process
raw_data['distance'] = raw_data[['order_id','seller_id','customer_id','geolocation_lat_x',
'geolocation_lat_y', 'geolocation_lng_x','geolocation_lng_y']].\
apply(lambda x: haversine((float(x['geolocation_lat_x']),float(x['geolocation_lng_x'])),
(float(x['geolocation_lat_y']),float(x['geolocation_lng_y'])))
if (x['geolocation_lat_x'] and x['geolocation_lng_x'] and x['geolocation_lat_y'] and x['geolocation_lng_y']) else ''
,axis=1)
raw_data[['order_id','seller_id','customer_id','distance']].to_sql('orskl_olist_geo_tab1', con=conn, schema='olist_geo_mart',index=False, if_exists='append')
<file_sep># Go get the data of 9 tables from postgresql into the python kernel as dataframes
# Join all the dataframes as needed
# Dump the final dataframe into a table in the olist_staging schema
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
pg_engine = psycopg2.connect(dbname='airflow', host='localhost', port=5032, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@localhost:5032/airflow')
customers_sql = 'select * from olist.orskl_customers'
customers = pd.read_sql(customers_sql, pg_engine)
gelocations_sql = 'select * from olist.orskl_geolocations'
geolocations = pd.read_sql(gelocations_sql, pg_engine)
order_items_sql = 'select * from olist.orskl_order_items'
order_items = pd.read_sql(order_items_sql, pg_engine)
order_payments_sql ='select * from olist.orskl_order_payments'
order_payments = pd.read_sql(order_payments_sql, pg_engine)
order_reviews_sql = 'select * from olist.orskl_order_reviews'
order_reviews = pd.read_sql(order_reviews_sql, pg_engine)
orders_sql = 'select * from olist.orskl_orders'
orders = pd.read_sql(orders_sql, pg_engine)
products_sql = 'select * from olist.orskl_products'
products = pd.read_sql(products_sql, pg_engine)
sellers_sql = 'select * from olist.orskl_sellers'
sellers = pd.read_sql(sellers_sql, pg_engine)
translation_sql = 'select * from olist.orskl_translation'
translation = pd.read_sql(translation_sql, pg_engine)
olist_final = orders.join(order_items.set_index('order_id'), on='order_id', how='left').\
join(products.set_index('product_id'), on='product_id', how='left').\
join(translation.set_index('product_category_name'), on='product_category_name', how='left').\
join(order_payments.set_index('order_id'), on='order_id', how='left').\
join(customers.set_index('customer_id'), on='customer_id', how='left').\
join(sellers.set_index('seller_id'), on='seller_id', how='left').\
merge(geolocations, how='left',
left_on='customer_zip_code_prefix', right_on='geolocation_zip_code_prefix', suffixes=('','_customer'))
geolocations_computed = geolocations.groupby('geolocation_zip_code_prefix').agg({'geolocation_lat':'min', 'geolocation_lng':'min'}).reset_index()
geolocations.columns
pd.to_datetime(orders['order_purchase_timestamp'], format='%Y-%m-%d %H:%M:%S').\
apply(lambda x: str(x.year)+str("{:02}".format(x.weekofyear)))
# Job 2
rawdata_sql = 'select * from olist_staging.orskl_olist_rawdata'
rawdata = pd.read_sql(rawdata_sql, pg_engine)
data_path = '/Users/pawanyaddanapudi/GDrive_kumar_OrSkl/OrSklDataAnalytics/BigDataEngineering/BigDataEngineeringBooster/datasets/YouTubeTrendingVideos/'
CA_df = pd.read_csv(data_path+'CAvideos.csv', header=0)
CA_df['trending_date'] = pd.to_datetime(CA_df['trending_date'], format='%y.%d.%m')
CA_df_2017 = CA_df[CA_df['trending_date']<'2018-01-01']
CA_df_2018_1 = CA_df[(CA_df['trending_date']>='2018-01-01') & (CA_df['trending_date']<'2018-04-01')]
CA_df_2018_2 = CA_df[CA_df['trending_date']>='2018-04-01']
CA_df_2017.to_csv(data_path+'CAvideos_2017.csv',index=False, header=False)
CA_df_2018_1.to_csv(data_path+'CAvideos_2018_1.csv',index=False, header=False)
CA_df_2018_2.to_csv(data_path+'CAvideos_2018_2.csv',index=False, header=False)
DE_df = pd.read_csv(data_path+'DEvideos.csv', header=0)
DE_df['trending_date'] = pd.to_datetime(DE_df['trending_date'], format='%y.%d.%m')
DE_df_2017 = DE_df[DE_df['trending_date']<'2018-01-01']
DE_df_2018_1 = DE_df[(DE_df['trending_date']>='2018-01-01') & (DE_df['trending_date']<'2018-04-01')]
DE_df_2018_2 = DE_df[DE_df['trending_date']>='2018-04-01']
DE_df_2017.to_csv(data_path+'DEvideos_2017.csv',index=False, header=False)
DE_df_2018_1.to_csv(data_path+'DEvideos_2018_1.csv',index=False, header=False)
DE_df_2018_2.to_csv(data_path+'DEvideos_2018_2.csv',index=False, header=False)
FR_df = pd.read_csv(data_path+'DEvideos.csv', header=0)
FR_df['trending_date'] = pd.to_datetime(FR_df['trending_date'], format='%y.%d.%m')
FR_df_2017 = FR_df[FR_df['trending_date']<'2018-01-01']
FR_df_2018_1 = FR_df[(FR_df['trending_date']>='2018-01-01') & (FR_df['trending_date']<'2018-04-01')]
FR_df_2018_2 = FR_df[FR_df['trending_date']>='2018-04-01']
FR_df_2017.to_csv(data_path+'FRvideos_2017.csv',index=False, header=False)
FR_df_2018_1.to_csv(data_path+'FRvideos_2018_1.csv',index=False, header=False)
FR_df_2018_2.to_csv(data_path+'FRvideos_2018_2.csv',index=False, header=False)
from datetime import datetime
print(datetime.now().strftime('%y-%m-%d'))<file_sep># Python function to read data or write data or delete data from postgres sql<file_sep>import pandas as pd
data_path = '/Users/pawanyaddanapudi/GDrive_kumar_OrSkl/OrSklDataAnalytics/BigDataEngineering/BigDataEngineeringBooster/datasets/OlistECommerce/'
#pd.to_datetime(orskl_orders['order_purchase_timestamp'], format='%Y-%m-%d %H:%M:%S').\
# apply(lambda x: str(x.year)+str("{:02}".format(x.weekofyear)))
#pd.to_datetime(orskl_orders['order_purchase_timestamp'], format='%Y-%m-%d %H:%M:%S').dt.week.apply(lambda x: "{:02}".format(x))
orskl_orders = pd.read_csv(data_path+'olist_orders_dataset.csv', header=0)
orskl_orders['order_purchase_timestamp'] = pd.to_datetime(orskl_orders['order_purchase_timestamp'], format='%Y-%m-%d %H:%M:%S')
orskl_orders_20162017 = orskl_orders[orskl_orders['order_purchase_timestamp'] < '2018-01-01']
orskl_orders_2018_1 = orskl_orders[(orskl_orders['order_purchase_timestamp'] >= '2018-01-01') & (orskl_orders['order_purchase_timestamp'] < '2018-07-01')]
orskl_orders_2018_2 = orskl_orders[(orskl_orders['order_purchase_timestamp'] >= '2018-07-01')]
orskl_orders_20162017.to_csv(data_path+'olist_orders_dataset_20162017.csv', index=False)
orskl_orders_2018_1.to_csv(data_path+'olist_orders_dataset_2018_1.csv', index=False)
orskl_orders_2018_2.to_csv(data_path+'olist_orders_dataset_2018_2.csv', index=False)
orskl_orders_items = pd.read_csv(data_path+'olist_order_items_dataset.csv', header=0)
orskl_orders_items_20162017 = orskl_orders_items[orskl_orders_items['order_id'].isin(orskl_orders_20162017['order_id'])]
orskl_orders_items_2018_1 = orskl_orders_items[orskl_orders_items['order_id'].isin(orskl_orders_2018_1['order_id'])]
orskl_orders_items_2018_2 = orskl_orders_items[orskl_orders_items['order_id'].isin(orskl_orders_2018_2['order_id'])]
orskl_orders_items_20162017.to_csv(data_path+'olist_orders_items_dataset_20162017.csv', index=False)
orskl_orders_items_2018_1.to_csv(data_path+'olist_orders_items_dataset_2018_1.csv', index=False)
orskl_orders_items_2018_2.to_csv(data_path+'olist_orders_items_dataset_2018_2.csv', index=False)
orskl_reviews = pd.read_csv(data_path+'olist_order_reviews_dataset.csv', header=0)
orskl_reviews['review_creation_date'] = pd.to_datetime(orskl_reviews['review_creation_date'], format='%Y-%m-%d %H:%M:%S')
orskl_reviews_20162017 = orskl_reviews[orskl_reviews['review_creation_date'] < '2018-01-01']
orskl_reviews_2018_1 = orskl_reviews[(orskl_reviews['review_creation_date'] >= '2018-01-01') & (orskl_reviews['review_creation_date'] < '2018-07-01')]
orskl_reviews_2018_2 = orskl_reviews[(orskl_reviews['review_creation_date'] >= '2018-07-01')]
orskl_reviews_20162017[['review_id','order_id','review_score','review_creation_date','review_answer_timestamp']].to_csv(data_path+'olist_order_reviews_dataset_20162017.csv', index=False, encoding="utf-8-sig")
orskl_reviews_2018_1[['review_id','order_id','review_score','review_creation_date','review_answer_timestamp']].to_csv(data_path+'olist_order_reviews_dataset_2018_1.csv', index=False)
orskl_reviews_2018_2[['review_id','order_id','review_score','review_creation_date','review_answer_timestamp']].to_csv(data_path+'olist_order_reviews_dataset_2018_2.csv', index=False)
orskl_payments = pd.read_csv(data_path+'olist_order_payments_dataset.csv', header=0)
orskl_payments_20162017 = orskl_payments[orskl_payments['order_id'].isin(orskl_orders_20162017['order_id'])]
orskl_payments_2018_1 = orskl_payments[orskl_payments['order_id'].isin(orskl_orders_2018_1['order_id'])]
orskl_payments_2018_2 = orskl_payments[orskl_payments['order_id'].isin(orskl_orders_2018_2['order_id'])]
orskl_payments_20162017.to_csv(data_path+'olist_order_payments_dataset_20162017.csv', index=False)
orskl_payments_2018_1.to_csv(data_path+'olist_order_payments_dataset_2018_1.csv', index=False)
orskl_payments_2018_2.to_csv(data_path+'olist_order_payments_dataset_2018_2.csv', index=False)
<file_sep>from airflow.models.dag import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
from airflow.utils.dates import days_ago
from jobs.raw_load_job1 import job1_table1
from jobs.customers_mart import *
from jobs.reviews_mart import *
import sys
sys.path.insert(0, "/home/myname/pythonfiles")
default_args = {
'depends_on_past': False,
'email': ['<EMAIL>'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5)
}
with DAG(
'OlistDataPipeline',
default_args=default_args,
start_date=datetime(2021,5,30,4,30,00),
tags=['python', 'pipeline','olist'],
) as dag:
t1 = PythonOperator(
task_id = 'rawload',
#bash_command='. /opt/airflow/script1.bash'
python_callable=script1
)
t2 = PythonOperator(
task_id='script2',
#bash_command='python /opt/airflow/script2.py'
python_callable=script2
)
t3 = PythonOperator(
task_id='script3',
#bash_command='python /opt/airflow/script3.py'
python_callable=script3
)
[t1, t2] >> t3
<file_sep>import pandas as pd
from sqlalchemy import create_engine
import psycopg2
def job2_table1_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
get_max_time_sql = 'select * from olist_staging.pipelinetimestamp'
max_date = pd.read_sql(get_max_time_sql, pg_engine)
order_max_time = max_date['earlier_max_timestamp'][0]
raw_data_sql = "select * from olist_staging.orskl_staging_rawdata where order_purchase_timestamp > '" +str(order_max_time)+"'"
raw_data = pd.read_sql(raw_data_sql, pg_engine)
raw_data['yearweek'] = raw_data['order_purchase_timestamp'].apply(lambda x: str(x.year)+str("{:02}".format(x.weekofyear)))
table1 = raw_data[['yearweek','seller_id','product_category_name_english','customer_id','order_item_id','price',
'freight_value']].groupby(['yearweek','seller_id','product_category_name_english','customer_id']).\
agg({'order_item_id':'sum', 'price':'sum', 'freight_value':'sum'}).rename(columns={'order_item_id':'itemssold','price':'total_price'}).\
reset_index()
table1['total_margin'] = table1['total_price'] - table1['freight_value']
table1.to_sql("orskl_olist_cust_sales_tab1", con=conn, schema='olist_cust_sales_mart', index=False, if_exists='append')
def job2_table1():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
raw_data_sql = 'select * from olist_staging.orskl_staging_rawdata'
raw_data = pd.read_sql(raw_data_sql, pg_engine)
raw_data['yearweek'] = raw_data['order_purchase_timestamp'].apply(lambda x: str(x.year)+str("{:02}".format(x.weekofyear)))
table1 = raw_data[['yearweek','seller_id','product_category_name_english','customer_id','order_item_id','price',
'freight_value']].groupby(['yearweek','seller_id','product_category_name_english','customer_id']).\
agg({'order_item_id':'sum', 'price':'sum', 'freight_value':'sum'}).rename(columns={'order_item_id':'itemssold','price':'total_price'}).\
reset_index()
table1['total_margin'] = table1['total_price'] - table1['freight_value']
table1.to_sql("orskl_olist_cust_sales_tab1", con=conn, schema='olist_cust_sales_mart', index=False)
def job3_table2():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table2 = sales_data.groupby(['yearweek','seller_id']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table2.to_sql("orskl_olist_cust_sales_tab2", con=conn, schema='olist_cust_sales_mart', index=False)
def job3_table2_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table2 = sales_data.groupby(['yearweek','seller_id']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table2.to_sql("orskl_olist_cust_sales_tab2", con=conn, schema='olist_cust_sales_mart', index=False, if_exists='append')
def job4_table3():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table3 = sales_data.groupby(['yearweek','seller_id','product_category_name_english']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table3.to_sql("orskl_olist_cust_sales_tab3", con=conn, schema='olist_cust_sales_mart', index=False)
def job4_table3_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table3 = sales_data.groupby(['yearweek','seller_id','product_category_name_english']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table3.to_sql("orskl_olist_cust_sales_tab3", con=conn, schema='olist_cust_sales_mart', index=False, if_exists='append')
def job5_table4():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table4 = sales_data.groupby(['yearweek','customer_id']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table4.to_sql("orskl_olist_cust_sales_tab4", con=conn, schema='olist_cust_sales_mart', index=False)
def job5_table4_inc():
pg_engine = psycopg2.connect(dbname='airflow', host='postgres', port=5432, user='airflow', password='<PASSWORD>')
conn = create_engine('postgresql://airflow:airflow@postgres/airflow')
sales_data_sql = 'select * from olist_cust_sales_mart.orskl_olist_cust_sales_tab1'
sales_data = pd.read_sql(sales_data_sql, pg_engine)
table4 = sales_data.groupby(['yearweek','customer_id']).agg({'itemssold':'sum', 'total_price':'sum', 'total_margin':'sum'}).\
reset_index()
table4.to_sql("orskl_olist_cust_sales_tab4", con=conn, schema='olist_cust_sales_mart', index=False, if_exists='append')<file_sep>from airflow.models.dag import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
import sys
sys.path.insert(0, "/opt/airflow/olistecommerce/")
from jobs.raw_load_job1 import *
from jobs.customers_mart import *
from jobs.geographics_mart import *
from jobs.reviews_mart import *
default_args = {
'depends_on_past': False,
'email': ['<EMAIL>'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5)
}
with DAG(
'OlistDataPipeline',
default_args=default_args,
start_date=datetime(2021,6,11,5,55,00),
tags=['python', 'pipeline','olist'],
) as dag:
job1_raw = PythonOperator(
task_id='RawDataLoad',
python_callable=raw_data_job1_inc
)
job2_table1 = PythonOperator(
task_id='CustSalesLoad1',
# bash_command='python /opt/airflow/script2.py'
python_callable=job2_table1_inc
)
job3_table2 = PythonOperator(
task_id='CustSalesLoad2',
# bash_command='python /opt/airflow/script3.py'
python_callable=job3_table2_inc
)
job4_table3 = PythonOperator(
task_id='CustSalesLoad3',
# bash_command='python /opt/airflow/script3.py'
python_callable=job4_table3_inc
)
job5_table4 = PythonOperator(
task_id='CustSalesLoad4',
# bash_command='python /opt/airflow/script3.py'
python_callable=job5_table4_inc
)
job6_geo = PythonOperator(
task_id='GeoLoad',
# bash_command='python /opt/airflow/script3.py'
python_callable=job6_table1_inc
)
job7_review = PythonOperator(
task_id='ReviewLoad',
# bash_command='python /opt/airflow/script3.py'
python_callable=job7_table1_inc
)
job1_raw >> [job2_table1, job6_geo, job7_review]
job2_table1 >> [job3_table2, job4_table3, job5_table4]
|
c4bff7cff8d8878a51ed05ec2676942214b2b34e
|
[
"Python",
"Text"
] | 10
|
Python
|
pawanyaddanapudi/olistecommerce
|
6451dc936469cac888d1521d3157427bf39b3445
|
50f9347006692e4474d38cbab9adb7a1f64c1413
|
refs/heads/master
|
<file_sep>package com.example.quizgame;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
public class Quiz5Activity extends AppCompatActivity {
private static final long countdownTime = 30000; // 30 second timer
private TextView scoreView;
private TextView timerView;
private CheckBox answer1;
private CheckBox answer2;
private CheckBox answer3;
private CheckBox answer4;
private CheckBox answer5;
private Button confirm;
private int score = 0;
private CountDownTimer timer;
private long timeLeft;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz5);
scoreView = findViewById(R.id.scoreNum);
timerView = findViewById(R.id.timer);
answer1 = findViewById(R.id.answer1);
answer2 = findViewById(R.id.answer2);
answer3 = findViewById(R.id.answer3);
answer4 = findViewById(R.id.answer4);
answer5 = findViewById(R.id.answer5);
confirm = findViewById(R.id.confirm);
// Get score
Intent intent = getIntent();
int points = intent.getIntExtra("score", 0);
scoreView.setText("" + points);
score = points;
timeLeft = countdownTime;
countdown();
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
confirmAnswerDialog();
}
});
}
private void confirmAnswerDialog(){
LayoutInflater confirmDialogInflater = LayoutInflater.from(getApplicationContext());
View view = confirmDialogInflater.inflate(R.layout.confirm_dialog, null);
AlertDialog.Builder userConfirm = new AlertDialog.Builder(this);
userConfirm.setView(view);
userConfirm
.setCancelable(false)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("Go back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = userConfirm.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer();
}
});
}
private void checkAnswer(){
timer.cancel();
if(answer1.isChecked() && answer3.isChecked() && answer4.isChecked() && answer5.isChecked() ) {
score++;
updateScore(score);
Toast.makeText(Quiz5Activity.this, "Correct! Great job! :)", Toast.LENGTH_SHORT).show();
// Goes to next page
Intent intent = new Intent(Quiz5Activity.this, ResultsActivity.class);
intent.putExtra("score", score); // pass the current score to results
startActivity(intent);
finish();
} else {
Toast.makeText(Quiz5Activity.this, "Incorrect! The answers are: <NAME>," +
" <NAME> Jr, <NAME>, and <NAME>",
Toast.LENGTH_SHORT).show();
updateScore(score);
// Goes to next page
Intent intent = new Intent(Quiz5Activity.this, ResultsActivity.class);
intent.putExtra("score", score); // pass the current score to results
startActivity(intent);
finish();
}
}
// Updates score
private void updateScore(int pt) {
scoreView.setText("" + score);
}
// Countdown timer --> user has 30 seconds to answer
// If timer runs out, answer is checked and then goes to next question
private void countdown(){
timer = new CountDownTimer(timeLeft, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateTimerView();
}
@Override
public void onFinish() {
timeLeft = 0;
updateTimerView();
checkAnswer();
}
}.start();
}
// Update timer
private void updateTimerView() {
int seconds = (int) (timeLeft / 1000) % 60;
String timeSeconds = String.format(Locale.getDefault(), "%d seconds left", seconds);
timerView.setText(timeSeconds); // displays seconds countdown
// less than 5 seconds remaining, change text color to red
if (timeLeft < 5000) {
timerView.setTextColor(Color.RED);
} else if (timeLeft < 10000) { // less than 10 seconds = yellow text
timerView.setTextColor(Color.YELLOW);
} else { // green text
timerView.setTextColor(Color.GREEN);
}
}
}<file_sep>package com.example.quizgame;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
public class LoginActivity extends AppCompatActivity {
private TextInputLayout pw;
private TextInputLayout un;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
pw = (TextInputLayout) findViewById(R.id.enterPW);
un = (TextInputLayout) findViewById(R.id.enterUser);
btnLogin = (Button) findViewById(R.id.Complete);
pw.getEditText().addTextChangedListener(myTextWatcher);
un.getEditText().addTextChangedListener(myTextWatcher);
btnLogin.setEnabled(false); // Disables login button to start
}
// Validates password
// Password = <PASSWORD>
private boolean passwordValidate() {
String password = pw.getEditText().getText().toString();
String acceptPW = "<PASSWORD>"; // Hardcoded password
// Checks if entered username is "testing123"
if (!password.equals(acceptPW)) {
return false;
} else {
return true;
}
}
// Validates username
// Username = montclair
private boolean usernameValidate() {
String username = un.getEditText().getText().toString();
String acceptUN = "montclair"; // Hardcoded username
// Checks if entered username is "montclair"
if (!username.equals(acceptUN)) {
return false;
} else {
return true;
}
}
// TextWatcher
private TextWatcher myTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
checkForEmptyFields(); // Checks for empty fields
}
};
// Disables login button if there are any empty fields
void checkForEmptyFields() {
String password = pw.getEditText().getText().toString();
String username = un.getEditText().getText().toString();
// Checks for empty fields
if (password.isEmpty() || username.isEmpty()) {
btnLogin.setEnabled(false); // Button disabled if one or both fields are empty
} else {
btnLogin.setEnabled(true); // Button enabled --> no empty fields
}
}
// Confirm button clicked --> go to WelcomeActivity
public void completeLogin (View view) {
Intent loginIntent = new Intent(LoginActivity.this, RulesActivity.class);
// Snackbar created
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"Invalid username and/or password", Snackbar.LENGTH_LONG);
// If any fields do not meet the requirements, snackbar message is shown
if (!passwordValidate() | !usernameValidate()) {
snackbar.show();
} else { // All field requirements are met
btnLogin.setEnabled(true);
// Registration complete, goes to WelcomeActivity
startActivity(loginIntent);
}
}
}<file_sep>package com.example.quizgame;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
// Register button clicked --> go to registration page
public void clickRegister (View view) {
Intent registerIntent = new Intent (HomeActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
// Login button clicked --> go to login page
public void clickLogin (View view) {
Intent loginIntent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(loginIntent);
}
}
|
c6fd5ef31bccc2f15e3f321673c2582e4500d877
|
[
"Java"
] | 3
|
Java
|
phoebe94huang/QuizGame
|
eb5549512ad1bc3ee24ce37bd25385f63ce8fee0
|
c00d98c300023f427ffa7d84fec0b2ea1984e2b3
|
refs/heads/master
|
<file_sep># pebblebeemo
Beemo watchface for pebble
<file_sep>#include <pebble.h>
static Window *s_main_window;
static TextLayer *s_time_layer;
static Layer *s_canvas;
static GPath *s_blue_triangle_path = NULL;
static const GPathInfo TRIANGLE_PATH_INFO = {
.num_points = 3,
.points = (GPoint []) {{135, 132}, {128, 142}, {142, 142}}
};
//no-op function for use in conditional macros
static void nop(){}
static void update_time() {
// Get a tm structure
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
// Write the current hours and minutes into a buffer
static char s_buffer[8];
strftime(s_buffer, sizeof(s_buffer), clock_is_24h_style() ?
"%H:%M" : "%I:%M", tick_time);
// Display this time on the TextLayer
text_layer_set_text(s_time_layer, s_buffer);
//redraw graphic layer
layer_mark_dirty(s_canvas);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed) {
update_time();
}
static void draw_bw_outlines(Layer *layer, GContext *ctx){
graphics_draw_round_rect(ctx, GRect(12, 30, 122, 70), 8);
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, GRect(20, 140, 10, 30), 2, GCornersAll);
graphics_fill_rect(ctx, GRect(10, 150, 30, 10), 2, GCornersAll);
}
static void bt_handler(bool connected) {
layer_mark_dirty(s_canvas);
}
static void draw_round_beemo(Layer *layer, GContext *ctx){
//FYI, GRects are like this: (x of top left corner, y of top left corner, width, height)
GRect bounds = layer_get_bounds(layer);
int16_t width = bounds.size.w;
int16_t midx = width / 2;
bool btConnected = connection_service_peek_pebble_app_connection();
BatteryChargeState charge_state = battery_state_service_peek();
//draw face background
graphics_context_set_fill_color(ctx, GColorPastelYellow);
graphics_fill_rect(ctx, GRect(30, 30, 122, 70), 8, GCornersAll);
//draw eyes
//if BT is connected, eyes open, otherwise eyes closed
graphics_context_set_fill_color(ctx, GColorBlack);
if(btConnected){
graphics_fill_circle(ctx, GPoint(midx - 50,50), 6);
graphics_fill_circle(ctx, GPoint(midx + 50,50), 6);
}
else{
graphics_fill_rect(ctx, GRect(midx - 50, 50, 15, 5), 0, GCornersAll);
graphics_fill_rect(ctx, GRect(midx + 35, 50, 15, 5), 0, GCornersAll);
}
//draw mouth, smile, straight, or frown depending on battery state
if(charge_state.charge_percent > 50){
graphics_fill_radial(ctx, GRect(71, 35, 40, 40), GOvalScaleModeFitCircle, 5, DEG_TO_TRIGANGLE(90), DEG_TO_TRIGANGLE(270));
}
else if(charge_state.charge_percent > 25){
graphics_fill_rect(ctx, GRect(71, 65, 40, 6), 0, GCornersAll);
}
else{
graphics_fill_radial(ctx, GRect(71, 55, 40, 40), GOvalScaleModeFitCircle, 5, DEG_TO_TRIGANGLE(270), DEG_TO_TRIGANGLE(450));
}
//draw slot
graphics_context_set_fill_color(ctx, GColorDarkGreen);
graphics_fill_rect(ctx, GRect(32, 105, 60, 8), 2, GCornersAll);
//draw dark blue circle on right side
graphics_context_set_fill_color(ctx, GColorOxfordBlue);
graphics_fill_circle(ctx, GPoint(140,108), 5);
//draw yellow d-pad
graphics_context_set_fill_color(ctx, GColorYellow);
graphics_fill_rect(ctx, GRect(40, 140, 10, 30), 2, GCornersAll);
graphics_fill_rect(ctx, GRect(30, 150, 30, 10), 2, GCornersAll);
//draw red circle
graphics_context_set_fill_color(ctx, GColorRed);
graphics_fill_circle(ctx, GPoint(138,157), 8);
//draw green circle
graphics_context_set_fill_color(ctx, GColorIslamicGreen);
graphics_fill_circle(ctx, GPoint(148,143), 5);
//draw blue triangle
graphics_context_set_fill_color(ctx, GColorBlue);
s_blue_triangle_path = gpath_create(&TRIANGLE_PATH_INFO);
gpath_draw_filled(ctx, s_blue_triangle_path);
}
static void draw_square_beemo(Layer *layer, GContext *ctx){
//FYI, GRects are like this: (x of top left corner, y of top left corner, width, height)
GRect bounds = layer_get_bounds(layer);
int16_t width = bounds.size.w;
int16_t midx = width / 2;
BatteryChargeState charge_state = battery_state_service_peek();
bool btConnected = connection_service_peek_pebble_app_connection();
//draw face background
graphics_context_set_fill_color(ctx, GColorPastelYellow);
graphics_fill_rect(ctx, GRect(12, 30, 122, 70), 8, GCornersAll);
//draw eyes and mouth
graphics_context_set_fill_color(ctx, GColorBlack);
//draw eyes
//if BT is connected, eyes open, otherwise eyes closed
if(btConnected){
graphics_fill_circle(ctx, GPoint(midx - 45,50), 7);
graphics_fill_circle(ctx, GPoint(midx + 45,50), 7);
}
else{
graphics_fill_rect(ctx, GRect(midx - 45, 50, 15, 5), 0, GCornersAll);
graphics_fill_rect(ctx, GRect(midx + 33, 50, 15, 5), 0, GCornersAll);
}
//draw mouth, smile, straight, or frown depending on battery state
if(charge_state.charge_percent > 50){
graphics_fill_radial(ctx, GRect(54, 35, 40, 40), GOvalScaleModeFitCircle, 5, DEG_TO_TRIGANGLE(90), DEG_TO_TRIGANGLE(270));
}
else if(charge_state.charge_percent > 25){
graphics_fill_rect(ctx, GRect(54, 65, 40, 6), 0, GCornersAll);
}
else{
graphics_fill_radial(ctx, GRect(54, 55, 40, 40), GOvalScaleModeFitCircle, 5, DEG_TO_TRIGANGLE(270), DEG_TO_TRIGANGLE(450));
}
//draw slot
graphics_context_set_fill_color(ctx, GColorDarkGreen);
graphics_fill_rect(ctx, GRect(14, 105, 60, 8), 2, GCornersAll);
//draw dark blue circle on right side
graphics_context_set_fill_color(ctx, GColorOxfordBlue);
graphics_fill_circle(ctx, GPoint(120,108), 5);
//draw yellow d-pad
graphics_context_set_fill_color(ctx, GColorYellow);
graphics_fill_rect(ctx, GRect(15, 136, 10, 30), 2, GCornersAll);
graphics_fill_rect(ctx, GRect(5, 146, 30, 10), 2, GCornersAll);
//draw red circle
graphics_context_set_fill_color(ctx, GColorRed);
graphics_fill_circle(ctx, GPoint(125,157), 8);
//draw green circle
graphics_context_set_fill_color(ctx, GColorIslamicGreen);
graphics_fill_circle(ctx, GPoint(136,143), 5);
//draw blue triangle
graphics_context_set_fill_color(ctx, GColorBlue);
s_blue_triangle_path = gpath_create(&TRIANGLE_PATH_INFO);
gpath_move_to(s_blue_triangle_path, GPoint(-15, 0));
gpath_draw_filled(ctx, s_blue_triangle_path);
//draw needed outlines if display is b/w
PBL_IF_BW_ELSE(draw_bw_outlines(layer, ctx), nop());
}
static void layer_update_proc(Layer *layer, GContext *ctx) {
PBL_IF_ROUND_ELSE(draw_round_beemo(layer, ctx), draw_square_beemo(layer, ctx));
}
static void main_window_load(Window *window) {
// Get information about the Window
Layer *window_layer = window_get_root_layer(window);
GRect bounds = layer_get_bounds(window_layer);
//create layer for drawing
s_canvas = layer_create(bounds);
layer_set_update_proc(s_canvas, layer_update_proc);
layer_add_child(window_layer, s_canvas);
// Create the TextLayer with specific bounds
s_time_layer = text_layer_create(
GRect(0, 110, bounds.size.w, 50));
// Improve the layout to be more like a watchface
text_layer_set_background_color(s_time_layer, GColorClear);
text_layer_set_text_color(s_time_layer, GColorBlack);
//text_layer_set_text(s_time_layer, "00:00");
text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_BITHAM_30_BLACK));
text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter);
// Add it as a child layer to the Window's root layer
layer_add_child(window_layer, text_layer_get_layer(s_time_layer));
}
static void main_window_unload(Window *window) {
// Destroy TextLayer
text_layer_destroy(s_time_layer);
layer_destroy(s_canvas);
}
static void init() {
// Create main Window element and assign to pointer
s_main_window = window_create();
// Register with TickTimerService
tick_timer_service_subscribe(MINUTE_UNIT, tick_handler);
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_set_background_color(s_main_window, GColorCyan);
window_stack_push(s_main_window, true);
bt_handler(connection_service_peek_pebble_app_connection());
//subscribe to bluetooth events
connection_service_subscribe((ConnectionHandlers) {
.pebble_app_connection_handler = bt_handler
});
// Make sure the time is displayed from the start
update_time();
}
static void deinit() {
//unsubscribe from bt events
connection_service_unsubscribe();
// Destroy Window
window_destroy(s_main_window);
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
eb31dc512875906f56ae56ba54ad2455a7ed4a99
|
[
"Markdown",
"C"
] | 2
|
Markdown
|
brandtamos/pebblebeemo
|
695843ed5cb4f941a652b6046543b707073932a9
|
4b99bb64a98c432d9bbf6fe7773acb8948ba4472
|
refs/heads/master
|
<repo_name>wallheac/phcConferenceOrganizer<file_sep>/src/main/java/com/jph/organizer/rest/representation/Participant.java
package com.jph.organizer.rest.representation;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class Participant {
private Integer participantId;
private String firstName;
private String lastName;
private String status;
private String institution;
private List<String> roles;
private String email;
private String notes;
private Paper paper;
@JsonCreator
public Participant(
@JsonProperty("participantId") Integer participantId,
@JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName,
@JsonProperty("status") String status,
@JsonProperty("institution") String institution,
@JsonProperty("roles") List<String> roles,
@JsonProperty("email") String email,
@JsonProperty("notes") String notes,
@JsonProperty("paper") Paper paper) {
this.participantId = participantId;
this.paper = paper;
this.firstName = firstName;
this.lastName = lastName;
this.status = status;
this.institution = institution;
this.roles = roles;
this.email = email;
this.notes = notes;
}
public Integer getParticipantId() {
return participantId;
}
public Paper getPaper() {
return paper;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getStatus() {
return status;
}
public String getInstitution() {
return institution;
}
public List<String> getRoles() {
return roles;
}
public String getEmail() {
return email;
}
public String getNotes() {
return notes;
}
}
<file_sep>/src/main/java/com/jph/organizer/domain/ParticipantRoleIdDomain.java
package com.jph.organizer.domain;
import javax.persistence.Column;
import java.io.Serializable;
import java.util.Objects;
public class ParticipantRoleIdDomain implements Serializable {
@Column(name="panel")
private Integer panelId;
@Column(name="participant")
private Integer participantId;
public ParticipantRoleIdDomain(){}
public ParticipantRoleIdDomain(Integer panelId, Integer participantId) {
this.panelId = panelId;
this.participantId = participantId;
}
public Integer getPanelId() {
return panelId;
}
public Integer getParticipantId() {
return participantId;
}
public void setPanelId(Integer panelId) {
this.panelId = panelId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParticipantRoleIdDomain)) return false;
ParticipantRoleIdDomain that = (ParticipantRoleIdDomain) o;
return Objects.equals(panelId, that.panelId) &&
Objects.equals(participantId, that.participantId);
}
@Override
public int hashCode() {
return Objects.hash(panelId, participantId);
}
}
<file_sep>/src/main/resources/database.properties
database.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_phc_organizer
spring.datasource.username=Amy
spring.datasource.password=<PASSWORD>
hibernate.hbm2ddl.auto=validate
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql = true
hibernate.format_sql = true<file_sep>/src/main/java/com/jph/organizer/domain/PaperDomain.java
package com.jph.organizer.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity(name="Paper")
@Table(name="paper")
public class PaperDomain {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="paper_id")
private Integer paperId;
@ManyToMany(cascade = {
CascadeType.PERSIST
})
@JoinTable(name="paper_participant",
joinColumns=@JoinColumn(name="paper_id"),
inverseJoinColumns = @JoinColumn(name="participant_id")
)
private List<ParticipantDomain> participantDomains = new ArrayList();
private String title;
private String abstractUrl;
private Integer panelId;
private Boolean accepted;
public PaperDomain() {
}
public PaperDomain(String title, String abstractUrl, Integer panelId, Boolean accepted) {
this.title = title;
this.abstractUrl = abstractUrl;
this.panelId = panelId;
this.accepted = accepted;
}
public PaperDomain(Integer paperId, String title, String abstractUrl, Integer panelId, Boolean accepted) {
this.paperId = paperId;
this.title = title;
this.abstractUrl = abstractUrl;
this.panelId = panelId;
this.accepted = accepted;
}
public void addParticipant(ParticipantDomain participant) {
participantDomains.add(participant);
}
public Integer getPaperId() {
return paperId;
}
public void setPaperId(Integer paperId) {
this.paperId = paperId;
}
public List<ParticipantDomain> getParticipantDomains() {
return participantDomains;
}
public void setParticipantDomains(List<ParticipantDomain> participantDomains) {
this.participantDomains = participantDomains;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAbstractUrl() {
return abstractUrl;
}
public void setAbstractUrl(String abstractUrl) {
this.abstractUrl = abstractUrl;
}
public Integer getPanelId() {
return panelId;
}
public void setPanelId(Integer panelId) {
this.panelId = panelId;
}
public Boolean getAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PaperDomain)) return false;
PaperDomain that = (PaperDomain) o;
return Objects.equals(participantDomains, that.participantDomains) &&
Objects.equals(title, that.title) &&
Objects.equals(abstractUrl, that.abstractUrl) &&
Objects.equals(panelId, that.panelId) &&
Objects.equals(accepted, that.accepted);
}
@Override
public int hashCode() {
return Objects.hash(participantDomains, title, abstractUrl, panelId, accepted);
}
}
<file_sep>/readme.md
### Policy History Conference Organizer
Personal project to retrieve data from Google Sheets and use it to populate a MySQL database and expose that data via a REST API<file_sep>/src/main/java/com/jph/organizer/rest/DateAccessor.java
package com.jph.organizer.rest;
import com.jph.organizer.domain.DateDomain;
import com.jph.organizer.repository.DateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DateAccessor {
@Autowired
private DateRepository dateRepository;
public List<DateDomain> getDates() {
return dateRepository.findAll();
}
}
<file_sep>/src/main/java/com/jph/organizer/rest/googles/SubmissionMutator.java
package com.jph.organizer.rest.googles;
import com.jph.organizer.domain.*;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.List;
@Component
@Transactional
public class SubmissionMutator {
@PersistenceContext
private EntityManager entityManager;
public void createPanel(HashMap panel) {
PanelDomain panelDomain = (PanelDomain) panel.get("panel");
entityManager.persist(panelDomain);
List panelists = (List) panel.get("panelists");
List papers = (List) panel.get("papers");
persistPanelistsAndPapers(panelists, papers, panelDomain);
persistSupporting(panelDomain, (ParticipantDomain) panel.get("chair"), PanelPositionDomain.CHAIR);
persistSupporting(panelDomain, (ParticipantDomain) panel.get("commentator"), PanelPositionDomain.COMMENTATOR);
persistSupporting(panelDomain, (ParticipantDomain) panel.get("organizer"), PanelPositionDomain.CONTACT);
entityManager.close();
}
private void persistPanelistsAndPapers(List panelists, List papers, PanelDomain panelDomain) {
for (int i = 0; i < panelists.size(); i++) {
ParticipantDomain participantDomain = (ParticipantDomain) panelists.get(i);
PaperDomain paperDomain = (PaperDomain) papers.get(i);
if (validateParticipant(participantDomain)) {
entityManager.persist(participantDomain);
ParticipantRoleDomain participantRoleDomain = createParticipantRoleDomain(participantDomain, panelDomain,
PanelPositionDomain.PRESENTER);
entityManager.persist(participantRoleDomain);
participantDomain.setParticipantRoleDomain(participantRoleDomain);
panelDomain.addParticipant(participantDomain);
panelDomain.setParticipantRoleDomain(participantRoleDomain);
paperDomain.addParticipant(participantDomain);
paperDomain.setPanelId(panelDomain.getPanelId());
}
entityManager.persist(paperDomain);
}
}
private void persistSupporting(PanelDomain panelDomain, ParticipantDomain participant, PanelPositionDomain position) {
if(validateParticipant(participant)){
ParticipantDomain matching = findMatchingPanelist(panelDomain.getParticipants(), participant);
if (matching != null) {
if (position == PanelPositionDomain.CHAIR) {
matching.getParticipantRoleDomain().setChair(true);
}
if (position == PanelPositionDomain.COMMENTATOR) {
matching.getParticipantRoleDomain().setCommentator(true);
}
if (position == PanelPositionDomain.CONTACT) {
matching.getParticipantRoleDomain().setContact(true);
}
} else {
entityManager.persist(participant);
ParticipantRoleDomain role = createParticipantRoleDomain(participant, panelDomain, position);
entityManager.persist(role);
participant.setParticipantRoleDomain(role);
panelDomain.addParticipant(participant);
}
}
}
private boolean validateParticipant(ParticipantDomain participantDomain) {
return participantDomain != null && !participantDomain.getFirstName().isEmpty() && !participantDomain.getLastName().isEmpty();
}
private ParticipantDomain findMatchingPanelist(List<ParticipantDomain> panelists, ParticipantDomain target) {
return panelists.stream().filter(target::equals).findFirst().orElse(null);
}
private ParticipantRoleDomain createParticipantRoleDomain(ParticipantDomain participantDomain, PanelDomain panelDomain,
PanelPositionDomain panelPositionDomain) {
ParticipantRoleDomain participantRoleDomain = new ParticipantRoleDomain
(new ParticipantRoleIdDomain(panelDomain.getPanelId(), participantDomain.getParticipantId()), false, false, false, false);
calculateRoles(participantRoleDomain, panelPositionDomain);
return participantRoleDomain;
}
private void calculateRoles(ParticipantRoleDomain participantRoleDomain, PanelPositionDomain panelPositionDomain) {
participantRoleDomain.setContact(panelPositionDomain.equals(PanelPositionDomain.CONTACT));
participantRoleDomain.setChair(panelPositionDomain.equals(PanelPositionDomain.CHAIR));
participantRoleDomain.setCommentator(panelPositionDomain.equals(PanelPositionDomain.COMMENTATOR));
participantRoleDomain.setPresenter(panelPositionDomain.equals(PanelPositionDomain.PRESENTER));
}
public void createPaperSubmission(HashMap paperMap) {
List<ParticipantDomain> participants = (List<ParticipantDomain>) paperMap.get("participants");
PaperDomain paper = (PaperDomain) paperMap.get("paper");
entityManager.persist(paper);
for (ParticipantDomain participant : participants) {
entityManager.persist(participant);
paper.addParticipant(participant);
participant.addPaper(paper);
}
entityManager.close();
}
}
<file_sep>/src/main/java/com/jph/organizer/rest/OrganizerParticipantTransformer.java
package com.jph.organizer.rest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.jph.organizer.domain.ParticipantDomain;
import com.jph.organizer.domain.ParticipantRoleDomain;
import com.jph.organizer.domain.ParticipantRoleIdDomain;
import com.jph.organizer.rest.representation.Participant;
@Component
public class OrganizerParticipantTransformer {
@Autowired
private OrganizerPaperTransformer organizerPaperTransformer;
public List<ParticipantDomain> toParticipantDomains(List<Participant> participants) {
List<ParticipantDomain> participantDomains = participants.stream()
.map(participant -> {
ParticipantDomain participantDomain = new ParticipantDomain(
participant.getParticipantId(),
participant.getFirstName(),
participant.getLastName(),
participant.getStatus(),
participant.getInstitution(),
participant.getEmail(),
participant.getNotes());
participantDomain.setParticipantRoleDomain(mapParticipantRoleDomain(participant));
if (participant.getPaper() != null) {
participantDomain.setPaperDomains(Arrays.asList(organizerPaperTransformer.toPaperDomain(participant.getPaper())));
}
return participantDomain;
})
.collect(Collectors.toList());
participantDomains.forEach(participantDomain -> participantDomain.setParticipantRoleDomain(
new ParticipantRoleDomain(new ParticipantRoleIdDomain(null, null), true, false, false, false)));
return participantDomains;
}
private ParticipantRoleDomain mapParticipantRoleDomain(Participant participant) {
ParticipantRoleDomain roleDomain = new ParticipantRoleDomain(new ParticipantRoleIdDomain(null, null), false, false, false, false);
if (participant.getRoles().isEmpty()) {
roleDomain.setPresenter(true);
} else {
List<String> roles = participant.getRoles();
roles.stream().forEach(role -> {
switch (role) {
case "CONTACT":
roleDomain.setContact(true);
case "CHAIR":
roleDomain.setContact(true);
case "PRESENTER":
roleDomain.setPresenter(true);
case "COMMENTATOR":
roleDomain.setCommentator(true);
}
});
}
return roleDomain;
}
public Participant fromParticipantDomain(ParticipantDomain participantDomain) {
return new Participant(participantDomain.getParticipantId(), participantDomain.getFirstName(),
participantDomain.getLastName(), participantDomain.getStatus(), participantDomain.getInstitution(),
null, participantDomain.getEmail(), participantDomain.getNotes(), null);
}
}
<file_sep>/src/main/java/com/jph/organizer/domain/ParticipantRoleDomain.java
package com.jph.organizer.domain;
import javax.persistence.*;
import java.util.Objects;
@Entity(name="ParticipantRole")
@Table(name="participant_role")
public class ParticipantRoleDomain {
@EmbeddedId
private ParticipantRoleIdDomain participantRoleIdDomain;
private Boolean presenter;
private Boolean commentator;
private Boolean chair;
private Boolean contact;
public ParticipantRoleDomain() {
}
public ParticipantRoleDomain(ParticipantRoleIdDomain participantRoleIdDomain, Boolean presenter, Boolean commentator,
Boolean chair, Boolean contact) {
this.participantRoleIdDomain = participantRoleIdDomain;
this.presenter = presenter;
this.commentator = commentator;
this.chair = chair;
this.contact = contact;
}
public ParticipantRoleIdDomain getParticipantRoleIdDomain() {
return participantRoleIdDomain;
}
public void setParticipantRoleIdDomain(ParticipantRoleIdDomain participantRoleIdDomain) {
this.participantRoleIdDomain = participantRoleIdDomain;
}
public Boolean getPresenter() {
return presenter;
}
public void setPresenter(Boolean presenter) {
this.presenter = presenter;
}
public Boolean getCommentator() {
return commentator;
}
public void setCommentator(Boolean commentator) {
this.commentator = commentator;
}
public Boolean getChair() {
return chair;
}
public void setChair(Boolean chair) {
this.chair = chair;
}
public Boolean getContact() {
return contact;
}
public void setContact(Boolean contact) {
this.contact = contact;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParticipantRoleDomain)) return false;
ParticipantRoleDomain that = (ParticipantRoleDomain) o;
return Objects.equals(presenter, that.presenter) &&
Objects.equals(commentator, that.commentator) &&
Objects.equals(chair, that.chair) &&
Objects.equals(contact, that.contact);
}
@Override
public int hashCode() {
return Objects.hash(participantRoleIdDomain, presenter, commentator, chair, contact);
}
}
<file_sep>/src/main/java/com/jph/organizer/domain/PanelDomain.java
package com.jph.organizer.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity(name="Panel")
@Table(name="panel")
public class PanelDomain {
@Id
@GeneratedValue
@Column(name="panel_id")
private int panelId;
@Column(name="panel_name")
private String panelName;
@OneToOne
private ParticipantDomain contact;
private String type;
private Boolean accepted;
@Column(name="date_time")
private Date dateTime;
private String location;
@Column(name="cv_url")
private String cvUrl;
@Column(name="abstract_url")
private String abstractUrl;
private String notes;
@Column(name="av_requested")
private Boolean avRequested;
private String requestor;
@Column(name="av_request_date")
private Date avRequestDate;
@ManyToOne
@JoinColumns({
@JoinColumn(
name = "panel",
referencedColumnName = "panel"),
@JoinColumn(
name = "participant",
referencedColumnName = "participant")
})
private ParticipantRoleDomain participantRoleDomain;
@ManyToMany(cascade = {
CascadeType.PERSIST
})
@JoinTable(name="panel_participant",
joinColumns=@JoinColumn(name="panel_id"),
inverseJoinColumns = @JoinColumn(name="participant_id")
)
private List<ParticipantDomain> participants = new ArrayList<>();
public PanelDomain() {
}
public PanelDomain(String panelName, ParticipantDomain contact, String type, Boolean accepted, Date dateTime,
String location, String cvUrl, String abstractUrl, String notes, Boolean avRequested,
String requestor, Date avRequestDate, ParticipantDomain... participantDomains) {
this.panelName = panelName;
this.contact = contact;
this.type = type;
this.accepted = accepted;
this.dateTime = dateTime;
this.location = location;
this.cvUrl = cvUrl;
this.abstractUrl = abstractUrl;
this.notes = notes;
this.avRequested = avRequested;
this.requestor = requestor;
this.avRequestDate = avRequestDate;
}
public void addParticipant(ParticipantDomain participantDomain) {
participants.add(participantDomain);
participantDomain.getPanels().add(this);
}
public void removeParticipant(ParticipantDomain participantDomain) {
participants.remove(participantDomain);
participantDomain.getPanels().remove(this);
}
public int getPanelId() {
return panelId;
}
public void setPanelId(int panelId) {
this.panelId = panelId;
}
public String getPanelName() {
return panelName;
}
public void setPanelName(String panelName) {
this.panelName = panelName;
}
public ParticipantDomain getContact() {
return contact;
}
public void setContact(ParticipantDomain contact) {
this.contact = contact;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCvUrl() {
return cvUrl;
}
public void setCvUrl(String cvUrl) {
this.cvUrl = cvUrl;
}
public String getAbstractUrl() {
return abstractUrl;
}
public void setAbstractUrl(String abstractUrl) {
this.abstractUrl = abstractUrl;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Boolean getAvRequested() {
return avRequested;
}
public void setAvRequested(Boolean avRequested) {
this.avRequested = avRequested;
}
public String getRequestor() {
return requestor;
}
public void setRequestor(String requestor) {
this.requestor = requestor;
}
public Date getAvRequestDate() {
return avRequestDate;
}
public void setAvRequestDate(Date avRequestDate) {
this.avRequestDate = avRequestDate;
}
public ParticipantRoleDomain getParticipantRoleDomain() {
return this.participantRoleDomain;
}
public void setParticipantRoleDomain(ParticipantRoleDomain participantRoleDomain) {
this.participantRoleDomain = participantRoleDomain;
}
public List<ParticipantDomain> getParticipants() {
return participants;
}
public void setParticipants(List<ParticipantDomain> participants) {
this.participants = participants;
}
}
<file_sep>/src/main/java/com/jph/organizer/domain/PanelPositionDomain.java
package com.jph.organizer.domain;
public enum PanelPositionDomain {
CHAIR,
COMMENTATOR,
PRESENTER,
CONTACT
}
<file_sep>/src/main/java/com/jph/organizer/rest/OrganizerPanelTransformer.java
package com.jph.organizer.rest;
import com.jph.organizer.domain.*;
import com.jph.organizer.rest.representation.ConstructedPanel;
import com.jph.organizer.rest.representation.Panel;
import com.jph.organizer.rest.representation.Paper;
import com.jph.organizer.rest.representation.Participant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.PersistenceException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class OrganizerPanelTransformer {
@Autowired
private PaperAccessor paperAccessor;
@Autowired
private RoleAccessor roleAccessor;
@Autowired
private PanelAccessor panelAccessor;
@Autowired
private OrganizerParticipantTransformer organizerParticipantTransformer;
@Autowired
private OrganizerPaperTransformer organizerPaperTransformer;
@Autowired
private OrganizerPanelMutator organizerPanelMutator;
public List<Panel> fromPanelDomains(List<PanelDomain> panelDomains) {
return panelDomains.stream().map(this::fromPanelDomain).collect(Collectors.toList());
}
public Panel fromPanelDomain(PanelDomain panelDomain) {
int panelId = panelDomain.getPanelId();
List<PaperDomain> paperDomains = paperAccessor
.getPapersByPanelId(panelId);
List<ParticipantRoleDomain> roles = roleAccessor.getParticipantRoleDomainsByPanelId(panelId);
List<Participant> participants = panelDomain.getParticipants()
.stream()
.map(participantDomain -> mapParticipant(participantDomain, paperDomains, roles))
.collect(Collectors.toList());
return mapPanel(panelDomain, participants);
}
private Participant mapParticipant(ParticipantDomain participantDomain, List<PaperDomain> paperDomains,
List<ParticipantRoleDomain> roles) {
if (participantDomain != null) {
List<String> roleList = calculateRoles(participantDomain, roles);
Paper paper = mapPaper(matchPaperDomain(participantDomain.getParticipantId(), paperDomains));
return new Participant(participantDomain.getParticipantId(), participantDomain.getFirstName(),
participantDomain.getLastName(), participantDomain.getStatus(), participantDomain.getInstitution(),
roleList, participantDomain.getEmail(), participantDomain.getNotes(), paper);
}
return null;
}
private List<String> calculateRoles(ParticipantDomain participantDomain, List<ParticipantRoleDomain> roles) {
ParticipantRoleDomain participantRoleDomain = roles
.stream()
.filter(participantRole -> participantRole.getParticipantRoleIdDomain().getParticipantId().equals(participantDomain.getParticipantId()))
.findFirst()
.orElse(null);
List<String> roleList = new ArrayList<>();
if (participantRoleDomain != null) {
if(participantRoleDomain.getChair()) {
roleList.add(PanelPositionDomain.CHAIR.toString());
}
if(participantRoleDomain.getCommentator()) {
roleList.add(PanelPositionDomain.COMMENTATOR.toString());
}
if(participantRoleDomain.getContact()) {
roleList.add(PanelPositionDomain.CONTACT.toString());
}
if(participantRoleDomain.getPresenter()) {
roleList.add(PanelPositionDomain.PRESENTER.toString());
}
}
return roleList;
}
private Panel mapPanel(PanelDomain panelDomain, List<Participant> participants) {
return new Panel(panelDomain.getPanelId(), panelDomain.getPanelName(), null,
panelDomain.getType(), panelDomain.getAccepted(), panelDomain.getDateTime(), panelDomain.getLocation(),
panelDomain.getCvUrl(), panelDomain.getAbstractUrl(), panelDomain.getNotes(), panelDomain.getAvRequested(),
panelDomain.getRequestor(), panelDomain.getAvRequestDate(), participants);
}
private Paper mapPaper(PaperDomain paperDomain) {
if (paperDomain != null) {
return new Paper(paperDomain.getPaperId(), paperDomain.getTitle(), paperDomain.getAbstractUrl(),
paperDomain.getPanelId(), paperDomain.getAccepted(), null);
}
return null;
}
private PaperDomain matchPaperDomain(Integer participantId, List<PaperDomain> paperDomains) {
return paperDomains.stream()
.filter(paperDomain -> paperDomain.getParticipantDomains()
.stream()
.anyMatch(participantDomain -> participantDomain.getParticipantId() == participantId))
.findFirst()
.orElse(null);
}
public List<PanelDomain> toPanelDomains(List<ConstructedPanel> constructedPanels) throws PersistenceException {
return constructedPanels.stream()
.map(this::toPanelDomain)
.collect(Collectors.toList());
}
public PanelDomain toPanelDomain(ConstructedPanel constructedPanel) throws PersistenceException {
PanelDomain panelDomain = new PanelDomain();
panelDomain.setPanelName(constructedPanel.getTitle());
panelDomain.setType(TypeDomain.CONSTRUCTED.toString());
//TODO this should eventually be set in the UI
panelDomain.setAccepted(true);
List<Participant> participants = constructedPanel.getPapers().stream()
.map(paper -> paper.getParticipant())
.collect(Collectors.toList());
List<ParticipantDomain> participantDomains = organizerParticipantTransformer.toParticipantDomains(participants);
List<PaperDomain> paperDomains = organizerPaperTransformer.toPaperDomains(constructedPanel.getPapers());
return organizerPanelMutator.persistConstructedPanel(panelDomain, participantDomains, paperDomains);
}
public PanelDomain toPanelDomain(Panel panel) throws PersistenceException {
PanelDomain panelDomain = new PanelDomain();
panelDomain.setPanelId(panel.getPanelId());
panelDomain.setPanelName(panel.getPanelName());
panelDomain.setType(panel.getType());
panelDomain.setAccepted(panel.getAccepted());
panelDomain.setNotes(panel.getNotes());
panelDomain.setAvRequested(panel.getAvRequested());
panelDomain.setRequestor(panel.getRequestor());
if(panel.getAvRequestDate() == null) {
panelDomain.setAvRequestDate(new Date());
}
if(panel.getDateTime() != null) {
panelDomain.setDateTime(panel.getDateTime());
}
List<ParticipantDomain> participantDomains = organizerParticipantTransformer.toParticipantDomains(panel.getParticipants());
return organizerPanelMutator.persistPanel(panelDomain, participantDomains);
}
}
<file_sep>/src/main/java/com/jph/organizer/rest/ParticipantAccessor.java
package com.jph.organizer.rest;
import com.jph.organizer.domain.ParticipantDomain;
import com.jph.organizer.repository.ParticipantRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class ParticipantAccessor {
@Autowired
private ParticipantRepository participantRepository;
public Optional getParticipantById(Integer id) {
return participantRepository.findById(id);
}
public List<ParticipantDomain> getParticipants() {
return participantRepository.findAll();
}
}
<file_sep>/src/main/java/com/jph/organizer/rest/googles/PanelTransformer.java
package com.jph.organizer.rest.googles;
import com.google.api.services.drive.model.File;
import com.jph.organizer.domain.PanelDomain;
import com.jph.organizer.domain.PaperDomain;
import com.jph.organizer.domain.ParticipantDomain;
import com.jph.organizer.rest.representation.Participant;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Component
public class PanelTransformer {
public List<HashMap<String, Object>> fromPanels(List<List<Object>> sheetValues, List<File> driveFiles) {
List<HashMap<String, Object>> panels = new ArrayList<>();
HashMap<String, String> docMap = mapDriveFiles(driveFiles);
if (sheetValues == null || sheetValues.isEmpty()) {
System.out.println("No Panel Data");
} else {
sheetValues.remove(0);
for (List row : sheetValues) {
fromPanel(panels, row, docMap);
}
}
return panels;
}
public List<HashMap<String, Object>> fromPanel(List<HashMap<String, Object>> panels, List row, HashMap docMap) {
HashMap<String, Object> panelMap = new HashMap();
try {
panelMap.put("panel", mapPanelDomain(row, docMap));
mapParticipantAndPaperDomains(row, panelMap);
} catch (Exception e) {
e.printStackTrace();
}
panels.add(panelMap);
return panels;
}
private HashMap<String,String> mapDriveFiles(List<File> driveFiles) {
HashMap<String, String> docMap = new HashMap<>();
driveFiles.stream()
.forEach(file -> docMap.put(StringEscapeUtils.unescapeHtml4(file.getName()), file.getId()));
return docMap;
}
private PanelDomain mapPanelDomain(List list, HashMap docMap) {
String notes = list.size() == 54 ? list.get(53).toString() : null;
if(docMap.get(list.get(1)) == null || docMap.get(list.get(1)).equals("")) {
System.out.println("failed to map title: " + list.get(1));
}
String abstractUrl = "https://drive.google.com/drive/u/0/folders/" + docMap.get(list.get(1));
String cvUrl = "https://drive.google.com/drive/u/0/folders/" + docMap.get(list.get(1));
return new PanelDomain(list.get(1).toString(), null, "SUBMITTED", false,
null, null, cvUrl, abstractUrl, notes,
false, null, null);
}
private HashMap<String, Object> mapParticipantAndPaperDomains(List list, HashMap panel) throws Exception {
List organizer = list.size() > 7 ? list.subList(2, 7) : null;
List chair = list.size() > 7 ? list.subList(7, 12) : null;
List commentator = list.size() > 43 ? list.subList(43, 48) : null;
List participants = new ArrayList();
if (list.size() > 30) {
if (list.get(30).equals("No")) {
participants = list.subList(12, 30);
} else {
List extraParticipants = list.subList(31, 43);
participants.addAll(list.subList(12, 30));
participants.addAll(extraParticipants);
}
}
if (organizer != null) {
panel.put("organizer", mapParticipantDomain(organizer));
}
if (chair != null) {
panel.put("chair", mapParticipantDomain(chair));
}
if (commentator != null) {
panel.put("commentator", mapParticipantDomain(commentator));
}
mapPanelistsAndPapers(participants, panel);
return panel;
}
private HashMap mapPanelistsAndPapers(List participants, HashMap panel) throws Exception {
List<ParticipantDomain> participantDomains = new ArrayList<>();
List<PaperDomain> paperDomains = new ArrayList<>();
if (participants.size() % 6 == 0) {
for (int i = 0; i < participants.size(); i = i + 6) {
List participant = participants.subList(i, i + 6);
participantDomains.add(mapParticipantDomain(participant));
paperDomains.add(mapPaperDomain(participant));
}
} else {
throw new Exception("error in participant list size");
}
panel.put("panelists", participantDomains);
panel.put("papers", paperDomains);
return panel;
}
private PaperDomain mapPaperDomain(List participant) {
return new PaperDomain(participant.get(5).toString(), null, null, false);
}
ParticipantDomain mapParticipantDomain(List participantInformation) {
return new ParticipantDomain(participantInformation.get(0).toString(), participantInformation.get(1).toString(),
participantInformation.get(2).toString(), participantInformation.get(3).toString(),
participantInformation.get(4).toString(), null);
}
}
<file_sep>/src/main/java/com/jph/organizer/repository/PanelRepository.java
package com.jph.organizer.repository;
import com.jph.organizer.domain.PanelDomain;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PanelRepository extends JpaRepository<PanelDomain, Integer> {
PanelDomain findByPanelIdEquals(Integer panelId);
}
|
bcd71c0cd171f617d631681024aed8f42d1d2ed6
|
[
"Markdown",
"Java",
"INI"
] | 15
|
Java
|
wallheac/phcConferenceOrganizer
|
fb4f473f4b03dbe5eefbb51cdaec384b577bd581
|
3b53ca51e53400175fa4206bf871f3e26bc74a2e
|
refs/heads/main
|
<file_sep># jquery-plugin
Custom jQuery plugin to print text
<file_sep>$(document).ready(function () {
$('#here').hello({
name: '<NAME>',
color: 'red'
});
});<file_sep>(function ($) {
$.fn.hello = function (options) {
// Default options
var settings = $.extend({
name: '<NAME>',
color: 'blue'
}, options);
// Apply options
return this.append('Hello ' + settings.name + '!').css({ color: settings.color });
};
}(jQuery));
|
1eaa23fff6456245f7d4c27d8abe3c485cf1e28f
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
povstenko/jquery-plugin
|
86b14a8c26f067a1254a5b659fe88f728cee6fe5
|
d5a2ffa0f1e2728962b27328e8c89b01a33eb60d
|
refs/heads/master
|
<file_sep>package com.surinov.alexander.navigationtest;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.surinov.alexander.navigationtest.fragments.BaseFragment;
import java.util.List;
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
private Context mContext;
public PagerAdapter(Context context, FragmentManager fm, List<Fragment> fragments) {
super(fm);
mContext = context;
mFragments = fragments;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
BaseFragment basePageFragment = (BaseFragment) mFragments.get(position);
return mContext.getResources().getString(basePageFragment.getTitleRes());
}
}<file_sep>package com.surinov.alexander.navigationtest.fragments.pages;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import com.surinov.alexander.navigationtest.R;
import com.surinov.alexander.navigationtest.fragments.BaseFragment;
import com.surinov.alexander.navigationtest.fragments.Parent;
public class PageTwoFragment extends BaseFragment implements Parent {
@Override
public int getTitleRes() {
return R.string.text_page_2;
}
@Override
protected int getColorRes() {
return R.color.orange_300;
}
@Override
protected void upButtonClick() {
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.childFragmentContainer, new PageTwoChildFragment())
.addToBackStack(null)
.commit();
}
@NonNull
@Override
public Fragment getChildFragment() {
FragmentManager fragmentManager = getChildFragmentManager();
return fragmentManager.findFragmentById(R.id.childFragmentContainer);
}
}<file_sep>package com.surinov.alexander.navigationtest.fragments;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
public interface Parent {
Fragment getChildFragment();
}
<file_sep>package com.surinov.alexander.navigationtest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import com.surinov.alexander.navigationtest.fragments.FavoritesFragment;
import com.surinov.alexander.navigationtest.fragments.MusicFragment;
import com.surinov.alexander.navigationtest.fragments.Parent;
import com.surinov.alexander.navigationtest.fragments.ScheduleFragment;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
switchFragment(new FavoritesFragment(), "Fav");
}
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorites:
switchFragment(new FavoritesFragment(), "Fav");
break;
case R.id.action_schedules:
switchFragment(new ScheduleFragment(), "Sched");
break;
case R.id.action_music:
switchFragment(new MusicFragment(), "Music");
break;
}
return true;
}
});
}
private void switchFragment(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentContainer);
if (currentFragment != null) {
fragmentTransaction.detach(currentFragment);
}
Fragment addedFragment = fragmentManager.findFragmentByTag(tag);
if (addedFragment != null) {
fragmentTransaction.attach(addedFragment);
} else {
fragmentTransaction.add(R.id.fragmentContainer, fragment, tag);
}
fragmentTransaction.commit();
List<Fragment> fragments = fragmentManager.getFragments();
Log.d("Fragments", "Fragment entries: " + (fragments == null ? 0 : fragments.size()));
}
@Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentContainer);
if (currentFragment != null) {
handleBackPressedRecursive(currentFragment);
} else {
super.onBackPressed();
}
}
private void handleBackPressedRecursive(@NonNull Fragment currentFragment) {
if (currentFragment instanceof Parent) {
// try to get child fragment of current parent fragment
Fragment childFragment = ((Parent) currentFragment).getChildFragment();
if (childFragment != null) {
// recursive call to get the most top child fragment
handleBackPressedRecursive(childFragment);
} else {
// if childFragment is null then we reached the most top fragment
// perform pop back stack
performPopBackStackRecursive(currentFragment);
}
} else {
// if current fragment not implement Parent interface (can not have any child fragments)
// then we reached the most top fragment - perform pop back stack
performPopBackStackRecursive(currentFragment);
}
}
private void performPopBackStackRecursive(@NonNull Fragment theMostTopFragment) {
// get parent fragment of the most top fragment
Fragment parentFragment = theMostTopFragment.getParentFragment();
if (parentFragment == null) {
// if parent fragment is null it's mean that
// the most top fragment is attached directly to an Activity, so perform onBackPressed()
super.onBackPressed();
} else {
// if parent fragment is not null try to pop beck stack from paren fragment manager
FragmentManager fragmentManager = parentFragment.getChildFragmentManager();
if (!fragmentManager.popBackStackImmediate()) {
// if popBackStackImmediate return false - then theMostTopFragment may be
// represented as page in ViewPager, so try to recursive call for parent fragment (may be bad solution)
performPopBackStackRecursive(parentFragment);
}
}
}
}
<file_sep>package com.surinov.alexander.navigationtest.fragments.pages;
import com.surinov.alexander.navigationtest.R;
import com.surinov.alexander.navigationtest.fragments.BaseFragment;
public class PageThreeFragment extends BaseFragment {
@Override
public int getTitleRes() {
return R.string.text_page_3;
}
@Override
protected int getColorRes() {
return R.color.teal_300;
}
@Override
protected void upButtonClick() {
}
}<file_sep>package com.surinov.alexander.navigationtest.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.surinov.alexander.navigationtest.R;
public abstract class BaseFragment extends Fragment {
public static final String TAG_FRAGMENT = "Fragment";
@StringRes
public abstract int getTitleRes();
@ColorRes
protected abstract int getColorRes();
protected abstract void upButtonClick();
@Override
public void onAttach(Context activity) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onAttach ");
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onCreate");
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onCreateView");
return inflater.inflate(R.layout.fragmen_base, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onViewCreated");
TextView titleView = (TextView) view.findViewById(R.id.titleView);
titleView.setText(getTitleRes());
View rootView = view.findViewById(R.id.rootView);
rootView.setBackgroundResource(getColorRes());
View upButtonView = view.findViewById(R.id.upButtonView);
upButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
upButtonClick();
}
});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onStart");
super.onStart();
}
@Override
public void onResume() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onResume");
super.onResume();
}
@Override
public void onPause() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onPause");
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onSaveInstanceState");
super.onSaveInstanceState(outState);
}
@Override
public void onStop() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onStop");
super.onStop();
}
@Override
public void onDestroyView() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onDestroyView");
super.onDestroyView();
}
@Override
public void onDestroy() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onDestroy");
super.onDestroy();
}
@Override
public void onDetach() {
Log.d(TAG_FRAGMENT, getClass().getSimpleName() + " " + getTag() + ".onDetach");
super.onDetach();
}
}
|
28c48466a62eec2a960bc5419633ce470db5a117
|
[
"Java"
] | 6
|
Java
|
rAseri/NavigationTest
|
cd4e7e0a0f6f08e2b4cc27923b946676746701e2
|
ce92df14f73a34e64f5413fd971ac23453b365a4
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# PROGRAMMER: <NAME>
# DATE CREATED: 13/11/2018
# REVISED DATE: <=(Date Revised - if any)
# PURPOSE: Use a trained network to detect facial keypoints for an input image
#
# Expected Call with <> indicating expected user input:
# python predict.py <input> <model>
#
# Example call:
# python predict.py images/obamas.jpg saved_models/keypoints_model_haar_bn20.pt
#
# Arguments explaination:
# <input> (required)
# Input image filename
#
# <model> (required)
# Trained model filename
#
#
# Imports python modules
import argparse
import os.path
import torch
from models import Net
import numpy as np
import cv2
import matplotlib.pyplot as plt
def loadModel(filename, gpu):
net = Net()
net.load_state_dict(torch.load(filename))
net.eval()
print("Network elements:", net)
if (gpu == True):
net.cuda()
return net
def loadFaceDetector(filename=""):
## load in a haar cascade classifier for detecting frontal faces
if filename == "":
filename = 'detector_architectures/haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(filename)
return face_cascade
def predict(filename, model, detector, gpu):
# load in color image for face detection
image = cv2.imread(filename)
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#run the detector
# the output here is an array of detections; the corners of each detection box
# if necessary, modify these parameters until you successfully identify every face in a given image
faces = detector.detectMultiScale(image, 1.2, 2)
# loop over the detected faces from your haar cascade
for i, (x,y,w,h) in enumerate(faces):
# Select the region of interest that is the face in the image
roi = image[y:y+h, x:x+w]
## DONE: Convert the face region from RGB to grayscale
roi = cv2.cvtColor(roi, cv2.COLOR_RGB2GRAY)
## DONE: Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]
roi = roi / 255.0
## DONE: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)
roi = cv2.resize(roi, (224, 224))
## DONE: Reshape the numpy image shape (H x W x C) into a torch image shape (C x H x W)
roi_t = roi.reshape(1, roi.shape[0], roi.shape[1], 1)
roi_t = roi_t.transpose((0, 3, 1, 2))
roi_t = torch.from_numpy(roi_t).type(torch.FloatTensor)
## DONE: Make facial keypoint predictions using your loaded, trained network
if (gpu == True):
roi_t = roi_t.cuda()
predicted_key_pts = model(roi_t)
if (gpu == True):
predicted_key_pts = predicted_key_pts.cpu()
predicted_key_pts = predicted_key_pts.view(predicted_key_pts.size()[0], 68, -1).detach().numpy().squeeze()
predicted_key_pts = predicted_key_pts*50.0+100
## DONE: Display each detected face and the corresponding keypoints
ax = plt.subplot2grid((1, len(faces)), (0, i))
plt.imshow(roi, cmap='gray')
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='b')
plt.title('Face {}'.format(i))
plt.axis('off')
plt.show()
# Main program function defined below
def main():
#Parse command line arguments
in_arg = get_input_args()
#Load face detector
face_cascade = loadFaceDetector()
#Load model checkpoint
model = loadModel(in_arg.model, in_arg.gpu)
#Prediction
predict(in_arg.input, model, face_cascade, in_arg.gpu)
# Command line arguments parser
def get_input_args():
"""
Retrieves and parses the command line arguments created and defined using
the argparse module. This function returns these arguments as an
ArgumentParser object.
Parameters:
None - simply using argparse module to create & store command line arguments
Returns:
parse_args() -data structure that stores the command line arguments object
"""
# create arguments parser
parser = argparse.ArgumentParser()
parser.add_argument("input", nargs=1, type = str,
help = "Input image filename")
parser.add_argument("model", nargs=1, type = str,
help = "Trained model filename")
parser.add_argument('--gpu', action='store_true',
help = "If set, GPU is used in prediction (default: False)")
in_arg = parser.parse_args()
in_arg.input = in_arg.input[0]
in_arg.model = in_arg.model[0]
error_list = []
# Check input Filename
if not os.path.isfile(in_arg.input):
error_list.append("predict.py: error: argument: input: file not found '{}'".format(in_arg.input))
# Check checkpoint Filename
if not os.path.isfile(in_arg.model):
error_list.append("predict.py: error: argument: model: file not found '{}'".format(in_arg.model))
# Check GPU
if in_arg.gpu and not torch.cuda.is_available():
error_list.append("predict.py: error: argument: --gpu: GPU not available")
# Print errors
if len(error_list) > 0:
parser.print_usage()
print('\n'.join(error for error in error_list))
quit()
# return arguments object
return in_arg
# Call to main function to run the program
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n** User interruption")
quit()
<file_sep>## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## DONE: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
#
# Conv layer output size
# Ow = (Iw - Fw + 2P) / Sw + 1
# Oh = (Ih - Fh + 2P) / Sh + 1
#
#Iw, Ih = 224, 224 (input image size)
#Ow, Oh = Iw, Ih
self.conv1 = nn.Conv2d(1, 32, 5) # S=1, P=0
#Ow, Oh = (Ow - 5 + 2*0) // 1 + 1, (Oh - 5 + 2*0) // 1 + 1
self.pool1 = nn.MaxPool2d(2)
#Ow, Oh = Ow // 2, Oh // 2
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 48, 5) # S=1, P=0
#Ow, Oh = (Ow - 5 + 2*0) // 1 + 1, (Oh - 5 + 2*0) // 1 + 1
#self.pool2 = nn.MaxPool2d(2)
#Ow, Oh = Ow // 2, Oh // 2
self.bn2 = nn.BatchNorm2d(48)
self.conv3 = nn.Conv2d(48, 56, 5) # S=1, P=0
#Ow, Oh = (Ow - 5 + 2*0) // 1 + 1, (Oh - 5 + 2*0) // 1 + 1
#self.pool3 = nn.MaxPool2d(2)
#Ow, Oh = Ow // 2, Oh // 2
self.bn3 = nn.BatchNorm2d(56)
self.conv4 = nn.Conv2d(56, 64, 3) # S=1, P=0
#Ow, Oh = (Ow - 3 + 2*0) // 1 + 1, (Oh - 3 + 2*0) // 1 + 1
#self.pool4 = nn.MaxPool2d(2)
#Ow, Oh = Ow // 2, Oh // 2
self.bn4 = nn.BatchNorm2d(64)
self.conv5 = nn.Conv2d(64, 64, 3) # S=1, P=0
#Ow, Oh = (Ow - 3 + 2*0) // 1 + 1, (Oh - 3 + 2*0) // 1 + 1
#self.linear1 = nn.Linear(Ow * Oh * 64, 512)
self.linear1 = nn.Linear(5184, 512)
self.linear2 = nn.Linear(512, 136)
def forward(self, x):
## DONE: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = self.conv1(x)
x = F.relu(self.pool1(x))
x = self.bn1(x)
x = self.conv2(x)
x = F.relu(self.pool1(x))
x = self.bn2(x)
x = self.conv3(x)
x = F.relu(self.pool1(x))
x = self.bn3(x)
x = self.conv4(x)
x = F.relu(self.pool1(x))
x = self.bn4(x)
x = F.relu(self.conv5(x))
## Flat
x = x.view(x.size(0), -1)
## Dense
x = F.relu(self.linear1(x))
x = self.linear2(x)
return x
if __name__ == "__main__":
net = Net()
print(net)
|
0e269ef6e65c4e73c6d0cf880315b4e082564ac8
|
[
"Python"
] | 2
|
Python
|
vittorio-nardone/Facial-Keypont-Detection
|
3f8ca7418fc0da6198c92185f9da0f96bc02bc0e
|
0bc1990c1dba38b9db339061345ff61d6d4050a0
|
refs/heads/master
|
<repo_name>epilocal/support-local-news<file_sep>/src/components/button.js
import React from 'react';
import "./styles/button.css";
const sizes = {
default: `buttonDefault`,
lg: `buttonLg`,
xl: `buttonXl`
};
const fontSizes = {
default: `0.875rem`,
sm: `0.875rem`,
md: `0.950rem`,
lg: `1.025rem`
};
const Button = ({ children, textSize = '', size, onClick, opposite, outline, customMargin }) => {
return (
<button
style={{
fontSize: `${fontSizes[textSize] || fontSizes.default}`,
fontFamily: 'Nunito',
margin: customMargin,
width: '200px'
}}
type="button"
onClick={onClick}
className={`
${sizes[size] || sizes.default}
${opposite ? `buttonOpposite` : `button`}
${outline ? `buttonOutline` : `button`}
`}
>
{children}
</button>
);
};
export default Button;
<file_sep>/gatsby-config.js
module.exports = {
siteMetadata: {
title: `Support Local News`,
description: `Find an independent, local news site near you.`,
siteUrl: `https://supportlocal.news`,
author: `Epilocal`,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-plugin-image`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `support-local-news`,
short_name: `sln`,
start_url: `/`,
background_color: `#47698e`,
theme_color: `#47698e`,
display: `minimal-ui`,
icon: `src/images/support-local-icon.png`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-s3`,
options: {
protocol: "https",
hostname: "supportlocal.news",
bucketName: "epilocal-supportlocal"
},
},
{
resolve: `gatsby-plugin-plausible`,
options: {
domain: `supportlocal.news`,
},
},
'gatsby-plugin-robots-txt',
`gatsby-plugin-advanced-sitemap`,
{
resolve: `gatsby-plugin-canonical-urls`,
options: {
siteUrl: "https://supportlocal.news",
}
}
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
<file_sep>/src/pages/index.js
import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import Layout from "../components/layout";
import SEO from "../components/seo";
import Button from "../components/button";
import Table from "../components/table";
import Card from "../components/card";
import publications from "../data/publications.json";
import options from "../data/options.json";
const IndexPage = () => {
const getRandomNumber = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const[randomPublication, setRandomPublication] = useState(publications[getRandomNumber(0, publications.length - 1)]);
const[randomFilteredPublication, setRandomFilteredPublication] = useState(publications[getRandomNumber(0, publications.length - 1)]);
const[filteredPublications, setFilteredPublications] = useState([]);
const[showTable, setShowTable] = useState(false);
const[countryValues, setCountryValues] = useState({ selectedOption: []});
const[stateValues, setStateValues] = useState({ selectedOption: []});
const[cityValues, setCityValues] = useState({ selectedOption: []});
const[stateOptions, setStateOptions] = useState([]);
const[cityOptions, setCityOptions] = useState([]);
const toggleShowTable = () => {
setShowTable(!showTable);
}
const newRandomPublication = (pubs) => {
let numPubs = pubs.length;
setRandomPublication(pubs[getRandomNumber(0, numPubs - 1)]);
}
const newRandomFilteredPublication = (pubs) => {
let numPubs = pubs.length;
setRandomFilteredPublication(pubs[getRandomNumber(0, numPubs - 1)]);
}
const countryOptions = Object.keys(options).map( (country) => ({value: country, label: country}));
const toggleDropdown = (values, name) => {
switch (name) {
case 'country':
setCountryValues({selectedOption: values});
if (values.length < 1) {
setStateValues({selectedOption: []});
setStateOptions([]);
setCityValues({selectedOption: []});
setCityOptions([]);
}
break;
case 'state':
setStateValues({selectedOption: values});
if (values.length < 1) {
setCityValues({selectedOption: []});
setCityOptions([]);
}
break;
case 'city':
setCityValues({selectedOption: values});
break;
default:
break
}
}
const filterPublications = () => {
let filteredPubs = publications;
if (countryValues.selectedOption.length > 0) {
let countryLabels = countryValues.selectedOption.map( (country) => country.label );
filteredPubs = filteredPubs.filter( (publication) => {
return countryLabels.indexOf(publication['Country']) > -1;
});
}
if (stateValues.selectedOption.length > 0) {
let stateLabels = stateValues.selectedOption.map( (state) => state.label );
filteredPubs = filteredPubs.filter( (publication) => {
return stateLabels.indexOf(publication['State']) > -1;
});
}
if (cityValues.selectedOption.length > 0) {
let cityLabels = cityValues.selectedOption.map( (city) => city.label );
filteredPubs = filteredPubs.filter( (publication) => {
return cityLabels.indexOf(publication['City']) > -1;
});
}
setFilteredPublications(filteredPubs);
newRandomFilteredPublication(filteredPubs);
}
useEffect(() => {
if (countryValues.selectedOption.length > 0) {
let newStateOptions = countryValues.selectedOption.map( (countryValue) => {
return Object.keys(options[countryValue.label]).map( (state) => ({value: state, label: state}))
});
setStateOptions(newStateOptions[0]);
}
}, [countryValues]);
useEffect(() => {
if (countryValues.selectedOption.length > 0 && stateValues.selectedOption.length > 0) {
let newCityOptions = countryValues.selectedOption.map( (countryValue) => {
return stateValues.selectedOption.map( (stateValue) => {
return Object.keys(options[countryValue.label][stateValue.label]).map( (city) => ({value: city, label: city}))
});
});
setCityOptions(newCityOptions[0][0]);
}
}, [countryValues, stateValues]);
useEffect(() => {
filterPublications()
}, [countryValues, stateValues, cityValues]);
return (
<Layout>
<SEO title="Home" />
<div style={{textAlign: 'center'}}>
<Card>
<h2>Did you know:</h2>
<p style={{fontSize: '1.5rem'}}>1 out of 5 local newspapers in the US has closed or merged since 2004</p>
</Card>
<section style={{paddingTop: '4rem'}}>
<h2 style={{fontSize: '2.5rem'}}>Show some love to an independent, local news site</h2>
<p style={{fontSize: '1.5rem'}}>Clicking on the button below will randomly take you to a local news site in the US or Canada</p>
<a href={randomPublication['URL']} rel="external" onClick={ () => newRandomPublication(publications) }><Button style size='lg' textSize='lg'>Inspire me</Button></a>
<p style={{fontSize: '1.5rem', paddingTop: '3rem'}}>Or use the filters below to find a local news site near you:</p>
<div style={{paddingBottom: '1rem', margin: 'auto'}}>
<Select
className="reactSelect"
name="country-filter"
placeholder="Country"
value={countryValues.selectedOption}
options={countryOptions}
onChange={(values) => toggleDropdown(values, 'country')}
isMulti
/>
<Select
className="reactSelect"
name="state-filter"
placeholder="State / Province"
value={stateValues.selectedOption}
options={stateOptions}
onChange={(values) => toggleDropdown(values, 'state')}
isMulti
isDisabled={stateOptions.length < 1}
/>
<Select
className="reactSelect"
name="city-filter"
placeholder="City / Town"
value={cityValues.selectedOption}
options={cityOptions}
onChange={(values) => toggleDropdown(values, 'city')}
isMulti
isDisabled={cityOptions.length < 1}
/>
</div>
<a href={randomFilteredPublication['URL']} rel="external" onClick={ () => newRandomFilteredPublication(filteredPublications) } ><Button customMargin='.75rem' style size='md' textSize='lg'>Go to random in my area</Button></a>
<Button customMargin='.75rem' style size='md' textSize='lg' onClick={ () => { toggleShowTable() }}>{!showTable ? 'See all in my area' : 'Hide all in my area'}</Button>
{showTable && <Table tableData={filteredPublications} />}
<p style={{fontSize: '1.25rem', paddingTop: '2rem'}}>Made by <a target="_blank" rel="noreferrer" href='https://twitter.com/dickens_greg'>Greg</a> as part of the <a href='https://www.epilocal.com/'>Epilocal</a> project</p>
</section>
</div>
</Layout>
)
}
export default IndexPage
<file_sep>/src/components/table.js
import React from 'react';
import { Table, Thead, Tbody, Tr, Th, Td } from 'react-super-responsive-table';
import './styles/table.css';
const tableHeaders = [
{id: 'url', accesor: 'URL', 'name': 'Site URL'},
{id: 'name', accesor: 'Publication Name', 'name': 'Name'},
{id: 'city', accesor: 'City', 'name': 'City'},
{id: 'state', accesor: 'State', 'name': 'State / Province'},
{id: 'country', accesor: 'Country', 'name': 'Country'}
];
const TableApp = ({tableData}) => {
return (
<Table>
<Thead>
<Tr>
{tableHeaders.map( (header, i) => (
<Th key={`th-${i}`}>{header.name}</Th>
))}
</Tr>
</Thead>
<Tbody>
{tableData.map( (row, r) => (
<Tr>
{tableHeaders.map( (cell, c) => {
if (cell.id === 'url') {
return (
<Td key={`td-${r}-${c}`}><a href={row[cell.accesor]} rel="external">{row[cell.accesor]}</a></Td>
)
}
return (
<Td key={`td-${r}-${c}`}>{row[cell.accesor]}</Td>
)
})}
</Tr>
))}
</Tbody>
</Table>
)
}
export default TableApp;
|
b8da0a28da0bbcc0993629022c8ab54255100bdd
|
[
"JavaScript"
] | 4
|
JavaScript
|
epilocal/support-local-news
|
09b1a64fe20ed8cb0fa749b571adae78ad7bd11e
|
06d838f3d7e0787af65ae2cd5645542d61db1d9f
|
refs/heads/main
|
<file_sep># frozen_string_literal: true
source "https://rubygems.org" do
gem "kitchen-terraform", "~> 5.8"
gem "inspec-bin", "~> 4.37"
end
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# gem "rails"
<file_sep>FROM hashicorp/terraform:1.0.2
COPY .ruby-version .ruby-version
# Update and install all of the required packages.
# At the end, remove the apk cache
RUN apk upgrade && \
apk add --update \
bash \
curl-dev \
curl \
"ruby-dev=~$(cat .ruby-version)" \
"ruby-full=~$(cat .ruby-version)" \
build-base \
python3 && \
rm -rf /var/cache/apk/*
RUN mkdir /usr/app
WORKDIR /usr/app
COPY Gemfile* ./
RUN gem install bundler && \
bundle config set system 'true' && \
bundle install
ENTRYPOINT ["/bin/bash"]<file_sep>title "Test creation of GCP logging export resources"
# Terraform outputs defined in examples/*/outputs.tf
# become directly available to Ispec tests as attributes
sumologic_endpoint = attribute("sumologic_endpoint")
google_project_id = attribute("google_project_id")
google_pubsub_topic_id = attribute("google_pubsub_topic_id")
google_pubsub_topic_name = attribute("google_pubsub_topic_name")
google_pubsub_subscription_id = attribute("google_pubsub_subscription_id")
google_pubsub_subscription_name = attribute("google_pubsub_subscription_name")
google_topic_iam_publisher = attribute("google_topic_iam_publisher")
control 'gcp configuration' do
describe google_pubsub_subscriptions(project: google_project_id) do
its('count') { should be >= 1 }
end
describe google_pubsub_topic(project: google_project_id, name: google_pubsub_topic_name) do
it { should exist }
end
google_pubsub_topic_iam_policy(project: google_project_id, name: google_pubsub_topic_name).bindings.each do |binding|
describe binding do
its('role') { should eq 'roles/pubsub.publisher'}
its('members') { should include google_topic_iam_publisher}
end
end
describe google_pubsub_subscription(project: google_project_id, name: google_pubsub_subscription_name) do
it { should exist }
its('topic') {should eq google_pubsub_topic_id}
its('push_config.push_endpoint') {should eq sumologic_endpoint}
end
end<file_sep># terraform-sumologic-gcp-soruce
This repo contains terraform code to help you route log messages from a GCP project to a sumologic GCP collector. The parent module creates both a GCP source on a pre-existing collector in sumologic and a topic, pubsub log router, and pubsub push subscription in GCP.
<!-- update badge link below for your repo! -->

# Contents:
- [Getting Started](#getting-started)
- [Basic Implementation](#basic-implementation)
- [Requirements](#requirements)
- [Providers](#providers)
- [Inputs](#inputs)
- [Testing](#testing)
- [Development](#development)
## Getting Started
Both an existing sumologic hosted collector and GCP project must exist prior to execution, this module does not create those objects. `modules/sumologic-gcp-source` can be used by itself as a basis for other logging functionality.
In GCP, you will also need to disable domain-restricted sharing for your project directly or by inheritence, as this module needs to add `roles/pubsub.publisher` to a Google-owned service account.
## Basic Implementation
```terraform
module "gcp-log-export" {
source = "../.."
project_id = "my-project-sr2f"
sumologic_collector_id = "1242652142"
name = "my-gcp-log-export"
gcp_filters = {
gke = "resource.type=\"gke_cluster\" OR resource.type=\"k8s_cluster\" OR resource.type=\"k8s_node\" OR resource.type=\"k8s_pod\"",
project = "resource.type=\"project\""
}
}
```
This will create both a sumologic GCP source as well as all the plumbing in your GCP project to export logs to sumologic. The `gcp_filters` parameter is important, as you need to set up at least one filter to be able to send any logs at all. These can be built using the Stackdriver log explorer in the GCP Cloud Console. `gcp_filters` is a map, so you can build an unlimited number of filters based on the logs you need. The example here will get you all GKE logs and project logs.
<!-- The content below is automatically generated by fmt precommit hook -->
<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Requirements
| Name | Version |
|------|---------|
| <a name="requirement_terraform"></a> [terraform](#requirement\_terraform) | ~> 1.0 |
| <a name="requirement_google"></a> [google](#requirement\_google) | 3.74 |
| <a name="requirement_sumologic"></a> [sumologic](#requirement\_sumologic) | >= 2.9, < 3.0 |
## Providers
| Name | Version |
|------|---------|
| <a name="provider_google"></a> [google](#provider\_google) | 3.74 |
## Modules
| Name | Source | Version |
|------|--------|---------|
| <a name="module_sumologic-gcp-source"></a> [sumologic-gcp-source](#module\_sumologic-gcp-source) | ./modules/sumologic-gcp-source | n/a |
## Resources
| Name | Type |
|------|------|
| [google_logging_project_sink.logged_messages](https://registry.terraform.io/providers/hashicorp/google/3.74/docs/resources/logging_project_sink) | resource |
| [google_pubsub_subscription.push](https://registry.terraform.io/providers/hashicorp/google/3.74/docs/resources/pubsub_subscription) | resource |
| [google_pubsub_topic.topic](https://registry.terraform.io/providers/hashicorp/google/3.74/docs/resources/pubsub_topic) | resource |
| [google_pubsub_topic_iam_member.member](https://registry.terraform.io/providers/hashicorp/google/3.74/docs/resources/pubsub_topic_iam_member) | resource |
## Inputs
| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| <a name="input_category"></a> [category](#input\_category) | Single-word category that logs for this search will go into. Will be concated with parent\_categories | `string` | `""` | no |
| <a name="input_gcp_filters"></a> [gcp\_filters](#input\_gcp\_filters) | List of map of filters to create and be routed into the pubsub topic and push | `map(string)` | `{}` | no |
| <a name="input_name"></a> [name](#input\_name) | Name to use uniformally for the log source, pubsub topic, and pubsub subscription | `string` | n/a | yes |
| <a name="input_parent_categories"></a> [parent\_categories](#input\_parent\_categories) | A hierarchy of terms that make up the parent categories. Important if using search partitioning | `list(string)` | `[]` | no |
| <a name="input_project_id"></a> [project\_id](#input\_project\_id) | GCP Project ID where the GCP resources should be created | `string` | n/a | yes |
| <a name="input_pubsub_sa_publisher_account"></a> [pubsub\_sa\_publisher\_account](#input\_pubsub\_sa\_publisher\_account) | GCP Service Account to assign roles/pubsub.publisher to. | `string` | `"serviceAccount:<EMAIL>"` | no |
| <a name="input_push_deadline_seconds"></a> [push\_deadline\_seconds](#input\_push\_deadline\_seconds) | Maximum amount of time for the subscription to wait for acknowledgement of reciept of message | `number` | `20` | no |
| <a name="input_source_description"></a> [source\_description](#input\_source\_description) | Description to use for the source | `string` | `""` | no |
| <a name="input_sumologic_collector_id"></a> [sumologic\_collector\_id](#input\_sumologic\_collector\_id) | ID of the hosted collector at sumologic that will recieve messages for the new source | `string` | n/a | yes |
## Outputs
| Name | Description |
|------|-------------|
| <a name="output_google_pubsub_subscription_id"></a> [google\_pubsub\_subscription\_id](#output\_google\_pubsub\_subscription\_id) | n/a |
| <a name="output_google_pubsub_subscription_name"></a> [google\_pubsub\_subscription\_name](#output\_google\_pubsub\_subscription\_name) | n/a |
| <a name="output_google_pubsub_subscription_shortid"></a> [google\_pubsub\_subscription\_shortid](#output\_google\_pubsub\_subscription\_shortid) | n/a |
| <a name="output_google_pubsub_topic_id"></a> [google\_pubsub\_topic\_id](#output\_google\_pubsub\_topic\_id) | n/a |
| <a name="output_google_pubsub_topic_name"></a> [google\_pubsub\_topic\_name](#output\_google\_pubsub\_topic\_name) | n/a |
| <a name="output_google_topic_iam_publisher"></a> [google\_topic\_iam\_publisher](#output\_google\_topic\_iam\_publisher) | n/a |
| <a name="output_sumologic_endpoint"></a> [sumologic\_endpoint](#output\_sumologic\_endpoint) | n/a |
<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Testing
This repository uses Kitchen-Terraform to test the terraform modules. In the [examples](/examples)directory you can find examples of how each module can be used. Those examples are fed to [Test Kitchen][https://kitchen.ci/]. To install test kitchen, first make sure you have Ruby and bundler installed.
```
brew install ruby
gem install bundler
```
Then install the prerequisites for test kitchen.
```
bundle install
```
You'll need to add some common credentials and secret variables
And now you're ready to run test kitchen. Test kitchen has a couple main commands:
- `bundle exec kitchen create` initializes terraform.
- `bundle exec kitchen converge` runs our terraform examples.
- `bundle exec kitchen verify` runs our inspec scripts against a converged kitchen.
- `bundle exec kitchen test` does all the above.
## Development
### Merging Policy
Use [GitLab Flow](https://docs.gitlab.com/ee/topics/gitlab_flow.html#production-branch-with-gitlab-flow).
* Create feature branches for features and fixes from default branch
* Merge only from PR with review
* After merging to default branch a release is drafted using a github action. Check the draft and publish if you and tests are happy
### Pre-commit hooks
Install and configure terraform [pre-commit hooks](https://github.com/antonbabenko/pre-commit-terraform)
To run them: `pre-commit run -a`
### CI
This project has three workflows enabled:
1. PR labeler: When openning a PR to default branch, a label is given automatically according to the name of your feature branch. The labeler follows thenrules in [pr-labeler.yml](.github/pr-labeler.yml)
2. Release Drafter: When merging to master, a release is drafted using the [Release-Drafter Action](https://github.com/marketplace/actions/release-drafter)
3. `Kitchen test` is run on every commit unless `[skip ci]` is added to commit message.
<file_sep>title "Test creation of sumologic GCP logging source"
# Grab some env variables in order to validate certain configs
sumologic_base64 = ENV["SUMOLOGIC_BASE64"]
# Terraform outputs defined in examples/*/outputs.tf
# become directly available to Ispec tests as attributes
sumologic_source_id = attribute("id")
sumologic_collector_id = ENV["TF_VAR_sumologic_collector_id"]
sumologic_source_name = attribute("name")
sumologic_endpoint = attribute("url")
sumologic_source_category = attribute("source_category")
sumologic_source_filters = attribute("filters")
control 'http_test' do
describe http("https://api.us2.sumologic.com/api/v1/collectors/#{sumologic_collector_id}/sources/#{sumologic_source_id}",
headers: {
'Accept' => 'application/json',
'Authorization' => "Basic #{sumologic_base64}"
}) do
its('status') { should eq 200 }
end
end
control 'sumologic configuration' do
http_request = http("https://api.us2.sumologic.com/api/v1/collectors/#{sumologic_collector_id}/sources/#{sumologic_source_id}",
headers: {
'Accept' => 'application/json',
'Authorization' => "Basic #{sumologic_base64}"
})
describe json(content: http_request.body) do
its(['source', 'id']) {should eq Integer(sumologic_source_id)}
its(['source', 'name']) {should eq sumologic_source_name}
its(['source', 'thirdPartyRef', 'resources', 0, 'serviceType']) {should eq 'GoogleCloudLogs'}
its(['source', 'url']) {should eq sumologic_endpoint}
end
end
|
2ffe096416b97a53d471752c13affe4f978fa562
|
[
"Markdown",
"Ruby",
"Dockerfile"
] | 5
|
Ruby
|
BrownUniversity/terraform-sumologic-gcp-source
|
2e2588d2b24c795530a6d01086a7ff40a27d8c27
|
a2e2ae9b47f0a7dcbf410c2a6b33273ca38b87f7
|
refs/heads/master
|
<file_sep>import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
if (sessionStorage.getItem('entry') !== null) {
return {
entry: JSON.parse(sessionStorage.entry)
}
}
else if ((sessionStorage.getItem('entry') !== null) && (sessionStorage.getItem('order') !== null)) {
return {
order: JSON.parse(sessionStorage.order),
entry: JSON.parse(sessionStorage.entry)
}
}
},
actions: {
saveEntry() {
var entry = new Object();
var newEntry = new Object();
if (sessionStorage.getItem('entry') !== null) {
newEntry.id = (JSON.parse(sessionStorage.entry)).length + 1;
} else {
newEntry.id = 1;
}
newEntry.productTitle = document.getElementById("productTitle").value; //ima drugačno vrednost z vsakim klikom
newEntry.stock = document.getElementById("stock").value;
newEntry.price = document.getElementById("price").value;
newEntry.itemImage = document.getElementById("itemImage").value;
if (sessionStorage.entry) {
entry = JSON.parse(sessionStorage.getItem('entry'));
}
else {
entry = [];
}
entry.push(newEntry)
sessionStorage.setItem('entry', JSON.stringify(entry));
var retrievedObject = sessionStorage.getItem('entry');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
console.log(JSON.parse(sessionStorage.entry));
document.getElementById("new-entry").reset();
location.reload();
},
deleteEntry() {
}
}
});
<file_sep>import Ember from 'ember';
export default Ember.Route.extend({
model() {
if ((sessionStorage.getItem('entry') !== null) && (sessionStorage.getItem('order') !== null)) {
return {
order: JSON.parse(sessionStorage.order),
entry: JSON.parse(sessionStorage.entry),
total: sessionStorage.total
}
}
},
actions: {
computeTotal() {
var sum;
(JSON.parse(sessionStorage.order)).reduce(function(prevVal, elem) {
sum = prevVal + elem.subtotal;
return sum;
}, 0);
sessionStorage.setItem("total", sum);
console.log(sessionStorage);
console.log('sum', sum);
location.reload();
}
}
});
<file_sep>import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('new-entry', function() {
this.route('entry-list');
});
this.route('new-order', function(){
this.route('test');
});
this.route('entry-list');
this.route('order-list');
});
export default Router;
<file_sep>import Ember from 'ember';
export default Ember.Route.extend({
model() {
if (sessionStorage.getItem('entry') !== null) {
return {
entry: JSON.parse(sessionStorage.entry)
}
}
else if ((sessionStorage.getItem('entry') !== null) && (sessionStorage.getItem('order') !== null)) {
return {
order: JSON.parse(sessionStorage.order),
entry: JSON.parse(sessionStorage.entry),
total: sessionStorage.total
}
}
},
actions: {
saveItem() {
var order = new Object();
var newOrder = new Object();
var e = document.getElementById("productTitleDropDown");
var beerIndex = e.selectedIndex // retrieves index of beer object in array of entries
newOrder.beerTitle = e.options[e.selectedIndex].text;
newOrder.quantity = document.getElementById("quantity").value;
newOrder.price = JSON.parse(sessionStorage.entry)[beerIndex].price;
newOrder.subtotal = newOrder.price * newOrder.quantity;
// console.log(JSON.parse(sessionStorage.entry)[beerIndex].stock);
console.log("subtotal", newOrder.subtotal);
JSON.parse(sessionStorage.entry)[beerIndex].stock == JSON.parse(sessionStorage.entry)[beerIndex].stock - 5;
// console.log(JSON.parse(sessionStorage.entry)[beerIndex].stock);
if(sessionStorage.order)
{
order= JSON.parse(sessionStorage.getItem('order'));
}else{
order=[];
}
order.push(newOrder)
sessionStorage.setItem('order', JSON.stringify(order));
var retrievedObject = sessionStorage.getItem('order');
document.getElementById("order-form").reset();
console.log(JSON.parse(sessionStorage.order));
},
}
});
<file_sep>import Ember from 'ember';
export function multiply(params) {
return params.reduce((a,b) => {
return a * b;
});
};
export default Ember.Helper.helper(multiply);
|
ec52d0968504d9c538da91cfc368294acbe27699
|
[
"JavaScript"
] | 5
|
JavaScript
|
marusa15/beerFTW
|
cdf7bfe5f6c61bf857bf7e80ab1f04ea1f7b37dd
|
7b7f598a49640bef129aa4927a6d5b8a647cda8c
|
refs/heads/master
|
<repo_name>drewler/babylon-test<file_sep>/src/BabylonPage.js
import * as React from 'react';
import * as BABYLON from 'babylonjs';
import 'babylonjs-loaders';
import BabylonScene from './BabylonScene'; // import the component above linking to file we just created.
export default class BabylonPage extends React.Component<{}, {}> {
onSceneMount = (e) => {
const { canvas, scene, engine } = e;
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
// var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
const octo = BABYLON.SceneLoader.ImportMesh(null, "./", "aria.stl", scene, function(scene){
// const octo = BABYLON.SceneLoader.ImportMesh(null, "./", "CuteOcto.stl", scene, function(scene){
scene[0].showBoundingBox = true;
const boundingInfo = scene[0].getBoundingInfo();
const ratio = 5.0/boundingInfo.boundingSphere.radius;
// debugger;
scene[0].position.y = (0 - boundingInfo.minimum.y) * ratio;
scene[0].scaling.x = ratio;
scene[0].scaling.y = ratio;
scene[0].scaling.z = ratio;
// debugger;
console.log(boundingInfo)
// debugger;
// return scene;
});
// This creates and positions a free camera (non-mesh)
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(-12, 8, 12), scene);
// This targets the camera to scene origin
camera.setTarget(new BABYLON.Vector3(0, 5, 0));
// This attaches the camera to the canvas
camera.attachControl(canvas, true);
camera.keysUp.push(87); //W
camera.keysLeft.push(65); //A
camera.keysRight.push(68); //S
camera.keysDown.push(83) //D
// Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
engine.runRenderLoop(() => {
if (scene) {
scene.render();
}
});
}
render() {
return (
<div>
{/* <BabylonScene width={100} height={100} onSceneMount={this.onSceneMount} /> */}
<BabylonScene width={800} height={480} onSceneMount={this.onSceneMount} />
</div>
)
}
}
|
c18900742b60f811633101b9f0f90b46112ca33b
|
[
"JavaScript"
] | 1
|
JavaScript
|
drewler/babylon-test
|
d5dad415ff0c82170c327030725ae40b98aadcd3
|
b3b5b75b21796ba14792a5af4b63801308fe5a1f
|
refs/heads/master
|
<file_sep><?php
namespace App\Admin\Controllers;
use App\Models\File;
use App\Models\Book;
use App\Models\Catalog;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Storage;
class FileController extends AdminController
{
/**
* Title for current resource.
*
* @var string
*/
protected $title = 'File';
/**
* Make a grid builder.
*
* @return Grid
*/
protected function grid()
{
$grid = new Grid(new File());
$grid->column('id', '編號');
$grid->column('book_id', '書本')->display(function($book_id){
return Book::find($book_id)->name;
});
$grid->column('path','檔案')->display(function($path) {
$name = "";
foreach ($path as $file) {
$name .= "<a target='_blank' href='" . Storage::disk('admin')->url($file) . "'>" . basename($file) . "</a><br>";
}
return $name;
});;
$grid->column('catalog_id', '類別')->display(function($catalog_id){
return Catalog::find($catalog_id)->name;
});
$grid->column('created_at', __('Created at'));
$grid->column('updated_at', __('Updated at'));
return $grid;
}
/**
* Make a show builder.
*
* @param mixed $id
* @return Show
*/
protected function detail($id)
{
$show = new Show(File::findOrFail($id));
$show->field('id', __('Id'));
// $show->field('name', __('Name'));
// $show->field('origin_name', __('Origin name'));
// $show->field('size', __('Size'));
// $show->field('path', __('Path'));
// $show->field('book_id', __('Book id'));
// $show->field('catalog_id', __('Catalog id'));
// $show->field('created_at', __('Created at'));
// $show->field('updated_at', __('Updated at'));
return $show;
}
/**
* Make a form builder.
*
* @return Form
*/
protected function form()
{
$form = new Form(new File());
$form->select('book_id', '書籍')->options(Book::getSelectOptions())->required();
$form->select('catalog_id', '分類')->options(Catalog::getSelectOptions());
$form->multipleFile('path','檔案')->move(function($form){
return '/files/' . dump($form->book_id);
})->removable()->name(function ($file){
return $file->getClientOriginalName();
});
return $form;
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Book;
use App\Models\Catalog;
use Storage;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name',
'path',
];
protected $casts = [
'path' => 'json',
];
public static function boot()
{
parent::boot();
self::creating(function($model){
// dd($model->path);
// $model->name = basename($model->path);
// $model->size = Storage::size($model->path);
});
self::created(function($model){
});
self::updating(function($model){
});
self::updated(function($model){
});
self::deleting(function($model){
// ... code here
});
self::deleted(function($model){
// ... code here
});
}
public function book()
{
return $this->belongsTo(Book::class);
}
/**
* Get the user that owns the File
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function catalog()
{
return $this->belongsTo(Catalog::class);
}
public static function getSelectOptions()
{
$options = DB::table('files')->select('id','name as text')->get();
$selectOption = [];
foreach ($options as $option){
$selectOption[$option->id] = $option->text;
}
return $selectOption;
}
}
<file_sep><?php
namespace App\Admin\Controllers;
use App\Models\Book;
use App\Models\Subject;
use App\Models\Publisher;
use App\Models\File;
use App\Models\Catalog;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
class BookController extends AdminController
{
/**
* Title for current resource.
*
* @var string
*/
protected $title = '書籍';
/**
* Make a grid builder.
*
* @return Grid
*/
protected function grid()
{
$grid = new Grid(new Book());
$grid->quickSearch('name');
// $grid->column('id', __('編號'));
$grid->column('cover','封面')->image('', 100, 100);
$grid->column('name', __('書名'));
$grid->column('subject.name', __('科目'));
$grid->column('publisher.name', __('出版社'));
$grid->column('released','發布')->switch();
return $grid;
}
/**
* Make a show builder.
*
* @param mixed $id
* @return Show
*/
protected function detail($id)
{
$show = new Show(Book::findOrFail($id));
$show->field('cover', __('封面'))->image();
$show->field('name', '書名');
$show->field('sid', '書號');
$show->field('isbn', 'ISBN');
$show->field('publish_year', '發售年');
$show->field('publisher.name', '出版社');
$show->field('describe', __('描述'));
$show->field('created_at', __('建立日期'));
$show->field('updated_at', __('更新日期'));
return $show;
}
/**
* Make a form builder.
*
* @return Form
*/
protected function form()
{
$form = new Form(new Book());
$form->column(1/3, function ($form) {
$form->image('cover', '封面')->removable();
});
$form->column(2/3, function ($form) {
$form->text('name', '書名');
$form->text('sid', '書號');
$form->text('isbn', 'ISBN');
$form->text('publish_year', '發售年');
$form->select('publisher_id', '出版社')->options(Publisher::getSelectOptions());
$form->select('subject_id', '科目')->options(Subject::getSelectOptions());
$form->textarea('describe', '描述')->rows(10);
$form->switch('released', '發布?');
});
// $form->display('id');
return $form;
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Catalog;
use App\Models\File;
use Illuminate\Http\Request;
use App\Models\Publisher;
class BookController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$publishers = Publisher::with(['books' => function($q){
$q->where('released','=', true);
}])->get();
return view('book.index',['publishers' => $publishers]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function show($id, Request $request)
{
$book = Book::with(['files' => function($q) use ($request){
if ($request->catalog && $request->catalog != "all"){
$q->where('catalog_id','=', $request->catalog);
}
},'subject','publisher'])->findOrFail($id);
$files = File::where('book_id', '=', $book->id)->get();
$catalog_id = [];
foreach ($files as $file) {
array_push($catalog_id, $file->catalog_id);
}
$catalogs = Catalog::whereIn('id',$catalog_id)->get();
return view('book.show',['book' => $book,'catalogs' => $catalogs,'request' => $request]);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function edit(Book $book)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Book $book)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function destroy(Book $book)
{
//
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// $path = storage_path('app/public/14/課本');
// $files = File::Files($path);
// $dir = scandir($path);
// dd($files);
// $a = "";
// foreach ($files as $file) {
// $a .= $file->getFileInfo() . "\n";
// }
// dd($a);
// return response()->download($path);
// return view('welcome');
// });
Route::get('/', [BookController::class,'index']);
Route::resource('books', BookController::class);
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Publisher;
use App\Models\Subject;
use App\Models\File;
use DB;
class Book extends Model
{
use HasFactory;
public function subject()
{
return $this->belongsTo(Subject::class);
}
public function files()
{
return $this->hasMany(File::class);
}
public function publisher()
{
return $this->belongsTo(Publisher::class);
}
public static function getSelectOptions()
{
$options = DB::table('books')->select('id','name as text')->get();
$selectOption = [];
foreach ($options as $option){
$selectOption[$option->id] = $option->text;
}
return $selectOption;
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('sid');
$table->string('name');
$table->string('cover')->nullable();
$table->string('publish_year');
$table->string('isbn')->nullable();
$table->text('describe')->nullable();
$table->boolean('released')->default(false);
$table->foreignId('subject_id');
$table->foreignId('publisher_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
<file_sep>require('./bootstrap');
$("input.select-all").click(function () {
var checked = this.checked;
$("input.select-item").each(function (index,item) {
item.checked = checked;
});
});
$('.view-online').click(function (e) {
alert('開發中!');
e.preventDefault();
});
$('#file-type').change(function (e) {
location.href = '/books/' + $(this).data('book_id') + '?catalog=' + $(this).val();
e.preventDefault();
});<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Book;
use DB;
class Subject extends Model
{
use HasFactory;
/**
* Get all of the books for the Subject
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function books()
{
return $this->hasMany(Book::class);
}
public static function getSelectOptions()
{
$options = DB::table('subjects')->select('id','name as text')->get();
$selectOption = [];
foreach ($options as $option){
$selectOption[$option->id] = $option->text;
}
return $selectOption;
}
}
|
c732237932b5891836fe1d55c72c9fb6037c431e
|
[
"JavaScript",
"PHP"
] | 9
|
PHP
|
lee98064/ans-site
|
21b4801abaf59784e418b59b10df36d72e177040
|
b5e4e1a97a8188f090b4883f0257046d8d1ef67b
|
refs/heads/main
|
<repo_name>SIGMAOON/Binary_Search<file_sep>/boj_2343.py
# 기타 레슨
def blue_ray(lists,mid):
cnt = 1
total = 0
for l in lists:
if total+l > mid:
cnt+=1
total = l
else:
total+=l
return cnt
N,M = map(int,input().split())
lesson = list(map(int,input().split()))
start = max(lesson)
end = sum(lesson)
while start<=end:
mid = (start+end)//2
if blue_ray(lesson,mid) <= M:
end = mid - 1
else:
start = mid + 1
print(start)<file_sep>/boj_2470.py
# 두 용액
import sys
N = int(input())
portion = sorted(list(map(int,sys.stdin.readline().split())))
start = 0
end = len(portion) - 1
minimum = sys.maxsize
pair = []
while start<end:
answer = portion[start]+portion[end]
if abs(answer) < minimum:
pair = [portion[start],portion[end]]
minimum = abs(answer)
if answer < 0:
start +=1
else:
end-=1
print(pair[0],pair[1])<file_sep>/boj_7795.py
# 먹을 것인가 먹힐 것인가
def findInx(lists,n):
start = 0
end = len(lists)-1
idx = -1 # A[0]<=B[0]면 0 돌려줌
while start<=end:
mid = (start+end)//2
if lists[mid] < n:
idx = mid
start = mid + 1
else:
end = mid - 1
return idx + 1 # 개수는 인덱스보다 하나 크니까,,,,
T = int(input())
for _ in range(T):
cnt = 0
numA,numB = map(int,input().split())
A = sorted(list(map(int,input().split())))
B = sorted(list(map(int,input().split())))
for a in A:
cnt+=findInx(B,a)
print(cnt) <file_sep>/378.py
# Kth Smallest Element in a Sorted Matrix
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
_all = []
for num in matrix:
for n in num:
_all.append(n)
_all.sort()
return _all[k-1]<file_sep>/29.py
# Divide Two Integers
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
MAX = 2**31 - 1
MIN = -1*(2**31)
result = int(dividend/divisor)
if result > MAX:
return MAX
elif result < MIN:
return MIN
return result<file_sep>/boj_16401.py
# 과자 나눠주기
joca,snackN = map(int,input().split())
snack = list(map(int,input().split())) # 정렬되어있음
start,end = 1, max(snack)
length = 0
while start<=end:
mid = (start+end)//2
cnt = 0
for yamyam in snack:
cnt+= yamyam//mid
if cnt >= joca:
length = mid
start = mid + 1
else:
end = mid - 1
print(length)<file_sep>/287.py
# Find the Duplicate Number
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
dic = {}
for num in nums:
dic[num] = 0
for num in nums:
dic[num]+=1
if dic[num] > 1:
return num<file_sep>/240.py
# Search a 2D Matrix II
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
for i in range(n):
for j in range(m):
if matrix[j][i] == target:
return True
elif matrix[j][i] > target:
break
return False<file_sep>/34.py
# Find First and Last Position of Element in Sorted Array
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
answer = []
for i in range(len(nums)):
if nums[i] == target:
answer.append(i)
if answer == []:
return [-1,-1]
return [answer[0],answer[-1]]<file_sep>/boj_1072.py
# 게임
X,Y = map(int,input().split())
Z = int(100*Y/X)
start = 1
end = 10000000000
while start < end:
mid = (start+end)//2
newZ = int(100*(Y+mid)/(X+mid))
if newZ <= Z:
start = mid+1
else:
end = mid
if int(100*(Y+end)/(X+end)) > Z:
print(end)
else:
print(-1)<file_sep>/boj_1300.py
# K번째 수
# A는 N*N 행렬, A[i][j] = i*j
# B는 A의 오름차순, B[k] = ?
N = int(input())
k = int(input())
start = 1
end = k
while start<= end:
mid = (start+end)//2
cnt = 0
for i in range(1,N+1):
cnt+=min(N,mid//i)
if cnt < k:
start = mid + 1
else:
end = mid - 1
print(start)
<file_sep>/README.md
# Binary_Search
binary search problem solving
(leetcoed, Baekjoon)
<file_sep>/boj_19592.py
# 장난감 경주 . 수정필요
T = int(input())
for _ in range(T):
N,X,Y = map(int,input().split())
V = list(map(int,input().split()))
fastest = X/max(V[:-1]) # 나를 제외하고 가장 최단시간에 들어온 사람의 시간
if fastest > X/V[-1]:
print(0)
elif 1+((X-Y)/V[-1]) >= fastest:
print(-1)
else:
start = 0
end = Y
while start < end:
mid = (start+end)//2
if 1+((X-mid)/V[-1]) < fastest:
end = mid
else:
start = mid + 1
print(end)<file_sep>/boj_19637.py
# IF문 좀 대신 써줘
import sys
N, M = map(int, sys.stdin.readline().split())
NamePower = [sys.stdin.readline().split() for _ in range(N)]
for _ in range(M):
start = 0
end = len(NamePower) - 1
x = int(sys.stdin.readline())
while start<=end:
mid = (start+end)//2
if x <= NamePower[mid][1]:
end = mid - 1
else:
start = mid + 1
print(NamePower[start][0]) <file_sep>/boj_2110.py
# 공유기 설치
def count_wifi(lists,mid):
cnt = 1
before = lists[0]
for i in range(1,len(lists)):
if lists[i] >= before + mid:
cnt+=1
before = lists[i]
return cnt
h,wifi = map(int,input().split())
home = sorted([int(input()) for _ in range(h)])
start = 1
end = home[-1] - home[0]
answer =0
while start<=end:
mid = (start+end)//2
x = count_wifi(home,mid)
if x >= wifi:
start = mid + 1
else:
end = mid - 1
print(answer)<file_sep>/boj_3079.py
# 입국 심사
import sys
gate,sangs = map(int,sys.stdin.readline().split())
gates = [int(sys.stdin.readline()) for _ in range(gate)]
start = min(gates)
end = max(gates)*sangs
answer = 0
while start<=end:
mid = (start+end)//2
total = 0
for g in gates:
total += mid//g
if total < sangs:
start = mid + 1
else:
end = mid - 1
answer = mid
print(answer)<file_sep>/boj_2792.py
# 보석 상자.pypy3
def count_people(lists,mid):
cnt = 0
for num in lists:
a = num//mid
b = num%mid
cnt += a
if b != 0:
cnt +=1
return cnt
child,color = map(int,input().split())
jewl = sorted([int(input()) for _ in range(color)])
start = 1
end = jewl[-1]
while start < end:
mid = (start+end)//2
if count_people(jewl,mid) <= child:
end = mid
else:
start = mid + 1
print(end)<file_sep>/boj_14426.py
# 접두사 찾기,pypy3
N,M = map(int,input().split())
string = [input() for _ in range(N)]
cnt = 0
for _ in range(M):
prefix = input()
for s in string:
if prefix == s[:len(prefix)]:
cnt+=1
break
print(cnt)<file_sep>/4.py
# Median of Two Sorted Arrays
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
total = nums1 + nums2
total.sort()
l = len(total)
if l % 2 == 1:
return total[l//2]
return (total[l//2] + total[l//2 - 1])/2<file_sep>/boj_17266.py
# 어두운 굴다리
def cover_check(bridge,cover):
# 맨 앞, 맨 뒤 처리 후 가운데 처리
if (bridge[1] - bridge[0]) > cover:
return False
if (bridge[-1]- bridge[-2]) > cover:
return False
for i in range(1,len(bridge)-2):
if (bridge[i+1] - bridge[i])/2 > cover:
return False
return True
N = int(input()) # 굴다리의 길이
M = int(input()) # 가로등의 개수
x = list(map(int,input().split())) # 가로등의 위치
bridge = [0] + x + [N]
start,end = 0,N
height = 0
while start<=end:
mid = (start+end)//2
if cover_check(bridge,mid):
end = mid - 1
height = mid
else:
start = mid + 1
print(height)<file_sep>/boj_6236.py
# 용돈 관리
def Mcountdown(lists,k):
total = 0
cnt = 1
for money in lists:
if total+money > k:
cnt+=1 # 인출 범위를 넘어가면 한 번 더 인출해야함
total = money # 새로 인출함. 초기화.
else:
total+=money
return cnt
N,M = map(int,input().split())
use = []
for _ in range(N):
use.append(int(input()))
start = max(use) # 매일 인출이 가능하려면,,,,
end = sum(use) # 한 번만 인출하면 됨
while start<=end:
mid = (start+end)//2
if Mcountdown(use,mid) <= M:
end = mid - 1
else:
start = mid + 1
print(mid)<file_sep>/boj_16564.py
# 히오스 프로게이머
def total(lists,K):
total = 0
for xi in lists:
if xi >= K:
return total
total += (K-xi)
return total
N,K = map(int,input().split())
X = sorted([int(input()) for _ in range(N)])
start,end = min(X),max(X) + K
answer = 0
while start<=end:
mid = (start+end)//2
if total(X,mid) <= K: # total이 K보다 작아야함
answer = mid
start = mid + 1
else:
end = mid - 1
print(answer)<file_sep>/boj_14627.py
# 파닭파닭. 수정 필요
pa_num,chicken = map(int,input().split())
pas = [int(input()) for _ in range(pa_num)]
pa_total = sum(pas)
start = 1
end = max(pas)
answer = 0
while start<=end:
mid = (start+end)//2
cnt = 0
for pa in pas:
cnt+=pa//mid
if cnt >= chicken:
answer = mid
start = mid + 1
else:
end = mid - 1
print(pa_total - answer*chicken)
|
ff5656e6ac33a4aafe9112e3f1d6fdcdde6ee328
|
[
"Markdown",
"Python"
] | 23
|
Python
|
SIGMAOON/Binary_Search
|
334cf7966c9130b0d666876eb2c875384c8283aa
|
677a723c11f721a9e095f5a24492a0371a444a80
|
refs/heads/master
|
<repo_name>davidjaggi/miniprojects<file_sep>/MITx_6.00.1x/PS3/PS_3.1.py
# Is the world guessed
secretWord = 'apple'
lettersGuessed = ['e','i','k','p','r','s']
# lettersGuessed = ['a','p','p','l','e']
def isWordGuessed(secretWord, lettersGuessed):
for char in secretWord:
if char not in lettersGuessed:
return False
return True
print(isWordGuessed(secretWord, lettersGuessed))
<file_sep>/DailyProgrammer/20180509_DailyProgrammer_Nearest_Airplane.py
# https://www.reddit.com/r/dailyprogrammer/comments/8i5zc3/20180509_challenge_360_intermediate_find_the/
import urllib.request, json
from math import acos, sin, cos, radians, atan2
with urllib.request.urlopen("https://opensky-network.org/api/states/all") as url:
data = json.loads(url.read().decode())['states']
EARTH_RAD = 6371
def geo_dist(x,y):
xrad = [radians(d) for d in x]
yrad = [radians(d) for d in y]
return EARTH_RAD*acos(sin(xrad[0])*sin(yrad[0])+
cos(xrad[0])*cos(yrad[0])*
cos(abs(xrad[1]-yrad[1])))
def get_closest(longitude, lattitude):
closest = data[0],10000000
for plane in data:
if None in plane[5:7]: continue
dist = geo_dist(plane[5:7],[longitude,lattitude])
if dist < closest[1]:
closest = plane, dist
print("closest plane to ",longitude,"E ",lattitude,"N")
print("Geodesic distance:", closest[1])
print("Callsign:", closest[0][1])
print("Longitude and Lattitude:", closest[0][5],"E", closest[0][6],"N")
print("Geometric Altitude:", closest[0][7])
print("Country of origin:", closest[0][2])
print("ICAO24 ID:", closest[0][0])
print("EIFEL TOWER\n------------")
get_closest(2.2945,48.8584)
print("\n<NAME> AIRPORT\n----------------------")
get_closest(-73.7781,40.6413)<file_sep>/Mailer.py
# http://naelshiab.com/tutorial-send-email-python/
import smtplib
from email.mime import multipart
from email.mime import text
fromaddr = '<EMAIL>'
toaddr = '<EMAIL>'
msg = multipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = 'Test E-Mail!'
body = 'This is a test email!'
msg.attach(text.MIMEText(body,'plain'))
server = smtplib.SMTP()
server.connect('login-178.hoststar.ch')
server.login(fromaddr, 'Password')
server.starttls()
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
<file_sep>/Webscraper/BloomScraper.py
import urllib.request
from bs4 import BeautifulSoup
import csv
from datetime import datetime
import lxml
# specify the url
page = 'http://www.bloomberg.com/quote/SPX:IND'
# get the html page of the url declared
page = urllib.request.urlopen(page)
# parse the html using beautiful soup
soup = BeautifulSoup(page, 'lxml')
name_box = soup.find('h1', attrs={'class': 'name'})
name = name_box.text.strip() # strip is used to remove starting and trailing
price_box = soup.find('div', attrs={'class':'price'})
price = price_box.text
print(name, price)
# with open('index.csv', 'a') as csv_file:
# writer = csv.writer(csv_file)
# writer.writerow([name, price, datetime.now()])<file_sep>/Maschinelearningmastery/ML_Start.py
# The code used in this project is from
# https://machinelearningmastery.com/machine-learning-in-python-step-by-step/
# Import packages
import sys
import scipy
import numpy
import matplotlib
import pandas as pd
import sklearn
from pandas.plotting import scatter_matrix
from matplotlib import pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
# Load the dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal-length',' sepal-width','petal-length','petal-width','class']
dataset = pd.read_csv(url, names=names)
# Describe the dataset
print(type(dataset))
print(dataset.shape)
print(dataset.head(20))
print(dataset.describe())
print(dataset.groupby('class').size())
# Visualize the data
# Box and whisker plot
dataset.plot(kind = 'box', subplots = True, layout = (2,2), sharex = False, sharey = False)
plt.show()
# Histograms
dataset.hist()
plt.show()
# Scatter plot matrix
scatter_matrix(dataset)
plt.show()
# Evaluate some algorithms
# Split-out validation dataset
array = dataset.values
X = array[:,0:4]
Y = array[:,4]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X,Y,test_size = validation_size)
# Test options and evaluation metric
scoring = 'accuracy'
# Build models
models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC()))
# evaluate each model
results = []
names = []
for name, model in models:
kfold = model_selection.KFold(n_splits=10, random_state=seed)
cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = f'Name: {name}, Mean: {cv_results.mean():.4f}, Std: {cv_results.std():.4f}'
print(msg)
# Compare algorithms
fig = plt.figure()
fig.title('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.show()
# Make predictions
knn = KNeighborsClassifier()
knn.fit(X_train, Y_train)
predictions = knn.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))<file_sep>/DailyProgrammer/20180516_ DailyProgrammer_ElsieFour.py
# https://www.reddit.com/r/dailyprogrammer/comments/8jvbzg/20180516_challenge_361_intermediate_elsiefour/
import numpy as np
def elsie_four(key, text, decryption = True):
# marker = m, with position (i,j)
# text character = a, with position (r,c)
# dectypted/encrypted char = b, with position (x,y)
if text.startswith('%'):
decryption = False
text = text[1:]
alphabet = '#_<KEY>'
vectors = {i:[n%6, n//6] for n, i in enumerate(alphabet)} # create dictionary of vectors
if len(key) != 36: # Check if key is invalid
return '--Error: Please provide a 36-char key--'
if len(set(alphabet+key+text)) > 36: # Check for invalid characters
return 'Error: Invalid characters in key/text--'
grid = np.array(list(key)).reshape(6,6) # Initialze grid
m, i, j = key[0], 0, 0 # Set marker position
res = ''
for a in text: # Input character
r, c = np.ravel(np.where(grid == a))
if decryption:
x, y = np.subtract([r, c], vectors[m][::-1])%6
b = grid[x][y]
row, col, tile = x, c, a
else:
x, y = np.subtract([r, c], vectors[m][::-1])%6
b = grid[x][y]
row, col, tile = r, y, b
res += b
grid[row] = np.roll(grid[row],1)
col = np.where(grid == tile)[1]
grid[:, col] = np.roll(grid[:, col],1)
i, j = np.ravel(np.where(grid == m))
i, j = np.add([i, j], vectors[tile][::-1])%6
m = grid[i][j]
return res
print(elsie_four('s2ferw_nx346ty5odiupq#lmz8ajhgcvk79b', 'tk5j23tq94_gw9c#lhzs'))
print(elsie_four('#o2zqijbkcw8hudm94g5fnprxla7t6_yse3v', 'b66rfjmlpmfh9vtzu53nwf5e7ixjnp'))
print(elsie_four('9mlpg_to2yxuzh4387dsajknf56bi#ecwrqv', 'grrhkajlmd3c6xkw65m3dnwl65n9op6k_o59qeq'))
print(elsie_four('7dju4s_in6vkecxorlzftgq358mhy29pw#ba', '%the_swallow_flies_at_midnight'))
<file_sep>/MITx_6.00.1x/PS2/PS_2.2.py
# Test Case 1:
# balance = 3329
# annualInterestRate = 0.2
# Test Case 2:
# balance = 4773
# annualInterestRate = 0.2
# Test Case 3:
# balance = 3926
# annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
initialBalance = balance
month = 0
minimumPayment = 0
def calculator(month,balance,minimumPayment,monthlyInterestRate):
while month < 12:
unpaidBalance = balance - minimumPayment
balance = unpaidBalance + (monthlyInterestRate*unpaidBalance)
month += 1
return balance
while calculator(month,balance,minimumPayment,monthlyInterestRate) > 0:
balance = initialBalance
minimumPayment += 10
month = 0
calculator(month,balance,minimumPayment,monthlyInterestRate)
print('Lowest Payment: ' + str(minimumPayment))
<file_sep>/MITx_6.00.2x/Test.py
import random
def genEven():
'''
Returns a random even number x, where 0 <= x < 100
'''
num = random.randrange(10,21,2)
return num
i = 0
while i <= 100:
print(genEven())
i += 1
<file_sep>/Plotting.py
# https://pythonprogramming.net/matplotlib-python-3-basics-tutorial/
# Importing matplotlib
from matplotlib import pyplot as plt
# Plotting to our canvas
plt.plot([1,2,3],[4,5,1])
# Show what we plotted
plt.show()
# add title
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title('Epic title')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()<file_sep>/MITx_6.00.1x/PS2/PS_2.3.py
# Test Case 1:
balance = 320000
annualInterestRate = 0.2
# Test Case 2:
# balance = 999999
# annualInterestRate = 0.18
initialBalance = balance
monthlyInterestRate = annualInterestRate / 12.0
lowerBound = balance / 12.0
upperBound = (balance * ((1.0 + monthlyInterestRate)**12))/12.0
epsilon = 0.01
minimumPayment = (upperBound + lowerBound)/2.0
month = 0
def claculator(month,balance,minimumPayment,monthlyInterestRate):
while month < 12:
unpaidBalance = balance - minimumPayment
balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
month += 1
return balance
while abs(balance) >= epsilon:
balance = initialBalance
month = 0
balance = claculator(month,balance,minimumPayment,monthlyInterestRate)
if balance > 0:
lowerBound = minimumPayment
else:
upperBound = minimumPayment
minimumPayment = (upperBound + lowerBound) / 2.0
minimumPayment = round(minimumPayment,2)
print('Lowest Payment: '+str(minimumPayment))<file_sep>/MITx_6.00.1x/PS3/PS_3.2.py
# Printing out the user's guess
secretWord = 'apple'
# lettersGuessed = ['e','i','k','p','r','s']
lettersGuessed = ['a','p','p','l','e']
def getGuessedWord(secretWord,lettersGuessed):
answer = []
for char in secretWord:
if char in lettersGuessed:
answer.append(char)
else:
answer.append('_')
return ' '.join(answer)
print(getGuessedWord(secretWord, lettersGuessed))<file_sep>/Sudoku_Solver.py
# This program is copied from the link mentioned belog.
# https://towardsdatascience.com/peter-norvigs-sudoku-solver-25779bb349ce
# http://norvig.com/sudoku.html
def cross(A,B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
digits = '123456789'
rows = 'ABCDEFGHI'
cols = digits
squares = cross(rows,cols)
unlist = ([cross(rows,c) for c in cols] +
[cross(r,cols) for r in rows] +
[cross(rs,cs) for rs in ('ABC','DEF','GHI') for cs in
('123','456','789')])
units = dict((s, [u for u in unlist if s in u])
for s in squares)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares)
def parse_grid(grid):
'''
Convert grid to a dict of possible values, {square: digits},
or return False if a contradiction is detected.
'''
values = dict((s,digits) for s in squares)
for s,d in gris_values(grid).items():
if d in digits and not assign(values, s, d):
return False
return values
def gris_values(grid):
chars = [c for c in grid if c in digits or c in '0.']
assert len(chars) == 81
return dict(zip(squares, chars))
def assign(values, s, d):
other_values = values[s].replace(d,'')
if all(eliminate(values, s, d2) for d2 in other_values):
return values
else:
return False
def eliminate(values, s, d):
if d not in values[s]:
return values
values[s] = values[s].replace(d,'')
if len(values[s]) == 0:
return False
elif len(values[s]) == 1:
d2 = values[2]
if not all(eliminate(values, s2,d2) for s2 in peers[s]):
return False
for u in units[s]:
dplaces = [s for s in u if d in values[s]]
if len(dplaces) == 0:
return False
elif len(dplaces) == 1:
if not assign(values, dplaces[0], d):
return False
return values
def solve(grid):
return search(parse_grid(grid))
def search(values):
if values is False:
return False
if all(len(values[s]) == 2 for s in squares):
return values
n,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
return some(search(assign(values.copy(), s, d)) for d in values[s])
def some(seq):
for e in seq:
if e: return e
return False<file_sep>/Webscraper/EconScraper.py
from bs4 import BeautifulSoup
import requests
import lxml
pages = ['currencies','stocks','commodities','bonds']
tabels = ['FX','']
def requestor(page):
request = requests.get(f'https://tradingeconomics.com/{page}')
return request
currencies = requestor(pages[0])
soup = BeautifulSoup(currencies.content, 'lxml')
currencies = soup.find_all('div',class_ = 'table-responsive')
for currency in currencies:
currency.find_all('td')
<file_sep>/MITx_6.00.1x/PS2/PS_2.1.py
# Test Case 1
# balance = 42
# annualInterestRate = 0.2
# monthlyPaymentRate = 0.04
# Test Case 2
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
month = 0
totalPayment = 0
monthlyInterestRate = annualInterestRate / 12.0
while month < 12:
minimumMonthlyPayment = monthlyPaymentRate * balance
unpaidBalance = balance - minimumMonthlyPayment
totalPayment += minimumMonthlyPayment
balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
month += 1
print('Remaining balance: '+str(round(balance,2)))<file_sep>/MITx_6.00.1x/PS3/PS_3.3.py
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
def getAvailableLetters(lettersGuessed):
import string
result = []
for char in string.ascii_lowercase:
if char not in lettersGuessed:
result.append(char)
return ''.join(result)
print(getAvailableLetters(lettersGuessed))
<file_sep>/PyDistributions.py
# http://bigdata-madesimple.com/how-to-implement-these-5-powerful-probability-distributions-in-python/
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
# Binomial Distribution
n = 10
p = 0.3
k = np.arange(0,21)
binomial = stats.binom.pmf(k, n, p)
binomial
plt.plot(k, binomial, 'o-')
plt.title('Binomial: n = %i , p = %.2f' % (n,p), fontsize=15)
plt.xlabel('Number of successes')
plt.ylabel('Probability of successes', fontsize = 15)
plt.show()
binom_sim = data = stats.binom.rvs(n = 10, p = 0.3, size = 10000)
print(f'Mean: {np.mean(binom_sim):.4f}')
print(f'SD: {np.std(binom_sim, ddof = 1):.4f}')
plt.hist(binom_sim, bins = 10, normed = True)
plt.xlabel('x')
plt.ylabel('density')
plt.show()
# Poisson distribution
rate = 2
n = np.arange(0,10)
y = stats.poisson.pmf(n, rate)
y
plt.plot(n ,y , 'o-')
plt.title(f'Poisson: $\lambda$ = {rate}')
plt.xlabel('Number of accidents')
plt.ylabel('Probability of number of accidents')
plt.show()
data = stats.poisson.rvs(mu = 2, loc = 0, size = 1000)
print(f'Mean: {np.mean(data):.4f}')
print(f'SD: {np.std(data, ddof=1):.4f}')
plt.figure()
plt.hist(data, bins = 9, normed = True)
plt.xlim(0, 10)
plt.xlabel('Number of accidents')
plt.title('Simulating Poisson Random Variables')
plt.show()
# Normal distribution
mu = 0
sigma = 1
x = np.arange(-5,5,0.1)
y = stats.norm.pdf(x, 0, 1)
plt.plot(x, y)
plt.title(f'Normal: $\mu$ ={mu:.1f}, $\sigma^2$={sigma:.1f}')
plt.xlabel('x')
plt.ylabel('Probability density')
plt.show()
# Beta distribution
a = 0.5
b = 0.5
x = np.arange(0.01, 1, 0.01)
y = stats.beta.pdf(x, a, b)
plt.plot(x, y)
plt.title(f'Beta: a = {a:.1f}, b = {b:.1f}')
plt.xlabel('x')
plt.ylabel('Probability density')
plt.show()
# Exponential distribution
lambd = 0.5
x = np.arange(0, 15, 0.1)
y = lambd*np.exp(-lambd*x)
plt.plot(x, y)
plt.title(f'Exponential: $\lambda$ = {lambd:.2f}')
plt.xlabel('x')
plt.ylabel('Probability density')
plt.show()
data = stats.expon.rvs(scale = 2, size = 1000)
print(f'Mean: {np.mean(data):.4f}')
print(f'SD: {np.std(data, ddof=1):.4f}')
plt.figure()
plt.hist(data, bins = 20, normed = True)
plt.xlim(0,15)
plt.ylabel('Probability density')
plt.title('Simulatind Exponential Random Variables')
plt.show()
<file_sep>/DailyProgrammer/20180530_ DailyProgrammer_Route.py
import numpy as np
def grid_dimensions(string, tuple_of_2_inits):
h, w = tuple_of_2_inits
output = [ch for ch in list(string) if ch.isalpha()]
output += ['X']*((w*h)-len(output))
return [output[offs:offs+h] for offs in range(0, len(output),h)]
def clock(array):
output = []
while len(array) > 1:
output += array.pop(0)
array = np.rot90(array).tolist()
output += array.pop(0)
return output
def spiral(array, direction):
array = np.rot90(array).tolist()
if direction != 'clockwise':
array = np.transpose(array).tolist()
return clock(array)
def main(inp):
string, dimension, direction = inp
output = grid_dimensions(string, dimension)
output = spiral(output, direction)
return ''.join(output)
print(main(("WE ARE DISCOVERED. FLEE AT ONCE", (9, 3), 'clockwise')))
print(main(("why is this professor so boring omg", (6, 5), 'counter-clockwise')))
print(main(("Solving challenges on r/dailyprogrammer is so much fun!!", (8, 6), 'counter-clockwise')))
print(main(("For lunch let's have peanut-butter and bologna sandwiches", (4, 12), 'clockwise')))
print(main(("I've even witnessed a grown man satisfy a camel", (9,5), 'clockwise')))
print(main(("Why does it say paper jam when there is no paper jam?", (3, 14), 'counter-clockwise')))<file_sep>/blackjack.py
from random import shuffle
# define the card ranks and suits
ranks = [_ for _ in range(2,11)] + ['Jack','Queen','King','Ace']
suits = ['Spade','Heart','Diamond','Club']
def get_deck():
'''
Return a new deck of cards.
'''
return[[rank, suit] for rank in ranks for suit in suits]
# get deck of cards, and randomly shuffle it
deck = get_deck()
shuffle(deck)
# boolean variable that indicates wether the player has gone bust
player_in = True
# issue the player and dealer their first two cards
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
def card_value(card):
'''
Returns the integer value of a single card.
'''
rank = card[0]
if rank in ranks[0:-4]:
return int(rank)
elif rank is 'Ace':
return 11
else:
return 10
def hand_value(hand):
'''
Returns the integer value of a set of cards.
'''
# Naivly sum up the cards in the deck
tmp_value = sum(card_value(_) for _ in hand)
# Count the sum of Aces in the hand.
num_aces = len([_ for _ in hand if _[0] is 'Ace'])
# Aces can count for 1, or 11. If it is possible to bring the value
# of the hand under 21 by making 11 -> 1 substitutions , do so.
while num_aces > 0:
if tmp_value > 21 and 'Ace' in ranks:
tmp_value -= 10
num_aces -= 1
else:
break
# Return a string and an integer representing the value of the hand.
# if the hand is bust return 100.
if tmp_value < 21:
return[str(tmp_value),tmp_value]
elif tmp_value == 21:
return ['Blackjack!', 21]
else:
return ['Bust!',100]
# As long as the player remains in the game, ask them if they'd like to hit
# for another card, or stay with their current hand.
while player_in:
# Display player's current hand, as well as its value.
current_score = hand_value(player_hand)[0]
print(f'\nYou are currently at {current_score} {player_hand}')
# if the player's hand is bust, don't ask them for a decision.
if hand_value(player_hand)[1] == 100:
break
if player_in:
response = int(input('Hit or stay? (Hit = 1, Stay = 0)'))
# If the player asks to be hit, take the first card from the top of
# the deck and add it to their hand. If they ask to stay, change
#player_in to falsem and move on to the dealer's hand.
if response:
player_in = True
new_player_card = deck.pop()
player_hand.append(new_player_card)
print(f'You draw {new_player_card}')
else:
player_in = False
player_score_label, player_score = hand_value(player_hand)
dealer_score_label, dealer_score = hand_value(dealer_hand)
if player_score <= 21:
print(f'Dealer is at {dealer_score_label}\n with the hand {dealer_hand}')
else:
print('Dealer wins!')
while hand_value(dealer_hand)[1] < 17:
new_dealer_card = deck.pop()
dealer_hand.append(new_dealer_card)
print(f'Dealer draws {new_dealer_card}')
dealer_score_label, dealer_score = hand_value(dealer_hand)
if player_score < 100 and dealer_score == 100:
print('You beat the dealer!')
elif player_score > dealer_score:
print('You beat the dealer!')
elif player_score == dealer_score:
print('You tied the dealer, nobody wins!')
else:
print('Dealer wins!')
|
9d68a39199b2cd0c320b75b4ccf5147f62a857b5
|
[
"Python"
] | 18
|
Python
|
davidjaggi/miniprojects
|
b25199f5924aea35c6539e453f5c13d4b9f53525
|
9fd9d9d1175ada605753b4c9aefbd8719d8ec34e
|
refs/heads/master
|
<repo_name>zcj12396/fastRPC<file_sep>/src/main/java/com/fastRPC/netty/RpcServerLoader.java
package com.fastRPC.netty;
import com.fastRPC.serialization.RpcSerializeProtocol;
import com.fastRPC.utils.PropertyUtil;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class RpcServerLoader {
private static final Logger logger = LoggerFactory.getLogger(RpcServerLoader.class);
private EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
private ChannelHandlerAdapter messageSendHandler = null;
private Lock lock = new ReentrantLock();
private Condition connectStatus = lock.newCondition();
private Condition handlerStatus = lock.newCondition();
private boolean connStatus=false;
private String addr;
private int port;
public RpcServerLoader(String addr,int port) {
this.addr = addr;
this.port = port;
}
public RpcServerLoader(String addr) {
Object[] o = addrToIPPort(addr);
this.addr = (String) o[0];
this.port = (int) o[1];
}
//开启连接
public void load () throws Exception{
RpcSerializeProtocol protocol = RpcSerializeProtocol.HESSIANSERIALIZE;
switch (PropertyUtil.getProp("serialize")){
case "JDK":protocol = RpcSerializeProtocol.JDKSERIALIZE;break;
case "HESSIAN":protocol = RpcSerializeProtocol.HESSIANSERIALIZE;break;
}
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
Future<ChannelFuture> res = executor.submit(new MessageSendInitializeTask(eventLoopGroup, addr,port,protocol));
ChannelFuture confutue = res.get(2000,TimeUnit.MILLISECONDS);
confutue.addListener((ChannelFuture future1)->{
if(future1.isSuccess()){
lock.lock();
if (messageSendHandler == null) {
handlerStatus.await();
}
if (messageSendHandler != null) {
connectStatus.signalAll();
this.connStatus = true;
}
lock.unlock();
}
});
}
public void setMessageSendHandler(ChannelHandlerAdapter messageSendHandler) {
try {
lock.lock();
this.messageSendHandler = messageSendHandler;
handlerStatus.signal();
} finally {
lock.unlock();
}
}
public ChannelHandlerAdapter getMessageSendHandler() {
try {
lock.lock();
if (messageSendHandler == null) {
connectStatus.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return messageSendHandler;
}
public boolean getConnStatus() {
return connStatus;
}
public boolean conpareAddr(String addr){
if(addr != null) {
String[] s = addr.split(":");
if(s.length == 2 && this.addr.equals(s[0]) && Integer.valueOf(s[1]) == this.port){
return true;
}
}
return false;
}
public Object[] addrToIPPort(String addr){
Object[] result = new Object[2];
if(addr != null) {
String[] s = addr.split(":");
if(s.length == 2 ){
try {
result[0] = String.valueOf(s[0]);
result[1] = Integer.valueOf(s[1]);
}catch (Exception e){
logger.error("address error");
}
}
}
return result;
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/hessian/HessianSerialize.java
package com.fastRPC.serialization.hessian;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.fastRPC.serialization.RpcSerialize;
import java.io.InputStream;
import java.io.OutputStream;
public class HessianSerialize implements RpcSerialize {
@Override
public void serialize(OutputStream outputStream, Object object) throws Exception {
Hessian2Output hessian2Output = new Hessian2Output(outputStream);
hessian2Output.startMessage();
hessian2Output.writeObject(object);
hessian2Output.completeMessage();
hessian2Output.close();
outputStream.close();
}
@Override
public Object deserialize(InputStream inputStream) throws Exception {
Object object = null;
Hessian2Input hessian2Input = new Hessian2Input(inputStream);
hessian2Input.startMessage();
object = hessian2Input.readObject();
hessian2Input.completeMessage();
hessian2Input.close();
inputStream.close();
return object;
}
}
<file_sep>/src/main/java/com/fastRPC/server/service/impl/Echo2Impl.java
package com.fastRPC.server.service.impl;
import com.fastRPC.server.service.Echo2;
public class Echo2Impl implements Echo2 {
@Override
public String echotry() {
return "新方法"+String.valueOf(Math.random());
}
}
<file_sep>/src/main/java/com/fastRPC/client/service/EchoRandomService.java
package com.fastRPC.client.service;
import com.fastRPC.annotation.FastRpcConsumerClass;
import com.fastRPC.annotation.FastRpcRegisterableClass;
import com.fastRPC.annotation.FastRpcRegisterableMethod;
@FastRpcConsumerClass
public interface EchoRandomService {
@FastRpcRegisterableMethod
public String echo();
}
<file_sep>/src/main/java/com/fastRPC/netty/MessageServerChannelInitializer.java
package com.fastRPC.netty;
import com.fastRPC.serialization.RpcSerializeProtocol;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import java.util.Map;
public class MessageServerChannelInitializer extends ChannelInitializer<SocketChannel> {
private RpcSerializeProtocol protocol;
private RpcServerSerializeFrameImpl frame;
public RpcSerializeProtocol getProtocol() {
return protocol;
}
public void setProtocol(RpcSerializeProtocol protocol) {
this.protocol = protocol;
}
public MessageServerChannelInitializer build(RpcSerializeProtocol protocol){
this.protocol = protocol;
return this;
}
public MessageServerChannelInitializer() {
this.frame = new RpcServerSerializeFrameImpl();
}
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
frame.select(protocol,pipeline);
}
}
<file_sep>/src/main/java/com/fastRPC/netty/MessageSendInitializeTask.java
package com.fastRPC.netty;
import com.fastRPC.client.handler.RpcClientHandler;
import com.fastRPC.serialization.RpcSerializeProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Callable;
public class MessageSendInitializeTask implements Callable {
private static final Logger logger = LoggerFactory.getLogger(MessageSendInitializeTask.class);
private EventLoopGroup eventLoopGroup;
private String ip;
private int port;
private RpcSerializeProtocol protocol;
public MessageSendInitializeTask(EventLoopGroup eventLoopGroup, String ip, int port,RpcSerializeProtocol protocol) {
this.eventLoopGroup = eventLoopGroup;
this.ip = ip;
this.port = port;
this.protocol = protocol;
}
@Override
public Object call() throws Exception {
Bootstrap b = new Bootstrap();
b.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE,true)
.remoteAddress(ip,port);
//自定义序列化方法
b.handler(new MessageChannelInitializer(protocol));
ChannelFuture future = b.connect();
logger.info("connecting to {}:{}",ip,port);
future.addListener((ChannelFuture future1)->{
if(future1.isSuccess()){
ChannelHandlerAdapter handler = future1.channel().pipeline().get(RpcClientHandler.class);
logger.info("setting the handler for {}:{}",ip,port);
// ((RpcClientHandler) handler).getChannel().writeAndFlush(new MessageRequest());
RpcServerConnectionFactory.getRpcConnectionInstance(ip+":"+port).setMessageSendHandler(handler);
}else {
logger.info("Conn't connect to {}:{}",ip,port);
}
});
return future;
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/jdkserialize/JdkEncoder.java
package com.fastRPC.serialization.jdkserialize;
import com.fastRPC.serialization.MessageCodecUtil;
import com.fastRPC.serialization.MessageEncoder;
public class JdkEncoder extends MessageEncoder {
public JdkEncoder(MessageCodecUtil messageCodec) {
super(messageCodec);
}
}
<file_sep>/src/main/java/com/fastRPC/zookeeper/BaseZookeeperFactory.java
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.fastRPC.zookeeper;
import com.fastRPC.utils.PropertyUtil;
import java.util.concurrent.CountDownLatch;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.zookeeper.Watcher;
public class BaseZookeeperFactory {
private static ZkClient serverZK;
private static ZkClient clientZK;
private String host;
private static final int SESSION_TIME_OUT = 3000;
private static final int CONNECT_TIME_OUT = 3000;
private BaseZookeeperFactory() {
}
public static ZkClient getInstance(String type) {
switch (type){
case "client":
if (clientZK == null) {
String host = PropertyUtil.getProp("zookeeper.server.url");
synchronized(ZkClient.class) {
if (clientZK == null) {
clientZK = new ZkClient(new ZkConnection(host, BaseZookeeperFactory.SESSION_TIME_OUT));
}
}
}
return clientZK;
case "server":
if (serverZK == null) {
String host = PropertyUtil.getProp("zookeeper.server.url");
synchronized(ZkClient.class) {
if (serverZK == null) {
serverZK = new ZkClient(new ZkConnection(host, BaseZookeeperFactory.SESSION_TIME_OUT));
}
}
}
return serverZK;
}
return null;
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/jdkserialize/JdkDecoder.java
package com.fastRPC.serialization.jdkserialize;
import com.fastRPC.serialization.MessageCodecUtil;
import com.fastRPC.serialization.MessageDecoder;
public class JdkDecoder extends MessageDecoder {
public JdkDecoder(MessageCodecUtil messageCodec) {
super(messageCodec);
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/MessageEncoder.java
package com.fastRPC.serialization;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageEncoder extends MessageToByteEncoder {
private static final Logger logger = LoggerFactory.getLogger(MessageEncoder.class);
private MessageCodecUtil messageCodec;
public MessageEncoder(final MessageCodecUtil messageCodec) {
this.messageCodec = messageCodec;
}
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
logger.info("Encoder: {}",messageCodec.getClass().getSimpleName());
messageCodec.encode(byteBuf,o);
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/RpcSerialize.java
package com.fastRPC.serialization;
import java.io.InputStream;
import java.io.OutputStream;
public interface RpcSerialize {
public void serialize(OutputStream outputStream, Object object) throws Exception;
public Object deserialize(InputStream inputStream) throws Exception;
}
<file_sep>/README.md
# fastRPC
一个基于Netty、zookeeper和Spring的分布式RPC框架的实现
已实现的功能:
1.基于注解的配置
2.支持JDK及HESSIAN序列化方式
3.支持客户端一对多的RPC调用及连接维护
4.基于zookeeper的服务自动注册与发现
5.有多个服务实现时,默认采用随机的分配方式调用。
计划中的功能:
1.采用IOC来托管服务端的Bean,而不是反射的形式。
2.考虑支持配置的方式,不仅仅是注解
3.更多的序列化协议
4.服务端采用线程池的方式执行前端请求,而不是在netty的handler中
5.多个服务可用时,支持自定义的负载策略。
6.系统的健壮性。重连,重试,容错等机制的完善。
7.尽量避免集成其他框架(spring)的代码,暂时只有加载配置文件时候有用到,后续会以自定义loader的形式实现。
###
吐槽一下阿里云竟然不能获取本机对于外网的ip。让我只能以配置的形式硬编码自己的IP。。。
可以在autoRegister中自己修改
###
联系方式:
<EMAIL>
本人水平一般,代码中难免有许多不完善的地方,欢迎骚扰。
<file_sep>/src/main/java/com/fastRPC/netty/handler/JdkNativeHandler.java
package com.fastRPC.netty.handler;
import com.fastRPC.client.handler.RpcClientHandler;
import com.fastRPC.serialization.jdkserialize.JdkDecoder;
import com.fastRPC.serialization.jdkserialize.JdkEncoder;
import com.fastRPC.serialization.jdkserialize.JdkSerializeCodecUtil;
import io.netty.channel.ChannelPipeline;
public class JdkNativeHandler implements NettyRpcHandler {
@Override
public void handle(ChannelPipeline pipeline) {
JdkSerializeCodecUtil util = new JdkSerializeCodecUtil();
//添加编码解码器和处理器
pipeline.addLast(new JdkDecoder(util))
.addLast(new JdkEncoder(util))
.addLast(new RpcClientHandler());
}
}
<file_sep>/src/main/java/com/fastRPC/utils/ObjectUtil.java
package com.fastRPC.utils;
import java.util.*;
public class ObjectUtil {
public static boolean isEmptyOrNull(Object object){
if(object == null){
return true;
} else if(object instanceof String){
String str = String.valueOf(object);
if ("".equals(str.trim())){
return true;
}
}else if(object instanceof Map){
Map map = (Map)object;
if (map.size() == 0){
return true;
}
}else if(object instanceof List){
List list = (List)object;
if (list.size() == 0){
return true;
}
}else if(object instanceof Object[]){
Object[] arr = (Object[])object;
if(arr.length == 0){
return true;
}
}
return false;
}
public static boolean isEmptyOrNull(Object... objs) {
boolean flag = false;
for(Object obj : objs){
flag = flag || isEmptyOrNull(obj);
}
return flag;
}
}
<file_sep>/src/main/java/com/fastRPC/rundemo/RunServer.java
package com.fastRPC.rundemo;
import com.fastRPC.bootstrap.FastRpcServerBootstrap;
public class RunServer {
public static void main(String[] args) throws Exception{
FastRpcServerBootstrap.start();
}
}
<file_sep>/src/main/java/com/fastRPC/netty/RpcServerConnectionFactory.java
package com.fastRPC.netty;
import java.util.ArrayList;
public class RpcServerConnectionFactory {
private final static ArrayList<RpcServerLoader> rpcServerLoaders = new ArrayList<>();
public static RpcServerLoader getRpcConnectionInstance(Object o) throws Exception {
assert o instanceof String;
String addr = String.valueOf(o);
if (-1 != containsServerLoader(addr)){
return rpcServerLoaders.get(containsServerLoader(addr));
}
RpcServerLoader loader;
synchronized (RpcServerConnectionFactory.class) {
if (-1 == containsServerLoader(addr)) {
loader = new RpcServerLoader(addr);
rpcServerLoaders.add(loader);
loader.load();
}else {
loader = rpcServerLoaders.get(containsServerLoader(addr));
}
}
return loader;
}
private static int containsServerLoader(String addr){
for(RpcServerLoader loader:rpcServerLoaders){
if(loader.conpareAddr(addr)){
return rpcServerLoaders.indexOf(loader);
}
}
return -1;
}
}
<file_sep>/src/main/java/com/fastRPC/bootstrap/FastRpcServerBootstrap.java
package com.fastRPC.bootstrap;
import com.fastRPC.server.Server;
public class FastRpcServerBootstrap {
public static void start() throws Exception {
Thread thread = new Thread(new Server(9000));
thread.start();
}
}
<file_sep>/src/main/java/com/fastRPC/proxy/MyInvocationHandler.java
package com.fastRPC.proxy;
import com.fastRPC.annotation.FastRpcConsumerClass;
import com.fastRPC.annotation.FastRpcRegisterableClass;
import com.fastRPC.annotation.FastRpcRegisterableMethod;
import com.fastRPC.client.handler.RpcClientHandler;
import com.fastRPC.client.zookeeper.NamingManager;
import com.fastRPC.exception.InvokeModuleException;
import com.fastRPC.model.MessageRequest;
import com.fastRPC.netty.RpcServerConnectionFactory;
import com.fastRPC.netty.RpcServerLoader;
import com.fastRPC.utils.ObjectUtil;
import org.assertj.core.internal.bytebuddy.agent.builder.AgentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class MyInvocationHandler implements InvocationHandler {
private static final Logger logger = LoggerFactory.getLogger(MyInvocationHandler.class);
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MessageRequest request = new MessageRequest();
String aliases = "";
Class<?> iface[] = proxy.getClass().getInterfaces();
for(Class<?> clz : iface){
if(clz.isAnnotationPresent(FastRpcConsumerClass.class)
&& method.isAnnotationPresent(FastRpcRegisterableMethod.class)){
FastRpcConsumerClass anno = clz.getAnnotation(FastRpcConsumerClass.class);
aliases = anno.aliases();
if("SelfClassName".equals(aliases)){
aliases = clz.getSimpleName();
}
}
}
HashMap map = NamingManager.findInvokeInfo(aliases);
if(ObjectUtil.isEmptyOrNull(map,aliases)){
logger.error("Con't find any implements in zookeeper");
return null;
}
request.setClassName(String.valueOf(map.get("serviceImpl")));
request.setMethodName(method.getName());
request.setMessageId(new Date().toString());
if (args != null && args.length > 0) {
String[] classes = new String[args.length];
for (int i = 0; i < args.length; ++i) {
classes[i] = args[i].getClass().getName();
}
request.setTypeParameters(classes);
request.setParameters(args);
}
List addrs = (List) map.get("addrs");
if (ObjectUtil.isEmptyOrNull(addrs)){
logger.error("Con't find any implements address in zookeeper");
return null;
}else {
//简单的负载均衡
int index = ((int) (new Random().nextFloat() * addrs.size() ));
logger.info("called : {}",addrs.get(index));
RpcServerLoader serverLoader = RpcServerConnectionFactory.getRpcConnectionInstance(addrs.get(index));
RpcClientHandler handler = (RpcClientHandler) serverLoader.getMessageSendHandler();
if(serverLoader.getConnStatus()){
return handler.sendRequest(request).start();
}
return null;
}
}
}
<file_sep>/src/main/java/com/fastRPC/netty/handler/HessianHandler.java
package com.fastRPC.netty.handler;
import com.fastRPC.client.handler.RpcClientHandler;
import com.fastRPC.serialization.hessian.HessianCodecUtil;
import com.fastRPC.serialization.hessian.HessianDecoder;
import com.fastRPC.serialization.hessian.HessianEncoder;
import com.fastRPC.server.handler.TestServerHandler;
import io.netty.channel.ChannelPipeline;
public class HessianHandler implements NettyRpcHandler {
@Override
public void handle(ChannelPipeline pipeline) {
HessianCodecUtil util = new HessianCodecUtil();
pipeline.addLast(new HessianEncoder(util))
.addLast(new HessianDecoder(util))
.addLast(new RpcClientHandler());
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/hessian/HessianCodecUtil.java
package com.fastRPC.serialization.hessian;
import com.fastRPC.serialization.MessageCodecUtil;
import io.netty.buffer.ByteBuf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class HessianCodecUtil implements MessageCodecUtil {
@Override
public void encode(ByteBuf out, Object message) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
//池化工厂生成
HessianSerialize serialize = new HessianSerialize();
serialize.serialize(bo, message);
byte[] result = bo.toByteArray();
int length = result.length;
out.writeInt(length);
out.writeBytes(result);
//返还serializer
}catch (Exception e){
//close
}
}
@Override
public Object decode(byte[] bytes) {
Object result = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
//池化工厂生成
HessianSerialize serialize = new HessianSerialize();
result = serialize.deserialize(bis);
//返还serializer
}catch (Exception e){
// close;
}
return result;
}
}
<file_sep>/src/main/java/com/fastRPC/serialization/codec/DefaultDecoder.java
package com.fastRPC.serialization.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.rmi.runtime.Log;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;
public class DefaultDecoder extends ByteToMessageDecoder {
private static final Logger logger = LoggerFactory.getLogger(DefaultDecoder.class);
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
logger.info("getMessage, length: {}",byteBuf.readableBytes());
if(byteBuf.readableBytes()<4)return;
byteBuf.markReaderIndex();//标记读取的位置,如果发现缓冲区并没有足够长度的字节,则放弃本次读取
int length = byteBuf.readInt();
if(length<0){
channelHandlerContext.close();
}
if(byteBuf.readableBytes()<length){
byteBuf.resetReaderIndex();
return;
}
byte[] body = new byte[length];
byteBuf.readBytes(body);
ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(body));
Object object = oi.readObject();
list.add(object);
}
}
|
6e0e1a2f3516b650396a85ba06e5a2b0b623a657
|
[
"Markdown",
"Java"
] | 21
|
Java
|
zcj12396/fastRPC
|
3b69cebc4e004c5f11445db6242723f98f9724e1
|
d83eba76f4a6108ccc7f038bd563d1dd64961bb1
|
refs/heads/master
|
<repo_name>geoffnagy/bebop_hri<file_sep>/script/leds.sh
#/usr/bin/env bash
ssh -f edison@tesla '/home/edison/launcher.sh sektor'
|
0f8338e924d1f54b97a18b14723af0404e492f8b
|
[
"Shell"
] | 1
|
Shell
|
geoffnagy/bebop_hri
|
12eeac1b79ea9414d6f3bac7fcfa0031e1a2af25
|
9c7f6deddccc5ea8f4cb92e5a9c9ac3a6c9e2a4e
|
refs/heads/main
|
<repo_name>phelipecomph/Pong-IA<file_sep>/Game.py
class Ball():
def __init__(self,board = ['________________________________________________________ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'_________________________________________________________ ']):
self.board_rows = len(board)
self.board_cols = len(board[0])
self.pos = {'x':round(self.board_cols/2),'y':round(self.board_rows/2)}
self.direction = {'vertical':1,'horizontal':0} # [down/up,left/right]
def move(self,l_pos,r_pos, debug = False):
if self.pos['y'] == self.board_rows-1 or self.pos['y'] == 1: self.direction['vertical'] = abs(self.direction['vertical']-1)
if self.direction['vertical'] == 1: self.pos['y'] -= 1
else: self.pos['y'] += 1
#print('{0} {1}'.format(r_pos,self.pos['y']))
if self.pos['x'] >= self.board_cols-5:
if r_pos+1 == self.pos['y']: self.direction['horizontal'] = abs(self.direction['horizontal']-1)
elif(debug==False):
self.restart_pos()
print('Point Left')
return -1 #Point Left
if self.pos['x'] <= 4:
if l_pos == self.pos['y']: self.direction['horizontal'] = abs(self.direction['horizontal']-1)
elif(debug==False):
self.restart_pos()
print('Point Right')
return 1 #Point Right
if self.direction['horizontal'] == 1: self.pos['x'] += 1
else: self.pos['x'] -= 1
return 0
def restart_pos(self):
self.pos = {'x':round(self.board_cols/2),'y':round(self.board_rows/2)}
class Game():
def __init__(self,p1,p2):
self.board = ['________________________________________________________ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'\ / ',
'/ \ ',
'_________________________________________________________ ']
self.ball = Ball(self.board)
self.gaming = True
self.p1 = p1
self.p2 = p2
def turn(self):
#Turno Jogador 1 (Esquerda)
action = self.p1.action(self.ball, self.p2)
if action.lower() == 'w' and self.p1.pos>=2: self.p1.pos -= 1
if action.lower() == 's' and self.p1.pos<=len(self.board)-3:self.p1.pos += 1
if action.lower() == ' ': pass
#Turno Jogador 2 (Direita)
action = self.p2.action(self.ball, self.p1)
if action.lower() == 'w' and self.p2.pos>=2: self.p2.pos -= 1
if action.lower() == 's' and self.p2.pos<=len(self.board)-3:self.p2.pos += 1
if action.lower() == ' ': pass
#Turnos Bolinha (Aumentar a quantide de turnos aumenta a velocidade da bolinha)
for _ in range(2):
ball_resposta = self.ball.move(self.p1.pos,self.p2.pos)
self.show_board()
if ball_resposta != 0:
if ball_resposta == -1: self.p1.points += 1
elif ball_resposta == 1: self.p2.points += 1
def show_board(self):
for _ in range(10): print()
for b in range(len(self.board)):
row = self.board[b]
if self.p1.pos == b: row = row[:2] + '|' + row[3:]
if self.p2.pos == b: row = row[:-4] + '|' + row[-3:]
if self.ball.pos['y'] == b: row = row[:self.ball.pos['x']] + 'o' + row[self.ball.pos['x']+1:]
print(row)
if __name__ == '__main__':
game = Game()
game.show_board()
while(game.gaming):
game.play()
game.show_board()<file_sep>/PlayerHuman.py
class Player():
def __init__(self, id):
self.pos = 4
self.id = id
self.points = 0
def action(self, ball, opponent):
return input() # 'w': up 's': down ' ': stay<file_sep>/PlayerMonteCarlo.py
import random
from Game import Ball
class Player():
def __init__(self, id):
self.pos = 4
self.spos = 4
self.id = id
self.points = 0
self.board_size = 10
self.board_cols = 58
def action(self, ball, opponent):
return self.simulate_sequence(ball)
def simulate_sequence(self, ball):
sequences = []
points = []
s_ball = {
'x':ball.pos['x'],
'y':ball.pos['y'],
'horizontal':ball.direction['horizontal'],
'vertical':ball.direction['vertical']
}
for i in range(10000):
sequences.append([])
points.append(0)
i_ball = s_ball
self.spos = self.pos
for _ in range(15):
i_ball, action, point = self.simulate(i_ball)
sequences[-1].append(action)
points[-1]+=point
if action == -1: break
# Ponderate actions
action_points = {'w': 0, 's': 0,' ': 0}
for i in range(len(sequences)):
action_points[sequences[i][0]] += points[i]
if action_points['w'] >= action_points['s'] and action_points['w'] >= action_points[' ']: return 'w'
if action_points['s'] >= action_points['w'] and action_points['s'] >= action_points[' ']: return 's'
if action_points[' '] >= action_points['s'] and action_points[' '] >= action_points['w']: return ' '
def simulate(self, ball):
action = random.choice(['w','s',' '])
if action.lower() == 'w' and self.spos>=2: self.spos -= 1
if action.lower() == 's' and self.spos<=self.board_size-3: self.spos += 1
if action.lower() == ' ': pass
if ball['y'] == self.board_size-1 or ball['y'] == 1: ball['vertical'] = abs(ball['vertical']-1)
if ball['vertical'] == 1: ball['y'] -= 1
else: ball['y'] += 1
if ball['x'] >= self.board_cols-5 and self.id == 1:
if self.pos+1 == ball['y']: ball['horizontal'] = abs(ball['horizontal']-1)
return ball, action, -1
if ball['x'] <= 4 and self.id == 0:
if self.pos == ball['y']: ball['horizontal'] = abs(ball['horizontal']-1)
return ball, action, -1
if ball['x'] >= self.board_cols-5 and self.id == 0:
if self.pos+1 == ball['y']: ball['horizontal'] = abs(ball['horizontal']-1)
return ball, action, 1
if ball['x'] <= 4 and self.id == 1:
if self.pos == ball['y']: ball['horizontal'] = abs(ball['horizontal']-1)
return ball, action, 1
if ball['horizontal'] == 1: ball['x'] += 1
else: ball['x'] -= 1
return ball, action, 0<file_sep>/Main.py
from Game import Game
from PlayerHuman import Player as HPlayer
from PlayerMonteCarlo import Player as MPlayer
if __name__ == '__main__':
playerLeft = MPlayer(0)
playerRight = MPlayer(1)
game = Game(playerLeft,playerRight)
game.show_board()
while(game.gaming):
game.turn()
game.show_board()
|
b114fe3f266cc0f23ba8a605c6ad93454516dc82
|
[
"Python"
] | 4
|
Python
|
phelipecomph/Pong-IA
|
b97191ad8e474c3e17fb77d8eb2e869157db04b1
|
717dfad92828ff6cad93e3f3ab260f0e897ac9b8
|
refs/heads/master
|
<file_sep>var $ = require('jquery');
require('../lib');
//<file_sep>## jQuery Modal [](https://npmjs.org/package/jquery-modal)
Spawn modals with jQuery.
[Demo](http://submariner-boar-66106.netlify.com/)
## Why?
- [NIH](https://en.wikipedia.org/wiki/Not_invented_here)
- Most similar plugins out there seem to be feature-complete but complicated
## Goals
- Simple yet customizable
- Terse API
- Transitions
- [Accessible](https://gist.github.com/ryanflorence/fd7e987c832cc4efaa56)
## Unsupported
- Nested modals (will not work)
- Old browsers (may work)
## Usage
```js
<button type="button" data-modal="#my-modal">
Open Modal
</button>
<div id="my-modal">
<!-- Modal Markup -->
<button type="button" data-modal-close="#my-modal">
Close
</button>
</div>
```
## API
```js
var $modal = $('#modal')
$modal.modal(opts) // Init
$modal.modal('open') // Progamatically open
$modal.modal('close') // Programatically close
```
### Options
| key | description | type | default |
|-----|-------------|------|---------|
|backdrop|Flag whether to use a backdrop, and attach a modal-close event to the backdrop)|`string` with the selector name or `false` to disable backdrop|The modal itself|
|escapable|Close modal on escape|`boolean`|`true`|
## Events
- `$modal.on('modal:open', cb)` - Triggered when modal is opened
- `$modal.on('modal:close', cb)` - Triggered when modal is closed
## Contributing
```bash
npm run example:build # Build example
npm run example:start # Build example, and watch for changes
open examples/index.html
```
<file_sep>const $ = require('jquery');
require('@srph/jqt');
require('./compensate');
const a11y = require('./a11y');
const ModalError = require('./ModalError');
const body = $('body');
const doc = $(document);
function Modal(el, opts) {
if (!(this instanceof Modal)) return new Modal(el, opts);
opts = this.opts = $.extend({}, opts, {
escapable: true,
backdrop: el
});
this.init = false;
this.status = false; // Open status
this.el = el;
this.dialogue = el.children().get(0);
this.jqt = el.jqt({ speed: opts.speed });
this.bind();
}
/**
* Main application element for accessibility
*/
Modal.main = $('main');
Modal.prototype = {
/**
* Bind all required events
*/
bind: function() {
var self = this;
self.init = true;
if ( self.opts.escapable ) {
doc.on('keyup', function(evt) {
if ( evt.which === 27 ) {
self.close();
}
});
}
if ( self.opts.backdrop ) {
var backdrop = $(self.opts.backdrop);
backdrop.children().on('click', function(evt) {
evt.stopPropagation();
});
backdrop.on('click', function(evt) {
self.close();
});
}
},
/**
* Open the modal
*/
open: function() {
if ( this.status ) return;
this.status = true;
body.addClass('modal-open');
this.jqt.enter(function() {
a11y.focus(Modal.main, this.dialogue);
this.el.trigger('modal:open');
}.bind(this));
},
/**
* Close the modal
*/
close: function() {
if ( !this.status ) return;
this.status = false;
body.removeClass('modal-open');
this.jqt.exit(function() {
a11y.restore(Modal.main);
this.el.trigger('modal:close');
}.bind(this));
},
};
module.exports = Modal;<file_sep>var $ = require('jquery');
var compensate = require('scrollbar-compensate');
$(function() { compensate(['.modal-open']); });<file_sep>const $ = window.$ = require('jquery');
const modal = require('./modal');
const ModalError = require('./ModalError');
$.fn.modal = function interface(opts) {
opts = opts || {};
$(this).each(function() {
var el = $(this);
if ( typeof opts === 'string' ) {
if ( !el.data('modal') ) {
throw new ModalError('Element hasn\'t been initialized yet!');
}
el.data('modal')[opts]();
} else if ( typeof opts === 'object' ) {
if ( el.data('modal') ) {
throw new ModalError('This element has already been initialized!');
}
el.data('modal', modal(el, opts));
}
});
return this;
}
// ----------
// Data API Convenience Binding
// ----------
// Setup Data API to open modal
$('[data-modal]').each(function(key, node) {
var el = $(node);
var target = $(el.data('modal'));
target.modal();
el.on('click', function(evt) {
evt.preventDefault();
target.modal('open');
});
});
// Setup Data API to close modal
$('[data-modal-close]').each(function(key, node) {
var el = $(node);
var target = $(el.data('modal-close'));
el.on('click', function(evt) {
evt.preventDefault();
target.modal('close');
});
});<file_sep>/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
function ModalError(msg) {
this.name = 'ModalError';
this.message = 'jquery-modal: ' + message;
this.stack = (new Error()).stack;
}
ModalError.prototype = Object.create(Error.prototype);
ModalError.prototype.constructor = ModalError;
module.exports = ModalError;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
const $ = window.$ = __webpack_require__(0);
const modal = __webpack_require__(3);
const ModalError = __webpack_require__(1);
$.fn.modal = function interface(opts) {
opts = opts || {};
$(this).each(function() {
var el = $(this);
if ( typeof opts === 'string' ) {
if ( !el.data('modal') ) {
throw new ModalError('Element hasn\'t been initialized yet!');
}
el.data('modal')[opts]();
} else if ( typeof opts === 'object' ) {
if ( el.data('modal') ) {
throw new ModalError('This element has already been initialized!');
}
el.data('modal', modal(el, opts));
}
});
return this;
}
// ----------
// Data API Convenience Binding
// ----------
// Setup Data API to open modal
$('[data-modal]').each(function(key, node) {
var el = $(node);
var target = $(el.data('modal'));
target.modal();
el.on('click', function(evt) {
evt.preventDefault();
target.modal('open');
});
});
// Setup Data API to close modal
$('[data-modal-close]').each(function(key, node) {
var el = $(node);
var target = $(el.data('modal-close'));
el.on('click', function(evt) {
evt.preventDefault();
target.modal('close');
});
});
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
const $ = __webpack_require__(0);
__webpack_require__(0);
__webpack_require__(4);
const a11y = __webpack_require__(7);
const ModalError = __webpack_require__(1);
const body = $('body');
const doc = $(document);
function Modal(el, opts) {
if (!(this instanceof Modal)) return new Modal(el, opts);
opts = this.opts = $.extend({}, opts, {
escapable: true,
backdrop: el
});
this.init = false;
this.status = false; // Open status
this.el = el;
this.dialogue = el.children().get(0);
this.jqt = el.jqt({ speed: opts.speed });
this.bind();
}
/**
* Main application element for accessibility
*/
Modal.main = $('main');
Modal.prototype = {
/**
* Bind all required events
*/
bind: function() {
var self = this;
self.init = true;
if ( self.opts.escapable ) {
doc.on('keyup', function(evt) {
if ( evt.which === 27 ) {
self.close();
}
});
}
if ( self.opts.backdrop ) {
var backdrop = $(self.opts.backdrop);
backdrop.children().on('click', function(evt) {
evt.stopPropagation();
});
backdrop.on('click', function(evt) {
self.close();
});
}
},
/**
* Open the modal
*/
open: function() {
if ( this.status ) return;
this.status = true;
body.addClass('modal-open');
this.jqt.enter(function() {
a11y.focus(Modal.main, this.dialogue);
this.el.trigger('modal:open');
}.bind(this));
},
/**
* Close the modal
*/
close: function() {
if ( !this.status ) return;
this.status = false;
body.removeClass('modal-open');
this.jqt.exit(function() {
a11y.restore(Modal.main);
this.el.trigger('modal:close');
}.bind(this));
},
};
module.exports = Modal;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(0);
var compensate = __webpack_require__(5);
$(function() { compensate(['.modal-open']); });
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var scrollbar = __webpack_require__(6).default;
module.exports = function compensate(elements) {
if (elements == null) {
throw new Error(
'You are calling `compensate()` without any argument. ' +
'You must provide an element!'
);
}
var selectors = elements.join(', ');
var size = scrollbar() || 0;
style(selectors + ' { padding-right: ' + size + 'px; }');
}
function style(styling) {
const style = document.createElement('style');
style.appendChild(document.createTextNode(styling));
document.head.appendChild(style);
return style;
}
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var scrollbarSize = (function () {
var scrollbarSize;
return function () {
if (scrollbarSize != null) {
return scrollbarSize;
}
var div1 = window.document.createElement("div");
var div2 = window.document.createElement("div");
div1.style.width = "100px";
div1.style.overflowX = "scroll";
div2.style.width = "100px";
window.document.body.appendChild(div1);
window.document.body.appendChild(div2);
scrollbarSize = div1.offsetHeight - div2.offsetHeight;
window.document.body.removeChild(div1);
window.document.body.removeChild(div2);
return scrollbarSize;
};
})();
exports.default = scrollbarSize;
//# sourceMappingURL=scrollbar-size.js.map
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
const scope = __webpack_require__(8);
const store = __webpack_require__(11);
/**
* Handle accessibility
* @forked https://github.com/cloudflare/react-modal2/blob/master/src/Modal.js#L6-L16
*/
module.exports = {
focus: function(main, el) {
store.storeFocus();
main.length && main.attr('aria-hidden', 'true');
scope.scopeFocus(el);
},
restore: function(main) {
scope.unscopeFocus();
main.length && main.removeAttr('aria-hidden');
store.restoreFocus();
},
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var tabbable = __webpack_require__(9);
var focusin = __webpack_require__(10);
var polyfilled = false;
function init(element) {
// lazily polyfill focusin for firefox
if (!polyfilled) {
focusin.polyfill();
polyfilled = true;
}
function focus() {
(tabbable(element)[0] || element).focus()
}
function onFocusIn(event) {
if (element !== event.target && !element.contains(event.target)) {
focus();
}
}
focus();
document.addEventListener('focusin', onFocusIn);
return function teardown() {
document.removeEventListener('focusin', onFocusIn);
};
}
var teardownFn;
exports.scopeFocus = function(element) {
if (teardownFn) teardownFn();
teardownFn = init(element);
};
exports.unscopeFocus = function() {
if (teardownFn) teardownFn();
teardownFn = null;
};
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = function(el, options) {
options = options || {};
var elementDocument = el.ownerDocument || el;
var basicTabbables = [];
var orderedTabbables = [];
// A node is "available" if
// - it's computed style
var isUnavailable = createIsUnavailable(elementDocument);
var candidateSelectors = [
'input',
'select',
'a[href]',
'textarea',
'button',
'[tabindex]',
];
var candidates = el.querySelectorAll(candidateSelectors.join(','));
if (options.includeContainer) {
var matches = Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
if (
candidateSelectors.some(function(candidateSelector) {
return matches.call(el, candidateSelector);
})
) {
candidates = Array.prototype.slice.apply(candidates);
candidates.unshift(el);
}
}
var candidate, candidateIndex;
for (var i = 0, l = candidates.length; i < l; i++) {
candidate = candidates[i];
candidateIndex = parseInt(candidate.getAttribute('tabindex'), 10) || candidate.tabIndex;
if (
candidateIndex < 0
|| (candidate.tagName === 'INPUT' && candidate.type === 'hidden')
|| candidate.disabled
|| isUnavailable(candidate, elementDocument)
) {
continue;
}
if (candidateIndex === 0) {
basicTabbables.push(candidate);
} else {
orderedTabbables.push({
index: i,
tabIndex: candidateIndex,
node: candidate,
});
}
}
var tabbableNodes = orderedTabbables
.sort(function(a, b) {
return a.tabIndex === b.tabIndex ? a.index - b.index : a.tabIndex - b.tabIndex;
})
.map(function(a) {
return a.node
});
Array.prototype.push.apply(tabbableNodes, basicTabbables);
return tabbableNodes;
}
function createIsUnavailable(elementDocument) {
// Node cache must be refreshed on every check, in case
// the content of the element has changed
var isOffCache = [];
// "off" means `display: none;`, as opposed to "hidden",
// which means `visibility: hidden;`. getComputedStyle
// accurately reflects visiblity in context but not
// "off" state, so we need to recursively check parents.
function isOff(node, nodeComputedStyle) {
if (node === elementDocument.documentElement) return false;
// Find the cached node (Array.prototype.find not available in IE9)
for (var i = 0, length = isOffCache.length; i < length; i++) {
if (isOffCache[i][0] === node) return isOffCache[i][1];
}
nodeComputedStyle = nodeComputedStyle || elementDocument.defaultView.getComputedStyle(node);
var result = false;
if (nodeComputedStyle.display === 'none') {
result = true;
} else if (node.parentNode) {
result = isOff(node.parentNode);
}
isOffCache.push([node, result]);
return result;
}
return function isUnavailable(node) {
if (node === elementDocument.documentElement) return false;
var computedStyle = elementDocument.defaultView.getComputedStyle(node);
if (isOff(node, computedStyle)) return true;
return computedStyle.visibility === 'hidden';
}
}
/***/ }),
/* 10 */
/***/ (function(module, exports) {
/* from https://gist.github.com/nuxodin/9250e56a3ce6c0446efa */
function polyfill () {
var w = window
var d = w.document
if (w.onfocusin === undefined) {
d.addEventListener('focus', addPolyfill, true)
d.addEventListener('blur', addPolyfill, true)
d.addEventListener('focusin', removePolyfill, true)
d.addEventListener('focusout', removePolyfill, true)
}
function addPolyfill (e) {
var type = e.type === 'focus' ? 'focusin' : 'focusout'
var event = new window.CustomEvent(type, { bubbles: true, cancelable: false })
event.c1Generated = true
e.target.dispatchEvent(event)
}
function removePolyfill (e) {
if (!e.c1Generated) {
d.removeEventListener('focus', addPolyfill, true)
d.removeEventListener('blur', addPolyfill, true)
d.removeEventListener('focusin', removePolyfill, true)
d.removeEventListener('focusout', removePolyfill, true)
}
setTimeout(function () {
d.removeEventListener('focusin', removePolyfill, true)
d.removeEventListener('focusout', removePolyfill, true)
})
}
}
module.exports = {
polyfill: polyfill
}
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var storedFocusElement;
exports.storeFocus = function() {
storedFocusElement = document.activeElement;
};
exports.clearStoredFocus = function() {
storedFocusElement = null;
};
exports.restoreFocus = function() {
if (!storedFocusElement) return;
try { storedFocusElement.focus(); } catch (err) {}
storedFocusElement = null;
};
/***/ })
/******/ ]);
|
ec60b29d4f076687b8714aace864610e7c97b754
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
srph/jquery-modal
|
2c4d13a9538620b6cc32e07337ce1de87718263a
|
8051e0613f9186ada4c735d2f63e53fffed1366b
|
refs/heads/master
|
<file_sep># esp_temp2mqtt
Simple esp8266 (Wemos D1 mino pro) temperature logger with MQTT publish
<file_sep>//source code from http://www.esp8266learning.com/wemos-mini-ds18b20-temperature-sensor-example.php
// OneWire DS18S20, DS18B20, DS1822 Temperature Example
#include <OneWire.h>
// Power supply of the DS18B20
int PinVCC = 14 ; // D5
int PinGND = 5 ; // D1
// D0 connected to RST for DeepSleep weakup
OneWire ds(4); // on pin D2 (a 4.7K resistor is necessary)
// from m1tt_esp8266 exemple (File-->Exemple)
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
// Connect to the WiFi
const char* ssid = ".....";
const char* password = ".....";
const char* mqtt_server = "192.168.1.110";
IPAddress ip( 192, 168, 1, 120 );
IPAddress gateway( 192, 168, 1, 1 );
IPAddress subnet( 255, 255, 255, 0 );
// MQTT topics
// Temperature measure
const char* temp_topic = "Piamont11/Salon/cheminee/temperature";
// Battery measure via ADC to read internal VCC
const char* vdd_topic = "Piamont11/Salon/cheminee/battery";
// Intervall between two publish;
// Time to sleep (in minutes):
const int sleepTimeM = 5;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int startup = 1;
// Set ADC to read internal VCC
ADC_MODE(ADC_VCC); //vcc read
void setup() {
// ITurn Off the LED
pinMode(BUILTIN_LED, OUTPUT);
digitalWrite(BUILTIN_LED, HIGH);
// Set power supply of the DS18B20
pinMode(PinVCC, OUTPUT);
pinMode(PinGND, OUTPUT);
digitalWrite(PinVCC, HIGH);
digitalWrite(PinGND, LOW);
Serial.begin(9600);;
delay(10);
// from m1tt_esp8266 exemple (File-->Exemple)
if (startup) {
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if (startup) {
if ( !ds.search(addr))
{
ds.reset_search();
delay(250);
return;
}
if (OneWire::crc8(addr, 7) != addr[7])
{
Serial.println("CRC is not valid!");
return;
}
// the first ROM byte indicates which chip
switch (addr[0])
{
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
startup = 0;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(1000);
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for ( i = 0; i < 9; i++)
{
data[i] = ds.read();
}
// Convert the data to actual temperature
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10)
{
raw = (raw & 0xFFF0) + 12 - data[6];
}
}
else
{
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
// exemple mqtt_esp8266 (File-->Exemple)
if (!client.connected()) {
reconnect();
}
client.loop();
float vdd = ESP.getVcc() / 1000.0;
snprintf (msg, 75, "%f", celsius);
Serial.print("Publish temperature value to ");
Serial.print(mqtt_server);
Serial.print(" : ");
Serial.print(temp_topic);
Serial.print(" = ");
Serial.println(msg);
client.publish(temp_topic, msg);
snprintf (msg, 75, "%f", vdd);
Serial.print("Publish VDD value to :");
Serial.print(mqtt_server);
Serial.print(" : ");
Serial.print(vdd_topic);
Serial.print(" = ");
Serial.println(msg);
client.publish(vdd_topic, msg);
// wait for the MQTT message to be send
delay(1000);
Serial.print("ESP8266 in sleep mode for ");
Serial.print(sleepTimeM);
Serial.println(" minutes");
//Time in uS
ESP.deepSleep(sleepTimeM * 60 * 1000000);
}
// from https://github.com/esp8266/Arduino/issues/1958
void setup_wifi() {
/*delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
*/
WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.mode( WIFI_STA );
WiFi.config( ip, gateway, subnet );
WiFi.begin( ssid, password );
Serial.println("");
Serial.print("WiFi connected, ");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// from m1tt_esp8266 exemple (File-->Exemple)
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
// from m1tt_esp8266 exemple (File-->Exemple)
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
}
|
9c7186fa1b836400554d09f44d660aed19aea0d8
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
gevard/esp_temp2mqtt
|
765d27178fe2885b4cd9cbd821d10cf11953ce4f
|
4e321a1c4fe075155a80dddf1bc6ef42ea1cfdff
|
refs/heads/master
|
<repo_name>afroborg/tic-tac-toe<file_sep>/src/Game.java
import java.util.Arrays;
import java.util.Scanner;
public class Game {
private final int BOARD_SIZE = 3;
private Tile[][] board;
private boolean running;
private Tile currentPlayer;
public Game() {
this.setup();
}
private void setup() {
// Initialize attributes
this.board = new Tile[BOARD_SIZE][BOARD_SIZE];
this.running = true;
this.currentPlayer = Tile.X;
// Populate board-matrix
for (Tile[] tiles : board) {
Arrays.fill(tiles, Tile.EMPTY);
}
}
public void start() {
Scanner scan = new Scanner(System.in);
this.output("Welcome to Tic tac toe!");
this.output("To end the game early, input a negative number.");
while (this.running) {
this.printBoard();
// Get user input for row
int row = this.userInput(scan, "Row");
if (row < 0) {
this.running = false;
break;
}
// Get user input for column
int col = this.userInput(scan, "Column");
if (col < 0) {
this.running = false;
break;
}
// Try to set tile
if (this.setTile(row, col)) {
this.nextTurn();
} else {
this.output("\nThis spot is already taken, please try again...");
// Skip unnecessary isGameOver-check because the board has not changed.
continue;
}
// After each move, check if someone has won
if (this.isGameOver()) {
this.running = false;
this.printBoard();
this.output("Game over");
}
}
scan.close();
}
private int userInput(Scanner scan, String value) {
String lowercase = value.toLowerCase();
System.out.print("(" + this.currentPlayer.toString() + ")" + " - Enter " + lowercase + ": ");
// Try-catch to make sure that only numbers are inputted
try {
int v = scan.nextInt();
if (v > BOARD_SIZE) {
this.output(value + " does not exist, please choose a " + lowercase + " between 1-" + BOARD_SIZE);
return userInput(scan, value);
}
return v;
} catch (Exception e) {
this.output("That is not a valid number, please try again...");
scan.nextLine();
return this.userInput(scan, value);
}
}
private boolean setTile(int r, int c) {
int row = r - 1, col = c - 1;
if (this.board[row][col] != Tile.EMPTY)
return false;
this.board[row][col] = this.currentPlayer;
return true;
}
private void printBoard() {
this.output("");
for (int i = 0; i < board.length; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < this.board[i].length; j++) {
// Add lines to middle sections
if (j != 0 && j != this.board[i].length)
row.append(" | ");
// Check value of tile in matrix and add that value to output string
switch (this.board[i][j]) {
case X:
row.append(" x ");
break;
case O:
row.append(" o ");
break;
case EMPTY:
row.append(" ");
break;
}
}
// Print row
this.output(row.toString());
// Add lines to middle sections
if (i != board.length - 1) {
for (int j = 0; j < 15; j++) {
System.out.print("-");
}
this.output("");
}
}
this.output("");
}
private boolean isGameOver() {
// Check rows
for (int i = 0; i < BOARD_SIZE; i++)
if (this.checkRowCol(this.board[i][0], this.board[i][1], this.board[i][2]))
return true;
// Check columns
for (int i = 0; i < BOARD_SIZE; i++)
if (this.checkRowCol(this.board[0][i], this.board[1][i], this.board[2][i]))
return true;
// Check diagonal left to right
if (this.checkRowCol(this.board[0][0], this.board[1][1], this.board[2][2]))
return true;
// Check diagonal right to left
return this.checkRowCol(this.board[0][2], this.board[1][1], this.board[2][0]);
}
// Check if three tiles are the same
private boolean checkRowCol(Tile a, Tile b, Tile c) {
return a == b && a == c && a != Tile.EMPTY;
}
private void nextTurn() {
this.currentPlayer = this.currentPlayer == Tile.X ? Tile.O : Tile.X;
}
private void output(String s) {
System.out.println(s);
}
}
|
c495afd348bdb0653c3572e1111aa3c0e5618359
|
[
"Java"
] | 1
|
Java
|
afroborg/tic-tac-toe
|
32b42c7291e5e5437c2ad944292f4c3a9c84df94
|
0f978b8a13886bf33210a3d178e3fc5c075448a0
|
refs/heads/master
|
<file_sep>Garden Home project
With association with the Garden Home History Project, I completed a digitization and density analysis of all buildings that were viewable from historical USGS aerial photography.
Full project overview at: https://www.spenserkuroda.com/project-garden-home-history.html
<file_sep>"""
Title: Visualing Change in the Garden Home neighborhood
Description: Iterates through each of the feature classes and pulls buildings
that the only were built since the previous decade.
Follow-up with hexbinning and kernel density
"""
# Import Libraries
import arcpy, os, zipfile
from requests import get
from io import BytesIO
from zipfile import ZipFile
# Set Workspsce
wksp = r'E:\GIS_DATA\GEO_267\Garden Home History\Data.gdb'
arcpy.env.workspace = wksp
arcpy.env.overwriteOutput = True
# Set feature classes
featNames = ['Buildings_1955', 'Buildings_1960', 'Buildings_1970'
, 'Buildings_1985', 'Buildings_1995', 'Buildings_2008'
, 'Buildings_2010']
# Generate empty list for outputs (for later use)
decadePts = []
## Parse out newly created features per decade
for feat in featNames:
# Extract Year from Feature
CurrentYear = feat.split('_')[-1]
inLYR = arcpy.MakeFeatureLayer_management(feat, CurrentYear)
# Set WhereClause based on Year
WC = """ 'Year_Noted' = %s """ % CurrentYear
selSet = arcpy.SelectLayerByAttribute_management(inLYR, "", WC)
# Create New features based on new buildings per decade
outFeat = "Only" + CurrentYear
arcpy.CopyFeatures_management(selSet, outFeat)
# Feature to Point
arcpy.FeatureToPoint_management(outFeat, " Point" + CurrentYear)
decadePts.append("Point" + CurrentYear)
### Create Density Maps with Hexagon Binning
##Create Concave Hull (not included in ArcGIS)
# Download ConcaveHull Tool and import into ArcPy
url = 'https://geonet.esri.com/servlet/JiveServlet/download/54704-1-156235/ConcaveHullByCase.zip'
request = get(url)
zip_file= ZipFile(BytesIO(request.content))
zip_file.extractall(r'E:\GIS_DATA')
arcpy.ImportToolbox(r'E:\GIS_DATA\ConcaveHullByCase')
# Apply Concave Hull to build polygon to overlay hexagon mesh
buildPt = arcpy.FeatureToPoint_management(r'E:\GIS_DATA\GEO_267\Garden Home History\Data.gdb\Buildings_2010', 'Build_pts')
arcpy.ConcaveHull(buildPt, "", 'buildingPerimeter')
arcpy.Merge_management(['buildingPerimeter', 'GH_Neighborhood'], 'hex_basis')
## Apply Hexagons
'''
Using "Create Hexagon Tesselation" tool created by <NAME>,
Available at http://www.arcgis.com/home/item.html?id=03388990d3274160afe240ac54763e57#!
'''
arcpy.ImportToolbox(r'E:\GIS_DATA\HexagonTool.tbx')
arcpy.CreateHexagonsBySideLength2('hex_basis', 129.48, 'hexagon_base')
# Hexagons per Decade
for decade in decadePts:
shape = decade.split('.')[0]
year = shape.split('Point')[1]
arcpy.SpatialJoin_analysis('hexagon_base', decade, 'hex' + year)
# Hexagons covering all current buildings
arcpy.FeatureToPoint_management(buildPt, 'CurrentBuild')
arcpy.SpatialJoin_analysis('hexagon_base', 'CurrentBuild', 'CurrentHex')
<file_sep>import arcpy, urllib2, os, csv, re
import pandas as pd
from bs4 import BeautifulSoup as BS
# Access VA election page
url = r'http://results.elections.virginia.gov/vaelections/2016%20November%20General/Site/Locality/Index.html'
header = {'User-Agent': 'Mozilla/5.0'}
request = urllib2.Request(url, headers=header)
page = urllib2.urlopen(request)
headsoup = BS(page, "html.parser")
html_body = headsoup.body.findAll(id='tab-1')
# Parse html to get hyperlinks to each individual counties'/cities' election result page
base_url = r'http://results.elections.virginia.gov/vaelections/2016%20November%20General/Site/Locality/'
virginia_co_link = []
co_name = []
vir_csv = csv.writer(open("Virginia.csv", 'wb'))
for hmtl in html_body:
for a in hmtl.findAll('a', href=True)[7:]:
co_link = a['href'][2:]
co_link_new = co_link.replace(' ', '%20')
county = ' '.join(co_link.split(' ')[:-1])
co_name.append(county)
virginia_co_link.append(base_url + co_link_new)
# For each county parse table and get
for co_url in virginia_co_link:
print(co_url)
county_name = ' '.join(((co_url.split('/')[-2]).split('%20')[:-1]))
print(county_name)
co_request = urllib2.Request(co_url, headers=header)
co_page = urllib2.urlopen(co_request)
soup = BS(co_page, "html.parser")
result_table = soup.body.findAll('table')
co_vote_list = []
for result in result_table[:1]:
votes = result.findAll('td', class_='votes')[:6]
for vote in votes:
co_vote_list.append(int(vote.contents[0].replace(',','')))
if len(co_vote_list) == 6:
Clinton = co_vote_list[0]
Trump = co_vote_list[1]
Johnson = co_vote_list[2]
Stein = co_vote_list[3]
Other = co_vote_list[4] + co_vote_list[5]
vote_roll = [county_name, Clinton, Trump, Johnson, Stein, Other]
print(vote_roll)
vir_csv.writerow(vote_roll)
vir_csv.close
<file_sep>"""
Title: Import sql table to Arc
Description: Import sqlite tables containing the parsed tweets to ArcMap,
using pandas dataframes as an intermediary.
"""
import sqlite3, os, arcpy
import pandas as pd
import numpy as np
# Set Arc Environments
wksp = r'E:\GIS_DATA\GEO_242\Final_Project\Data\Tweets'
arcpy.env.workspace = wksp
arcpy.env.overwriteOutput = True
tableList = ['trump', 'climate', 'news', 'politics', 'covfefe']
for table in tableList:
# Connect and read SQLite data by table name
conn = sqlite3.connect('selected_tweets.db')
inTable = ("SELECT * FROM %s" %table)
df = pd.read_sql_query(inTable, conn)
# Set output objects
outDBF = table + ".dbf"
lyrName = table
outSHP = table + ".shp"
print(outDBF, lyrName, outSHP)
### Convert to ESRI dbf
x = np.array(np.rec.fromrecords(df.values))
names = df.dtypes.index.tolist()
x.dtype.names = tuple(names)
tbl = arcpy.da.NumPyArrayToTable(x, os.path.join(wksp, outDBF))
lyr = arcpy.MakeXYEventLayer_management(os.path.join(wksp, outDBF), "y_coordina", "x_coordina", lyrName)
# arcpy.
<file_sep># python_portfolio
Store of previous python code used in projects
<file_sep>"""
Import CSVs and xls files to ESRI
"""
import xlrd, arcpy, csv, os, urllib2
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup as BS
# Set Workspace
wksp = r'E:\GIS_DATA\GEO_242\Final_Project\Data\ElectionData.gdb'
arcpy.env.workspace = wksp
arcpy.env.overwriteOutput = True
# Inputs
xls_folder = r'E:\GIS_DATA\GEO_242\Final_Project\ElectionResultAnalysis\Election Data\XLS'
US_counties = r'USCounties'
# Convert xls tables to geodatabase tables
xls_dir = r'E:\GIS_DATA\GEO_242\Final_Project\ElectionResultAnalysis\ElectionData\XLS'
xls_list = os.listdir(xls_dir)
for xls in xls_list:
xls_path = os.path.join(xls_dir, xls)
st_name = xls.split('.')[0]
outDBF = st_name.replace(' ','')
arcpy.ExcelToTable_conversion(xls_path, outDBF)
#Covert csv to geodatabase tables
csv_dir = r'E:\GIS_DATA\GEO_242\Final_Project\ElectionResultAnalysis\ElectionData\CSV'
csv_list= os.listdir(csv_dir)
print(csv_list)
for csv in csv_list:
csv_path = os.path.join(csv_dir, csv)
df = pd.read_csv(csv_path)
st_name = csv.split('.')[0]
outDBF = st_name.replace(' ','')
print(outDBF)
### Convert to ESRI dbf
x = np.array(np.rec.fromrecords(df.values))
names = df.dtypes.index.tolist()
x.dtype.names = tuple(names)
tbl = arcpy.da.NumPyArrayToTable(x, outDBF[:10])
### Import FIPS numbers and corresponding state
fips_list = []
# Access website with list
url = r'https://www.mcc.co.mercer.pa.us/dps/state_fips_code_listing.htm '
header = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, headers=header)
page = urllib2.urlopen(req)
soup = BS(page, "html.parser")
# Parse out table
table = soup.body.find('table')
# Build a 2-D array with fips codes and states
for row in table.findAll('tr')[1:]:
cells = row.findAll('td')
fips1 = cells[1].contents[0]
state1 = cells[2].contents[0]
fips2 = cells[4].contents[0]
state2 = cells[5].contents[0]
st_fips = [state1, fips1]
st_fips2 = [state2, fips2]
fips_list.append(st_fips)
fips_list.append(st_fips2)
# Break County map by states
# Get rid codes/states I didnt need
fips_list.sort()
del fips_list[1]
del fips_list[1]
del fips_list[10]
del fips_list[10]
del fips_list[-1]
del fips_list[-6]
del fips_list[-13]
print(fips_list)
for fips in fips_list:
fip_code = fips[1]
state = fips[0]
WC = '"STATEFP"=' + "'%s'" %fip_code
inLYR = arcpy.MakeFeatureLayer_management(US_counties, "Counties", WC)
arcpy.CopyFeatures_management(inLYR, fips[0].replace(' ',"")[:8] + "_co")
print(state.capitalize())
inFeat = fips[0].replace(' ',"")[:8] + "_co.shp"
joinTable = fips[0].capitalize().replace(' ','')
outFeat_name = fips[0].replace(' ',"")[:6] + "_elec"
print(inFeat)
print(joinTable)
joinFeat = arcpy.JoinField_management(inFeat, 'NAME', joinTable, 'County')
arcpy.CopyFeatures_management(joinFeat, outFeat_name)
<file_sep>"""
parse coords columns into x and y coords
Extract old table as RAW table
cursor -> fetch -> parse coods (and html from text) -> re-upload
create new table (Revised)
"""
import sqlite3, dataset, re, fnmatch
table_list = ['trump', 'climate', 'news', 'politics', 'covfefe']
for inTable in table_list:
db = dataset.connect("sqlite:///selected_tweets.db")
conn = sqlite3.connect("tweetstest.db")
curs = conn.cursor()
curs.execute("SELECT * FROM %s" % inTable).fetchone()
outTable = inTable
### Extract data and parse tweets out
for row in curs:
id_str = row[1]
x_coords = eval(row[2])["coordinates"][1]
y_coords = eval(row[2])["coordinates"][0]
user = row[3]
sentiment = row[4]
tweet_list = [id_str, user, x_coords, y_coords, sentiment]
#Checks for presence of weblink and then pull Website out of text if there is.
raw_text = row[5]
https = r"https:"
http = r"http:"
# Determines if weblink is present
link_number = 1
#Parses tweets if the contains a https link (majority)
if raw_text.count(https) > 0:
while link_number != 0 :
web_present = True
webLinks = []
tweet_list.append(web_present)
# Splits the text up and searches for weblink
text_list = raw_text.split(" ")
wild = fnmatch.filter(text_list, '*%s*' %https)
link_number = len(wild)
# Iterates through tweets and pulls out web links and puts tweet together again
for link in wild:
web_index = text_list.index(link)
web_link = text_list.pop(web_index)
clean_text = " ".join(text_list)
webLinks.append(web_link)
link_number = link_number - 1
tweet_list.append(clean_text)
webLink1 = webLinks[0]
tweet_list.append(webLink1)
if len(webLinks) > 1:
webLink2 = webLinks[1]
tweet_list.append(webLink2)
else:
webLink2 = "N/A"
tweet_list.append(webLink2)
# Parses tweet if the tweet contains a http link
elif raw_text.count(http) > 0:
while link_number != 0:
web_present = True
tweet_list.append(web_present)
webLinks = []
text_list = raw_text.split(" ")
wild = fnmatch.filter(text_list, '*%s*' %http)
link_number = len(wild)
for link in wild:
web_index = text_list.index(link)
web_link = text_list.pop(web_index)
clean_text = " ".join(text_list)
webLinks.append(web_link)
link_number = link_number - 1
final_text = clean_text
tweet_list.append(final_text)
webLink1 = webLinks[0]
tweet_list.append(webLink1)
if len(webLinks) > 1:
webLink2 = webLinks[1]
tweet_list.append(webLink2)
else:
webLink2 = "N/A"
tweet_list.append(webLink2)
# Does not parse tweet, does not contain a web link
else:
web_present = False
final_text = raw_text
webLink1 = "N/A"
webLink2 = "N/A"
tweet_list.append(web_present)
tweet_list.append(final_text)
tweet_list.append(webLink1)
tweet_list.append(webLink2)
# Insert into a SQLite Table
table = db["%s" % outTable]
table.insert(dict(
tweet_id = tweet_list[0],
user_name = tweet_list[1],
x_coordinate = tweet_list[2],
y_coordinate = tweet_list[3],
tweet = tweet_list[6],
sentiment_score = tweet_list[4],
web_link_present = tweet_list[5],
web_link1 = tweet_list[7],
web_link2 = tweet_list[8]))
print("tweet added", tweet_list[6])
print(inTable + " tweets done")
<file_sep>"""
Title: Election Results by County
Description: Pulls 2016 Presidential data by county from Wikipedia,
and creates a csv.
"""
import arcpy, urllib2, os, csv, re
import numpy as np
from bs4 import BeautifulSoup as BS
# Set inputs
csv_file = r"E:\GIS_DATA\GEO_242\Final_Project\ElectionResultAnalysis\St_Elections.txt"
counties = r"E:\GIS_DATA\US_BOUNDARY\cb_2016_us_county_500k.shp"
### Parse individual states to url path
state_elec_csv = csv.reader(open(csv_file), delimiter = '\t')
state_elec_csv.next() #Skip header
# Lexicon for header names
trump_headers = ['Trump', 'Trump#', 'Trump votes', 'Trump Votes']
clinton_headers = ['Clinton', 'Clinton#', 'Clinton votes', 'Clinton Votes']
johnson_headers = ['Johnson', 'Johnson#', 'Johnson Votes']
stein_headers = ['Stein', 'Stein#', 'Stein Votes']
total_headers = ['Total', 'Totals', 'Total Votes', 'Totals#']
other_headers = ['Other#', "Other", "Other votes", 'Others']
for state in state_elec_csv:
if state[2]== 'wikisort':
print(state[0])
url = state[-1] # url of the wiki page pulled from csv
header = {'User-Agent': 'Mozilla/5.0'}
request = urllib2.Request(url, headers=header)
page = urllib2.urlopen(request)
soup = BS(page, "html.parser")
state_results = []
header_list = []
print(len(soup.findAll('table', class_= 'wikitable sortable')))
# If there is only one sortable wikitable
if len(soup.findAll('table', class_= 'wikitable sortable')) == 1:
table = soup.find('table', class_= 'wikitable sortable')
for row in table.findAll('tr')[:1]:
### Determine Header indexes
for header in row.findAll('th'):
# Checks for b tag in html
if header.b is not None:
header_list.append(header.b.contents[0])
# Passes if there no b tag
else:
header_list.append(header.contents[0])
# Assign set index number to text
for header in header_list:
# Checks for matching names, since some tables use slightly different header names
find_t_index = list(set(trump_headers).intersection(header_list))[0]
find_c_index = list(set(clinton_headers).intersection(header_list))[0]
try:
find_total_index = list(set(total_headers).intersection(header_list))[0]
Total_index = header_list.index(find_total_index)
except:
Total_index = -9999
try:
find_s_index = list(set(stein_headers).intersection(header_list))[0]
Stein_index = header_list.index(find_s_index)
except:
Stein_index = -9999
try:
find_j_index = list(set(johnson_headers).intersection(header_list))[0]
Johnson_index = header_list.index(find_j_index)
except:
Johnson_index = -9999
try:
find_o_index = list(set(other_headers).intersection(header_list))[0]
Other_index = header_list.index(find_o_index)
except:
Other_index = -9999
# Sets index number
Trump_index = header_list.index(find_t_index)
Clinton_index = header_list.index(find_c_index)
if state[0] == 'Kentucky' or state[0] == 'North Carolina':
for row in table.findAll('tr')[1:-1]:
cells = row.findAll('td')
try:
County = cells[0].a.contents[0]
except:
County = cells[0].contents[0]
try:
Trump = int(cells[Trump_index].b.contents[0].replace(',',''))
except:
Trump = int(cells[Trump_index].contents[0].replace(',',''))
try:
Clinton = int(cells[Clinton_index].b.contents[0].replace(',',''))
except:
Clinton = int(cells[Clinton_index].contents[0].replace(',',''))
if Johnson_index != -9999:
Johnson = int(cells[Johnson_index].contents[0].replace(',',''))
elif Johnson_index == -9999:
Johnson = 0
if Stein_index != -9999:
Stein = int(cells[Stein_index].contents[0].replace(',',''))
elif Stein_index == -9999:
Stein = 0
try:
if Other_index != -9999:
Other = int(cells[Other_index].contents[0].replace(',',''))
elif Other_index == -9999:
Other = int(cells[Total_index].contents[0].replace(',','')) - (Trump + Clinton + Johnson + Stein)
except:
Other = 0
co_rows = [County, Clinton, Trump, Johnson, Stein, Other]
state_results.append(co_rows)
else:
for row in table.findAll('tr')[1:]:
for header in row.findAll('th'):
if header.b is not None:
header_list.append(header.b.contents[0])
else:
header_list.append(header.contents[0])
cells = row.findAll('td')
try:
County = cells[0].a.contents[0]
except:
County = cells[0].contents[0]
try:
Trump = int(cells[Trump_index].b.contents[0].replace(',',''))
except:
Trump = int(cells[Trump_index].contents[0].replace(',',''))
try:
Clinton = int(cells[Clinton_index].b.contents[0].replace(',',''))
except:
Clinton = int(cells[Clinton_index].contents[0].replace(',',''))
if Johnson_index != -9999:
Johnson = int(cells[Johnson_index].contents[0].replace(',',''))
elif Johnson_index == -9999:
Johnson = 0
if Stein_index != -9999:
Stein = int(cells[Stein_index].contents[0].replace(',',''))
elif Stein_index == -9999:
Stein = 0
try:
if Other_index != -9999:
Other = int(cells[Other_index].contents[0].replace(',',''))
elif Other_index == -9999:
Other = int(cells[Total_index].contents[0].replace(',','')) - (Trump + Clinton + Johnson + Stein)
except:
Other = 0
co_rows = [County, Clinton, Trump, Johnson, Stein, Other]
state_results.append(co_rows)
### More than one sortable wikitable
else:
table = soup.findAll('table', class_= 'wikitable sortable')
for row in table[1].findAll('tr')[:1]:
for header in row.findAll('th'):
if header.b is not None:
header_list.append(header.b.contents[0])
else:
header_list.append(header.contents[0])
find_t_index = list(set(trump_headers).intersection(header_list))[0]
find_c_index = list(set(clinton_headers).intersection(header_list))[0]
find_j_index = list(set(johnson_headers).intersection(header_list))[0]
Trump_index = header_list.index(find_t_index)
Clinton_index = header_list.index(find_c_index)
Johnson_index = header_list.index(find_j_index)
if header_list.count("Stein#") == 1 or header_list.count("Stein") == 1:
Stein_index = header_list.index(list(set(stein_headers).intersection(header_list))[0])
elif header_list.count('Stein') == 0:
Stein_index = -9999
if header_list.count('Total') > 0:
Total_index = header_list.index('Total')
elif header_list.count('Total Votes') > 0:
Total_index = header_list.index('Total Votes')
for row in table[1].findAll('tr')[1:]:
cells = row.findAll('td')
County = cells[0].a.contents[0]
Trump = int(cells[Trump_index].contents[0].replace(',',''))
Clinton = int(cells[Clinton_index].contents[0].replace(',',''))
Johnson = int(cells[Johnson_index].contents[0].replace(',',''))
if Stein_index != -9999:
Stein = int(cells[Stein_index].contents[0].replace(',',''))
elif Stein_index == -9999:
Stein = 0
try:
if Other_index != -9999:
Other = int(cells[Stein_index].contents[0].replace(',',''))
elif Other_index == -9999:
Other = int(cells[Total_index].contents[0].replace(',','')) - (Trump + Clinton + Johnson + Stein)
except:
pass
co_rows = [County, Clinton, Trump, Johnson, Stein, Other]
state_results.append(co_rows)
print(state_results)
with open(r'E:\GIS_DATA\GEO_242\Final_Project\ElectionResultAnalysis\%s.csv' % state[0].replace(' ',''), 'wb') as f:
writer = csv.writer(f)
writer.writerows(state_results)
f.close()
csv_file.close()
<file_sep>import tweepy, json, sqlite3, dataset, time
from tweepy.streaming import StreamListener
import pandas
from nltk.sentiment.vader import SentimentIntensityAnalyzer as sia
# Set Twitter credentials
auth = tweepy.OAuthHandler('v2yq8Vzz2gZNAMCMUCuuOsS48', '<KEY>')
auth.set_access_token('<KEY>', '<KEY>')
# Workspace for tweets - SQLite database (use dataset lib to imprt schema)
db = dataset.connect("sqlite:///tweets.db") # Create a data database, create one if none exists
### Query Twitter
class Streamer(StreamListener):
def on_status(self, status):
try:
if status.coordinates != None and status.place.country_code == 'US' and status.retweeted == False:
id_str = status.id_str # ID given to specific tweet
name = status.user.screen_name # Name of Tweeter
created = status.created_at # When the tweet was sent
text = status.text # The tweet
coords = status.coordinates # Coordinates from where the tweet was sent
coords = json.dumps(coords) # drops the coords from json to string, so it can be stored in sql
# Add sentiment analysis
sid = sia()
polarity = sid.polarity_scores(text)["compound"] # Set sentiment score to "polarity" object
if polarity != 0.0:
#Store Tweets into SQLite db
table = db["tweets"]
table.insert(dict(
tweet_id = id_str,
user = name,
tweet_datetime = created,
text = text,
sentement_score = polarity,
coords = coords,
))
print("Tweet Added", text)
except TypeError:
print('e')
pass
def on_error(self, status):
print(status)
# Set Bounding box to isolate geotagged tweets. Set to Lower 48 of the US.
US_bounds = [-133.0,25.3,-59.7,50.8]
# Call the Streaming service, pass the authorizing credentials
# Call the query using the filter
def start_stream():
while True:
try:
twitter_stream = tweepy.Stream(auth, Streamer())
twitter_stream.filter(locations=US_bounds, stall_warnings=True)
except:
continue
start_stream()
|
45f3f692c1c216ff7412d8bfec4c165e1b5be053
|
[
"Markdown",
"Python"
] | 9
|
Markdown
|
snkuroda/python_portfolio
|
b6c1684a5d4e2c027956410392abd73a6d61df3b
|
fe1cf3d11b27a9a9fcfa436425adc60360b243bc
|
refs/heads/master
|
<repo_name>PakhomovMA/Online_Store<file_sep>/src/dao/impl/CategoryDAOImpl.java
package dao.impl;
import dao.CategoryDAO;
import entity.CategoryEntity;
import exceptions.EntityNotFoundException;
import javax.persistence.*;
import java.util.List;
public class CategoryDAOImpl implements CategoryDAO {
private EntityManagerFactory factory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
@Override
public void addCategory(CategoryEntity category) {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
manager.persist(category);
manager.getTransaction().commit();
manager.close();
}
@Override
public void removeCategory(CategoryEntity category) throws EntityNotFoundException {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
CategoryEntity categoryEntity = manager.find(CategoryEntity.class, category.getCategoryId());
if(categoryEntity != null) {
manager.remove(categoryEntity);
manager.getTransaction().commit();
manager.getTransaction().begin();
manager.createNativeQuery("ALTER TABLE goods_category AUTO_INCREMENT = 1").executeUpdate();
manager.getTransaction().commit();
manager.close();
}
else {
manager.getTransaction().rollback();
manager.close();
throw new EntityNotFoundException("Error deleting category");
}
}
@Override
public void editCategory(CategoryEntity category, String new_name) throws EntityNotFoundException {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
CategoryEntity categoryEntity = manager.find(CategoryEntity.class, category.getCategoryId());
if(categoryEntity != null) {
categoryEntity.setName(new_name);
manager.getTransaction().commit();
manager.close();
}
else {
manager.getTransaction().rollback();
manager.close();
throw new EntityNotFoundException("Category not found");
}
}
@Override
public CategoryEntity findCategoryById(int id) throws EntityNotFoundException {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
CategoryEntity category = manager.find(CategoryEntity.class, id);
if(category == null) {
manager.getTransaction().rollback();
manager.close();
throw new EntityNotFoundException("Category not found");
}
manager.getTransaction().commit();
manager.close();
return category;
}
@Override
public List<String> getAll() {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
TypedQuery<String> namedQuery = manager.createNamedQuery("CategoryEntity.getAll", String.class);
List<String> list = namedQuery.getResultList();
manager.getTransaction().commit();
manager.close();
return list;
}
}
<file_sep>/src/dao/impl/AttributeDAOImpl.java
package dao.impl;
import dao.AttributeDAO;
import entity.AttributeEntity;
import exceptions.EntityNotFoundException;
import javax.persistence.*;
import java.util.List;
public class AttributeDAOImpl implements AttributeDAO{
private EntityManagerFactory factory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
@Override
public void addAttribute(AttributeEntity attribute) {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
manager.persist(attribute);
manager.getTransaction().commit();
manager.close();
}
@Override
public void removeAttribute(AttributeEntity attribute) throws EntityNotFoundException {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
AttributeEntity attributeEntity = manager.find(AttributeEntity.class, attribute.getCategoryId2());
if(attributeEntity != null) {
manager.remove(attributeEntity);
manager.getTransaction().commit();
manager.close();
}
else {
manager.getTransaction().rollback();
manager.close();
throw new EntityNotFoundException("Error deleting attribute");
}
}
@Override
public List findAttributeById(int type_id) throws EntityNotFoundException {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
Query query = manager.createNativeQuery("SELECT attr_key FROM goods_category_attr WHERE category_id2 =:id_param");
query.setParameter("id_param", type_id);
List list = query.getResultList();
if(list.isEmpty()) {
manager.getTransaction().rollback();
manager.close();
throw new EntityNotFoundException("Attribute not found");
}
manager.getTransaction().commit();
manager.close();
return list;
}
@Override
public List<String> getAll() {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
TypedQuery<String> namedQuery = manager.createNamedQuery("AttributeEntity.getAll", String.class);
List<String> list = namedQuery.getResultList();
manager.getTransaction().commit();
manager.close();
return list;
}
}
<file_sep>/src/dao/ValueDAO.java
package dao;
import entity.ValueEntity;
import exceptions.EntityNotFoundException;
import java.util.List;
public interface ValueDAO {
void addValue(ValueEntity value);
void removeValue(ValueEntity value) throws EntityNotFoundException;
List findValueById(int goods_id) throws EntityNotFoundException;
List<String> getAll();
}
<file_sep>/Web_Shop_script.sql
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema webshop
-- -----------------------------------------------------
-- This is Web Shop model for J2EE project
-- -----------------------------------------------------
-- Schema webshop
--
-- This is Web Shop model for J2EE project
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `webshop` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `webshop` ;
-- -----------------------------------------------------
-- Table `webshop`.`goods_category`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webshop`.`goods_category` (
`category_id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '',
`name` VARCHAR(50) NULL COMMENT '',
PRIMARY KEY (`category_id`) COMMENT '')
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `webshop`.`goods`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webshop`.`goods` (
`goods_id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '',
`name` VARCHAR(100) NULL COMMENT '',
`category_id1` INT UNSIGNED NOT NULL COMMENT '',
PRIMARY KEY (`goods_id`) COMMENT '',
INDEX `category_id1_idx` (`category_id1` ASC) COMMENT '',
CONSTRAINT `category_id1`
FOREIGN KEY (`category_id1`)
REFERENCES `webshop`.`goods_category` (`category_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `webshop`.`goods_category_attr`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webshop`.`goods_category_attr` (
`category_id2` INT UNSIGNED NOT NULL COMMENT '',
`key` VARCHAR(50) NOT NULL COMMENT '',
INDEX `category_id_idx` (`category_id2` ASC) COMMENT '',
UNIQUE INDEX `key_UNIQUE` (`key` ASC) COMMENT '',
CONSTRAINT `category_id2`
FOREIGN KEY (`category_id2`)
REFERENCES `webshop`.`goods_category` (`category_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `webshop`.`attr_value`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webshop`.`attr_value` (
`goods_id1` INT UNSIGNED NOT NULL COMMENT '',
`value` VARCHAR(50) NULL COMMENT '',
`key1` VARCHAR(50) NOT NULL COMMENT '',
INDEX `goods_id_idx` (`goods_id1` ASC) COMMENT '',
UNIQUE INDEX `key_UNIQUE` (`key1` ASC) COMMENT '',
CONSTRAINT `goods_id`
FOREIGN KEY (`goods_id1`)
REFERENCES `webshop`.`goods` (`goods_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `key`
FOREIGN KEY (`key1`)
REFERENCES `webshop`.`goods_category_attr` (`key`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/src/entity/AttributeEntity.java
package entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "goods_category_attr", schema = "", catalog = "webshop")
@NamedQuery(name = "AttributeEntity.getAll", query = "SELECT attrKey FROM AttributeEntity")
public class AttributeEntity implements Serializable{
private int categoryId2;
private String attrKey;
public AttributeEntity(String attrKey, int categoryId2) {
this.attrKey = attrKey;
this.categoryId2 = categoryId2;
}
public AttributeEntity() {
}
@Id
@Column(name = "category_id2")
public int getCategoryId2() {
return categoryId2;
}
public void setCategoryId2(int categoryId2) {
this.categoryId2 = categoryId2;
}
@Basic
@Column(name = "attr_key")
public String getAttrKey() {
return attrKey;
}
public void setAttrKey(String attrKey) {
this.attrKey = attrKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AttributeEntity that = (AttributeEntity) o;
if (getCategoryId2() != that.getCategoryId2()) return false;
return getAttrKey().equals(that.getAttrKey());
}
@Override
public int hashCode() {
int result = getCategoryId2();
result = 31 * result + getAttrKey().hashCode();
return result;
}
@Override
public String toString() {
return "AttributeEntity{" +
"categoryId2=" + categoryId2 +
", key='" + attrKey + '\'' +
'}';
}
}
<file_sep>/src/dao/impl/FactoryEntity.java
package dao.impl;
import dao.AttributeDAO;
import dao.CategoryDAO;
import dao.GoodsDAO;
import dao.ValueDAO;
public class FactoryEntity {
private static CategoryDAO categoryDAO = null;
private static GoodsDAO goodsDAO = null;
private static AttributeDAO attributeDAO = null;
private static ValueDAO valueDAO = null;
private static FactoryEntity instance = null;
public static FactoryEntity getInstance() {
if(instance == null){
return new FactoryEntity();
}
return instance;
}
public CategoryDAO getCategoryDAO() {
if(categoryDAO == null) {
return new CategoryDAOImpl();
}
return categoryDAO;
}
public GoodsDAO getGoodsDAO() {
if(goodsDAO == null) {
return new GoodsDAOImpl();
}
return goodsDAO;
}
public AttributeDAO getAttributeDAO() {
if(attributeDAO == null) {
return new AttributeDAOImpl();
}
return attributeDAO;
}
public ValueDAO getValueDAO() {
if(valueDAO == null) {
return new ValueDAOImpl();
}
return valueDAO;
}
}
|
cdf31b85e3c614b11c8aed8a564264ba06aa6dbd
|
[
"Java",
"SQL"
] | 6
|
Java
|
PakhomovMA/Online_Store
|
72ac73e3e73f4ea77a4374faa10ff844bef1a63f
|
7d542b543e3019bead76f4c6a2dd4d7ba8b468db
|
refs/heads/master
|
<repo_name>LizaKoliechkina/ap-webtech<file_sep>/src/main/java/edu/ap/spring/tml/controller/TMLController.java
package edu.ap.spring.tml.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import edu.ap.spring.redis.RedisService;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Controller
public class TMLController {
@Autowired
private RedisService service;
@GetMapping("/new")
public String getCreateForm() {
return "newRecipe";
}
@PostMapping ("/new")
public String newRecipe(@RequestParam ("name") String name,
@RequestParam ("ingredients") String ingredients,
Model model) {
if(this.service.exists("recipe:"+ name + ":*")) {
return "exists";
}
else {
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String recipeDate = date.format(formatter);
String [] listIngredients = ingredients.split(",");
this.service.setKey("recipe:" + name + ":" + listIngredients + recipeDate, recipeDate + " " + name + ": " + ingredients);
}
return "redirect:/listrecipes";
}
@GetMapping("/listrecipes")
public String listRecipes (Model model) {
ArrayList<String> recipes = new ArrayList<String>();
for(String a : this.service.keys("recipe:*")) {
recipes.add(this.service.getKey(a));
}
model.addAttribute("recipes", recipes);
return "listrecipes";
}
@GetMapping("/search")
public String getSearchForm() {
return "searchRecipe";
}
@PostMapping ("/search")
public String findRecipe (@RequestParam ("name") String name,
Model model) {
ArrayList<String> recipes = new ArrayList<String>();
for(String a : this.service.keys("recipe:"+ name + ":*")) {
recipes.add(this.service.getKey(a));
}
model.addAttribute("recipes", recipes);
model.addAttribute("name", name);
return "recipeByName";
}
}
<file_sep>/src/main/java/edu/ap/spring/tml/TMLApplication.java
package edu.ap.spring.tml;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"edu.ap.spring.redis",
"edu.ap.spring.tml"})
@SpringBootApplication
public class TMLApplication {
public static void main(String[] args) {
SpringApplication.run(TMLApplication.class, args);
}
}
<file_sep>/README.md
# ap-webtech
## Recipes Application on Redis
Simple Spring boot WebService that allows to manage a recipe database in Redis.
### Technologies:
* Java 1.8
* Spring Boot Framework 2.1
* Redis 3.2
* Bootstrap 4.3
* Thymeleaf
### Example of use:
Open localhost:8080 in your browser and go to '/new' to create a new recipe,
to open a whole list of recipes go to '/listrecipes'
|
cd613d18e16d9cfe897f1c599e8eb76b6db68405
|
[
"Markdown",
"Java"
] | 3
|
Java
|
LizaKoliechkina/ap-webtech
|
212e01503538648438379844e765317d64f9c804
|
16f79dcc70d07ccdb4edeea0999c4a4a749ee86c
|
refs/heads/master
|
<repo_name>tardisdriver/starkwebconcepts<file_sep>/src/components/contact.js
import React from 'react';
import Back from './back';
import Social from './social';
import './contact.css';
const socialList = [
{ img: '/images/githubicon.jpg', account: 'tardisdriver', alt: 'GitHub', link: 'https://github.com/tardisdriver' },
{ img: '/images/twittericon.png', account: 'tardisdriver13', alt: 'Twitter', link: 'https://twitter.com/tardisdriver13' },
{ img: '/images/linkedinicon.png', account: '<NAME>', alt: 'LinkedIn', link: 'https://www.linkedin.com/in/tracy-stark-5923442/' },
{ img: '/images/emailicon.png', account: '<EMAIL>', alt: 'Email', link: 'mailto: <EMAIL>' }
];
export default function Contact(props) {
const socialRender = socialList.map((acct, index) =>
<Social key={index} {...acct} />
);
return (
<div id='contact'>
<Back />
<h1 id='contact-head'>Contact</h1>
<div id='social'>
{socialRender}
</div>
</div>
);
}
<file_sep>/src/components/project-item.js
import React from 'react';
import './project-item.css';
export default function ProjectItem(props) {
return (
<div className='project-item'>
<a className='proj-link' href={props.pubLink} target='_blank'>
<h2 className='proj-heading'>{props.title}</h2>
<img className='proj-image' src={props.img} alt={props.title} />
<p className='stack'>
<span>Stack used:</span>
<span>{props.stack}</span>
</p>
<p className='proj-descr'>{props.descr}</p>
<a className='git-proj-link' href={props.gitLink} target='_blank'>{props.gitLink}</a>
</a>
</div>
);
};<file_sep>/src/components/social.js
import React from 'react';
import './social.css';
export default function Social(props) {
return (
<div className='social-item'>
<a href={props.link} target='_blank'>
<img className='social-img' src={props.img} alt={props.alt} />
<p className='social-name'>{props.account}</p>
</a>
</div>
);
}<file_sep>/src/components/logo.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Logo from './logo';
describe('<Logo />', () => {
it('renders the logo w/o crashing', () => {
shallow(<Logo />);
});
});
<file_sep>/src/components/port-stack.js
import React from 'react';
import './port-stack.css';
export default function PortStack() {
return (
<div id='port-stack'>
<p id='port-stack'>This website developed using React and React-Router</p>
</div>
)
}<file_sep>/src/components/projects.js
import React from 'react';
import ProjectItem from './project-item';
import Back from './back';
import './projects.css';
const projectList = require('../projects.json');
export default function Projects(props) {
const projectsRender = projectList.map((project, index) =>
<ProjectItem key={index} {...project} />
);
return (
<div id='projects-list'>
<Back />
<h1 id='proj-list-head'>Projects</h1>
{projectsRender}
</div>
);
}
<file_sep>/src/components/about.js
import React from 'react';
import Back from './back';
import './about.css';
export default function About(props) {
return (
<div id='about'>
<Back />
<h1 id='about-head'> About</h1 >
<p className='my-summary'>After my time in the US Army, I took the technical skills from my service to work for the Dell help desk via a contract through Stream International. After being laid off from that position, I sought higher education and turned to my second love: science. I recieved a Bachelor's of Science in General Biology in 2006. After some time working in that field, I decided that I missed tech and found my way working for first a digital documentation specialist, then as a technical trainer for a software company.</p>
<p className='my-summary'> Currently, I am seeking to take my hobby of web design to a professional level. To that end, I have been attending the Thinkful Full Stack Web Development bootcamp and expect to graduate in November or December of this year.</p>
<h2 className='summary'>Skills Summary</h2>
<ul className='bullet-list'>
<li className='bullet-list-item'>Over 10 years of experience with HTML and CSS</li>
<li className='bullet-list-item'>Expected to graduate from the Thinkful Full Stack Developer bootcamp 12/2017</li>
<li className='bullet-list-item'>Javascript, Node.js, React.js, Express.js, MongoDB, Git, Linux, MacOS, Windows OS, RESTful APIs, Bootstrap, jQuery, AJAX</li>
<li className='bullet-list-item'>US Army Veteran</li>
</ul>
<h2 className='summary'>Work Experience</h2>
<h3 className='date'>2015 – present</h3>
<h3 className='job'>Appspace -- Technical Training Manager</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Moved to a position that focused on improving the current client training model.</li>
<li className='bullet-list-item'>Redesigned the training curriculum to be modularly standardized so that specific client training goals could be easily met on a per-client basis.</li>
<li className='bullet-list-item'>Marked increase in client satisfaction of training curriculum based on customer surveys.</li>
</ul>
<h3 className='date'>2014 - 2016</h3>
<h3 className='job'>NTXB -- Web Lead</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Volunteer position for a non-profit organization.</li>
<li className='bullet-list-item'>Lead a team consisting of an assistant web lead, a graphics designer, and a Javascript developer.</li>
<li className='bullet-list-item'>Complete overhaul of current website to a simpler UI that was more user-friendly.</li>
<li className='bullet-list-item'>Initially utilized pure HTML5, but then moved to the Concrete5 CMS.</li>
</ul>
<h3 className='date'>2013 – 2015</h3>
<h3 className='job'>Appspace -- Technical Support and Training Manager</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Trained clients on both end user and administration of Appspace either on premise or remote via Cisco WebEx and Citrix GoToMeeting.</li>
<li className='bullet-list-item'>Installed Appspace digital signage software in client environment, typically involving Windows Server 2008/2012 on VMware virtual machines.</li>
<li className='bullet-list-item'>Provided troubleshooting for both software issues and hardware issues.</li>
<li className='bullet-list-item'>Provided proper internal documentation through Netsuite, Salesforce, and JIRA.</li>
<li className='bullet-list-item'>Initiated and created training documents, forms, and workflow to streamline the training process.</li>
</ul>
<h3 className='date'>2012 – 2013</h3>
<h3 className='job'>Jones-Blair -- Documentation Control Specialist</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Created digital documentation control systems from the ground up to mitigate document and information loss occurring within the company. </li>
<li className='bullet-list-item'>Decreased the time taken to find most needed information from several hours to just a few minutes.</li>
<li className='bullet-list-item'>Provided technical writing to update the troubleshooting field manual. </li>
<li className='bullet-list-item'>Created technical drawings using Illustrator and Photoshop for use in manuals and on website.</li>
</ul>
<h3 className='date'>2008 – 2012</h3>
<h3 className='job'>Parker University -- Academic Lab Manager </h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Assisted professors with teaching of microbiology and anatomy labs, and tutoring students.</li>
<li className='bullet-list-item'>Responsible for setting up microbiology, chemistry, organic chemistry, physiology, and anatomy labs. Included mixing and dilution of chemicals, inoculation and cultivation of bacterial specimens, set-up and testing of BIOPAC physiology computer equipment, and setting up anatomy models for classes.</li>
<li className='bullet-list-item'>Involved in research for a study (A study of the effectiveness of table disinfection protocols in the clinics of a chiropractic college) involving the spread of S. aureus, E. coli, and MRSA in chiropractic offices that was published in <i>Journal of Chiropractic Education</i>. 2010;24(1):109.</li>
<li className='bullet-list-item'>Responsible for replenishing laboratory stocks while adhering to a restrictive budget.</li>
</ul>
<h3 className='date'>2006 - 2008 </h3>
<h3 className='job'>North Lake College -- Lab Professor</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Taught General Biology I (BIOL 1406) and General Biology II (BIOL 1408) labs. Classes ranged in size from 4 to 20 students.</li>
<li className='bullet-list-item'>Responsible for test and quiz design for classes, syllabus preparation, grade assessments, lab preparation, and lab supervision.</li>
<li className='bullet-list-item'>Worked closely with lecture professors to ensure solidarity between the lecture series and the lab series.</li>
</ul>
<h3 className='date'>2002-2007</h3>
<h3 className='job'>North Lake College -- Academic Tutor</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Tutored Biology, Chemistry, Physics, Organic Chemistry, and Microbiology.</li>
<li className='bullet-list-item'>Assumed Assistant Managerial role during summer sessions. Managed a group of 2-5 tutors.</li>
<li className='bullet-list-item'>Continually pushed for improvement of the Science Learning Center: expanded hours to include Saturdays to accommodate more students; proposed, designed and implemented a quality assurance survey; designed marketing materials to help drive students to seek academic assistance at the Science Learning Center.</li>
</ul>
<h3 className='date'>1999-2001</h3>
<h3 className='job'>U.S. Army -- 14 E - PATRIOT Fire Control Enhanced Operator/Maintainer</h3>
<ul className='bullet-list'>
<li className='bullet-list-item'>Supported electronic systems on the PATRIOT Missile systems. </li>
<li className='bullet-list-item'>Included programming of PATRIOT system to define Theater of Operations (proprietary system); reading electronic schematics, generating error codes in hexadecimal and converting them to binary to determine which component needed repair or replacing.</li>
<li className='bullet-list-item'>Received Honorable Discharge.</li>
</ul>
<h2 className='summary'>Education</h2>
<h3 className='date'>2017-2017</h3>
<h3 className='job'>Thinkful Bootcamp -- Full Stack Web Development</h3>
<p className='edu-descr'>Coursework included:</p>
<p className='edu-descr'>HTML5, CSS3, JavaScript, JQuery, React, MongoDB, Git, Web API</p>
<h3 className='date'>2004-2006</h3>
<h3 className='job'>University of Texas-Arlington -- B.S. Biological Sciences</h3>
<p className='edu-descr'>Coursework included:</p>
<p className='edu-descr'>Biology, Genetics, Statistics, Trigonometry, Pre-Calculus, Calculus</p>
<h3 className='date'>2002-2007</h3>
<h3 className='job'>North Lake College</h3>
<p className='edu-descr'>Coursework leading up to degree and various personal enrichment courses including:</p>
<p className='edu-descr'>UNIX, JavaScript, A+ certification prep classes</p>
<ul className='bullet-list'>
<li className='bullet-list-item'>Phi Theta Kappa Honor Society</li>
<li className='bullet-list-item'>Served as North Lake chapter’s Public Relations Officer, 2002-2003</li>
<li className='bullet-list-item'>National Dean’s List - 2002</li>
</ul>
</div >
);
}<file_sep>/src/components/back.js
import React from 'react';
import { Link } from 'react-router-dom';
import './back.css';
export default function Back() {
return (
<Link to='/'>
<button id='back'> Back</button>
</Link>
);
}
|
5f207abdaf724da478c36cec7d53a5303f1c2306
|
[
"JavaScript"
] | 8
|
JavaScript
|
tardisdriver/starkwebconcepts
|
4efa5b022a6f321ba9bdb2e877c3192d7d860768
|
9fd9608e76753762a57fa7e566a93dd0b02389f4
|
refs/heads/master
|
<file_sep>#ifndef UI_H
#define UI_H
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "tft.h"
#include "bme280_defs.h"
#define UI_STACK_SIZE 2048
#define UI_UPDATE_RATE_MS 1000
#define SPI_BUS TFT_HSPI_HOST
#define TFT_WIDTH 320
#define TFT_HEIGHT 240
// UI AREA DEFINES
#define HEADER_HEIGHT 25
extern QueueHandle_t qButton;
extern QueueHandle_t qSensor;
extern QueueHandle_t qNetwork;
typedef struct{
unsigned int soc;
unsigned int voltage;
int current;
unsigned int full_capacity;
unsigned int capacity;
bool is_chg;
bool is_dsg;
int temp;
} BattStatus;
typedef struct{
float temp;
float press;
float humid;
} EnviroData;
typedef struct{
BattStatus batt;
EnviroData enviro;
} SensorData;
typedef struct{
bool connected;
char ip_addr[50];
} NetworkData;
#define BUTTON_QUEUE_SIZE 10
// functions to draw screens
void draw_screen();
uint8_t switch_screen(uint8_t current_screen, int8_t dir);
void draw_header();
void draw_header_background();
void draw_body_background();
void init_tft();
void ui_task(void *pvParameters);
#endif
<file_sep>#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "driver/i2c.h"
#include "esp_log.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "ui.h"
#include "credentials.h"
#include "bme280_idf.h"
#include "bme280_defs.h"
static const char *TAG = "[MAIN]";
/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;
/* The event group allows multiple bits for each event, but we only care about two events:
* - we are connected to the AP with an IP
* - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
#define BL_IO 26
#define I2C_SCL_IO 22 /*!< gpio number for I2C master clock */
#define I2C_SDA_IO 21 /*!< gpio number for I2C master data */
#define I2C_FREQ_HZ 400000 /*!< I2C master clock frequency */
#define I2C_PORT_NUM I2C_NUM_0 /*!< I2C port number for master dev */
#define I2C_TX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define I2C_RX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define BQ27441_I2C_ADDRESS 0x55
static int s_retry_num = 0;
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
if (s_retry_num < 5) {
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(TAG, "retry to connect to the AP");
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(TAG,"connect to the AP fail");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
NetworkData ndata;
ndata.connected = true;
sprintf(ndata.ip_addr,IPSTR,IP2STR(&event->ip_info.ip));
xQueueOverwrite(qNetwork,&ndata);
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void wifi_init_sta(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&event_handler,
NULL,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&event_handler,
NULL,
&instance_got_ip));
wifi_config_t wifi_config = {
.sta = {
.ssid = WIFI_SSID,
.password = <PASSWORD>,
/* Setting a password implies station will connect to all security modes including WEP/WPA.
* However these modes are deprecated and not advisable to be used. Incase your Access point
* doesn't support WPA2, these mode can be enabled by commenting below line */
.threshold.authmode = WIFI_AUTH_WPA2_PSK,
.pmf_cfg = {
.capable = true,
.required = false
},
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK(esp_wifi_start() );
ESP_LOGI(TAG, "wifi_init_sta finished.");
/* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
* number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
WIFI_SSID, WIFI_PASS);
} else if (bits & WIFI_FAIL_BIT) {
ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
WIFI_SSID, WIFI_PASS);
} else {
ESP_LOGE(TAG, "UNEXPECTED EVENT");
}
/* The event will not be processed after unregister */
ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
vEventGroupDelete(s_wifi_event_group);
}
static void i2c_master_init(void)
{
i2c_config_t conf = {};
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = (gpio_num_t)I2C_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = (gpio_num_t)I2C_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_FREQ_HZ;
i2c_param_config(I2C_PORT_NUM, &conf);
ESP_ERROR_CHECK(i2c_driver_install(I2C_PORT_NUM, conf.mode, I2C_RX_BUF_DISABLE, I2C_TX_BUF_DISABLE, 0));
i2c_set_timeout(I2C_PORT_NUM,0xFFFFF);
}
void app_main()
{
ESP_LOGI(TAG,"esp32_enviromonitor Main Started");
i2c_master_init();
vTaskDelay(100/portTICK_PERIOD_MS);
// Init BME280
ESP_ERROR_CHECK(bme280_begin(I2C_PORT_NUM,0x77));
gpio_num_t bl_pin = (gpio_num_t)BL_IO;
gpio_pad_select_gpio(bl_pin);
gpio_set_direction(bl_pin, GPIO_MODE_OUTPUT);
gpio_set_level(bl_pin,1);
//Initialize the TFT
init_tft();
// Start the UI task
TaskHandle_t uiHandle = NULL;
xTaskCreate(ui_task,"UI", UI_STACK_SIZE,NULL,tskIDLE_PRIORITY, &uiHandle);
vTaskDelay(100/portTICK_PERIOD_MS);
NetworkData ndata = {};
ndata.connected = false;
xQueueOverwrite(qNetwork,&ndata);
//Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
wifi_init_sta();
while (1) {
vTaskDelay(100/portTICK_PERIOD_MS);
SensorData data;
struct bme280_data comp_data;
bme280_get_forced_data(&comp_data);
data.enviro.temp = comp_data.temperature;
data.enviro.press = 0.01 * comp_data.pressure;
data.enviro.humid = comp_data.humidity;
xQueueOverwrite(qSensor,&data);
}
}
<file_sep>#include "ui.h"
uint8_t currScreen = 2;
QueueHandle_t qButton;
QueueHandle_t qSensor;
QueueHandle_t qNetwork;
static const char *TAG ="[UI]";
void ui_task(void *pvParameters)
{
qButton = xQueueCreate(1,sizeof(uint8_t));
qSensor = xQueueCreate(1,sizeof(SensorData));
qNetwork = xQueueCreate(1,sizeof(NetworkData));
if(qButton == NULL)
ESP_LOGE(TAG,"Error creating the button queue");
draw_header_background();
draw_header();
draw_body_background();
while(1)
{
vTaskDelay(200/portTICK_PERIOD_MS);
draw_screen();
}
}
void draw_screen()
{
SensorData data;
if(pdTRUE == xQueueReceive(qSensor,&data,0))
{
tft_font_transparent = 0;
TFT_setclipwin(5,HEADER_HEIGHT+1,TFT_WIDTH,TFT_HEIGHT);
tft_bg = TFT_DARKGREY;
tft_fg = TFT_WHITE;
char buf[50];
// Print Sesnor Data
sprintf(buf,"%.2f deg C %.2f%% RH",data.enviro.temp,data.enviro.humid);
TFT_print(buf,0,15);
}
NetworkData ndata;
if(pdTRUE == xQueueReceive(qNetwork,&ndata,0))
{
tft_font_transparent = 0;
TFT_setclipwin(5,HEADER_HEIGHT+1,TFT_WIDTH,TFT_HEIGHT);
tft_bg = TFT_DARKGREY;
tft_fg = TFT_WHITE;
TFT_fillWindow(tft_bg);
char buf[100];
// Print Sesnor Data
if(ndata.connected)
{
sprintf(buf,"WIFI %s",ndata.ip_addr);
}
else
{
sprintf(buf,"No WIFI");
}
TFT_print(buf,0,30);
}
}
void draw_header_background()
{
TFT_setclipwin(0,0,TFT_WIDTH,HEADER_HEIGHT);
tft_bg = TFT_LIGHTGREY;
TFT_fillWindow(tft_bg);
}
void draw_body_background()
{
TFT_setclipwin(0,HEADER_HEIGHT+1,TFT_WIDTH,TFT_HEIGHT);
tft_bg = TFT_DARKGREY;
TFT_fillWindow(tft_bg);
}
void draw_header()
{
TFT_setclipwin(0,0,TFT_WIDTH,HEADER_HEIGHT);
tft_fg = TFT_BLACK;
TFT_print("esp32_enviromonitor v0.01",CENTER,CENTER);
}
void init_tft()
{
esp_err_t ret;
TFT_PinsInit();
spi_lobo_device_handle_t spi;
spi_lobo_bus_config_t buscfg = {};
buscfg.mosi_io_num=PIN_NUM_MOSI;
buscfg.miso_io_num=PIN_NUM_MISO;
buscfg.sclk_io_num=PIN_NUM_CLK;
buscfg.quadwp_io_num=-1;
buscfg.quadhd_io_num=-1;
buscfg.max_transfer_sz = 6*1024;
spi_lobo_device_interface_config_t devcfg = {};
devcfg.clock_speed_hz=40000000; // Initial clock out at 40MHz
devcfg.mode=0; // SPI mode 0
devcfg.spics_io_num=-1; // we will use external CS pin
devcfg.spics_ext_io_num=PIN_NUM_CS; // external CS pin
devcfg.flags=LB_SPI_DEVICE_HALFDUPLEX; // ALWAYS SET to HALF DUPLEX MODE!! for display spi
ESP_LOGI(TAG,"Pins used: miso=%d, mosi=%d, sck=%d, cs=%d", PIN_NUM_MISO, PIN_NUM_MOSI, PIN_NUM_CLK, PIN_NUM_CS);
// ==== Initialize the SPI bus and attach the LCD to the SPI bus ====
ret=spi_lobo_bus_add_device(SPI_BUS, &buscfg, &devcfg, &spi);
if(ret != ESP_OK)
ESP_LOGE(TAG, "Failed to attach TFT to SPI bus");
else
ESP_LOGI(TAG,"SPI: display device added to spi bus (%d)", SPI_BUS);
tft_disp_spi = spi;
// ==== Test select/deselect ====
ret = spi_lobo_device_select(spi, 1);
if(ret != ESP_OK)
ESP_LOGE(TAG, "Failed to select TFT");
assert(ret==ESP_OK);
ret = spi_lobo_device_deselect(spi);
if(ret != ESP_OK)
ESP_LOGE(TAG, "Failed to deselect TFT");
assert(ret==ESP_OK);
ESP_LOGI(TAG,"SPI: attached display device, speed=%u", spi_lobo_get_speed(spi));
ESP_LOGI(TAG,"SPI: bus uses native pins: %s", spi_lobo_uses_native_pins(spi) ? "true" : "false");
TFT_display_init();
ESP_LOGI(TAG,"TFT init completed");
TFT_invertDisplay(1);
TFT_setGammaCurve(DEFAULT_GAMMA_CURVE);
tft_font_transparent = 0;
tft_bg = TFT_DARKGREY;
tft_fg = TFT_LIGHTGREY;
TFT_setRotation(LANDSCAPE_FLIP);
TFT_setFont(UBUNTU16_FONT, NULL);
TFT_resetclipwin();
}
<file_sep>cmake_minimum_required(VERSION 3.5)
set(srcs "main.c" "ui.c")
idf_component_register(SRCS "${srcs}"
REQUIRES tft nvs_flash spidriver esp-idf-bme280)
target_compile_options(${COMPONENT_LIB} PRIVATE )
|
143047c5a1e3842bae5ed7b377cc8ff92c586da5
|
[
"C",
"CMake"
] | 4
|
C
|
JMare/esp32_enviromonitor
|
a4d172a38c6351152c55f70bdf8e0c2e7b4572a1
|
c30af937d54623df196c512b89d3dd75ef7142e4
|
refs/heads/develop
|
<repo_name>shota-tsuji/experiment<file_sep>/resource_resolver/resolve.py
#!/usr/bin/python
import sys
import json
import copy
from pprint import pprint
class TemplateEngine:
_val = {}
def __init__(self, template):
for k, v in template["variables"].items():
self._val[k] = v
print json.dumps(self._resolve(template["resources"]))
def _resolve(self, param):
sys.stderr.write("[_resolve] %s\n" % param)
param = copy.deepcopy(param)
if type(param) is dict:
for k, v in param.items():
param[k] = self._resolve(v)
elif type(param) is list:
if param[0] == "ref":
if param[1] not in self._val.keys():
self._make_val(param[1])
param = self._val[param[1]]
else:
for i in range(len(param)):
param[i] = self._resolve(param[i])
return param
def _make_val(self, name):
sys.stderr.write("[_make_val] %s\n" % name)
self._val[name] = "new resource"
if __name__ == "__main__":
template = None
with open("res.json", "r") as f:
template = json.loads(f.read())
te = TemplateEngine(template)
#print template
<file_sep>/va_arg/Makefile
CC = gcc
CFLAGS = -m32 -g -Wall -O0 -fno-stack-protector
INCLUDE = -I./
all:
mkdir -p bin
$(CC) $(CFLAGS) $(INCLUDE) -c -o bin/stdlibc.o stdlibc.c
$(CC) $(CFLAGS) $(INCLUDE )-o bin/test main.c bin/stdlibc.o
run: all
bin/test
clean:
rm -rf bin/
<file_sep>/slstm/include/easy_stack.hpp
#include <cstdio>
namespace easy_stack{
class error{};
template <typename T>
class stack{
private:
T *_bottom;
T *_sp;
std::uint16_t _max_size;
std::uint16_t _size;
stack<T>(const stack<T> &src){};
stack<T> &operator=(const stack<T> &src){};
public:
stack<T>(std::uint16_t stack_size){
_max_size = stack_size;
_size = 0;
_bottom = new T[_max_size]();
_sp = _bottom;
}
~stack(){
delete _bottom;
}
bool push(T data){
if(_size >= _max_size) return false;
*_sp = data;
_sp++;
_size++;
return true;
}
bool pop(){
if(_size == 0) return false;
_sp--;
_size--;
return false;
}
T top(){
if(_size <= 0){
error e;
throw e;
}
return *(_sp - 1);
}
T *sp(){
return(_sp);
}
void sp(uint16_t p){
_sp = _bottom + p;
_size = p;
}
T* bottom(){
return(_bottom);
};
T offset(){
return(_sp - _bottom);
}
void _dump(){
T *p = _sp - 1;
fprintf(stderr, "|");
while(p >= _bottom){
fprintf(stderr, " 0x%.02X", *p);
p--;
}
fprintf(stderr, " |\n");
}
};
}
<file_sep>/va_arg/main.c
#include<stdio.h>
#include "stdlibc.h"
int return_arg_1(void *dummy, ...);
double return_arg_2(void *dummy, ...);
char return_arg_3(void *dummy, ...);
int return_arg_4(void *dummy, ...);
int main(void){
char buf[64] = {0};
printf("[int] %d\n", return_arg_1(NULL, (int)1, (double)2.1, (char)'a', (int)0x12));
printf("[double] %lf\n", return_arg_2(NULL, (int)1, (double)2.1, (char)'a', (int)0x12));
printf("[char] %c\n", return_arg_3(NULL, (int)1, (double)2.1, (char)'a', (int)0x12));
printf("[int] 0x%x\n", return_arg_4(NULL, (int)1, (double)2.1, (char)'a', (int)0x12));
_sprintf(buf, "%d %d %c %x", (int)1, (int)2, (char)'c', (int)0x12);
printf("%s\n", buf);
return 0;
}
int return_arg_1(void *dummy, ...){
my_va_list arg;
my_va_start(arg, dummy);
return my_va_arg(arg, int);
}
double return_arg_2(void *dummy, ...){
my_va_list arg;
my_va_start(arg, dummy);
my_va_arg(arg, int);
return my_va_arg(arg, double);
}
char return_arg_3(void *dummy, ...){
my_va_list arg;
my_va_start(arg, dummy);
my_va_arg(arg, int);
my_va_arg(arg, double);
return my_va_arg(arg, char);
}
int return_arg_4(void *dummy, ...){
my_va_list arg;
my_va_start(arg, dummy);
my_va_arg(arg, int);
my_va_arg(arg, double);
my_va_arg(arg, char);
return my_va_arg(arg, int);
}
<file_sep>/slstm/src/slstm.cpp
#include <cstdio>
#include <cstdint>
#include <unistd.h>
#include <unordered_map>
#include "easy_stack.hpp"
#include "word.hpp"
#define BUF_SIZE 256
#define STACK_SIZE 256
easy_stack::stack<DATA_TYPE> st(STACK_SIZE);
void push(DATA_TYPE n){
st.push(n);
}
DATA_TYPE pop(){
int n = st.top();
st.pop();
return n;
}
void add(){
int n1 = pop();
int n2 = pop();
push(n1 + n2);
}
void sub(){
int n1 = pop();
int n2 = pop();
push(n2 - n1);
}
void mul(){
int n1 = pop();
int n2 = pop();
push(n2 * n1);
}
void gt(){
int n1 = pop();
int n2 = pop();
push(n1 < n2);
}
void lt(){
int n1 = pop();
int n2 = pop();
push(n1 > n2);
}
int main(void){
std::unordered_map<DATA_TYPE, std::uint16_t> label;
std::unordered_map<DATA_TYPE, std::uint16_t> func;
std::uint16_t buf[BUF_SIZE] = {0};
read(0, buf, BUF_SIZE);
slbin_header *header = (slbin_header *)buf;
Word *phead = (Word *)(header + 1);
uint16_t pc = 0;
Word *p = phead + pc;
uint16_t bp = 0;
DATA_TYPE ret;
uint16_t length = header->size / sizeof(Word);
while(pc <= length){
p = phead + pc;
if(p->op == INS_LABEL){
label[p->arg] = pc;
}
else if(p->op == INS_ENTRY){
func[p->arg] = pc;
}
pc++;
}
fprintf(stderr, "----------[debug info]----------\n");
fprintf(stderr, "word length(bytes) : %ld\n", sizeof(Word));
fprintf(stderr, "program length(bytes) : %d\n", header->size);
fprintf(stderr, "program length(steps) : %d\n", length);
fprintf(stderr, "\n");
for(auto itr = label.begin(); itr != label.end(); itr++){
fprintf(stderr, "[label : address] 0x%04X : 0x%04X\n", itr->first, itr->second);
}
for(auto itr = func.begin(); itr != func.end(); itr++){
fprintf(stderr, "[func : address] 0x%04X : 0x%04X\n", itr->first, itr->second);
}
fprintf(stderr, "--------------------------------\n");
pc = 0;
p = phead + pc;
while(pc <= length){
p = phead + pc;
fprintf(stderr, "pc=0x%04X, ", pc);
fprintf(stderr, "bp=0x%04X ", bp);
switch(p->op){
case INS_PUSH:
fprintf(stderr, "(PUSH 0x%.2X) ", p->arg);
push(p->arg);
st._dump();
break;
case INS_POP:
fprintf(stderr, "(POP) ");
pop();
st._dump();
break;
case INS_ADD:
fprintf(stderr, "(ADD) ");
add();
st._dump();
break;
case INS_SUB:
fprintf(stderr, "(SUB) ");
sub();
st._dump();
break;
case INS_MUL:
fprintf(stderr, "(MUL) ");
mul();
st._dump();
break;
case INS_GT:
fprintf(stderr, "(GT) ");
gt();
st._dump();
break;
case INS_LT:
fprintf(stderr, "(LT) ");
lt();
st._dump();
break;
case INS_JMP:
fprintf(stderr, "(JMP 0x%.2X) ", p->arg);
pc = label[p->arg];
st._dump();
continue;
break;
case INS_BEQ0:
fprintf(stderr, "(BEQ0 0x%.2X) ", p->arg);
if(pop() == 0){
pc = label[p->arg];
st._dump();
continue;
}
st._dump();
break;
case INS_ENTRY:
bp = st.offset();
fprintf(stderr, "(ENTRY 0x%.2X, bp=%04d)\n", p->arg, bp);
break;
case INS_FRAME:
if ((p - 1)->op != INS_ENTRY){
fprintf(stderr, "ERROR! INS_FRAME must be used first of functions.\n");
exit(-1);
}
fprintf(stderr, "(FRAME 0x%.2X) ", p->arg);
for(int i = 0; i < p->arg; i++){
push(0x00);
}
st._dump();
break;
case INS_STOREL:
fprintf(stderr, "(STOREL 0x%.2X) ", p->arg);
*(st.bottom() + bp + p->arg) = st.top();
st._dump();
break;
case INS_LOADL:
fprintf(stderr, "(LOADL 0x%.2X) ", p->arg);
push(*(st.bottom() + bp + p->arg));
st._dump();
break;
case INS_CALL:
fprintf(stderr, "(CALL 0x%.2X) ", p->arg);
push(pc);
push(bp);
pc = func[p->arg];
bp = st.offset();
st._dump();
continue;
break;
case INS_RET:
fprintf(stderr, "(RET 0x%.2X) ", p->arg);
ret = st.top();
st.sp(bp);
bp = pop();
pc = pop();
push(ret);
st._dump();
break;
case INS_LOADA:
fprintf(stderr, "(LOADA 0x%.2X) ", p->arg);
push(*(st.bottom() + bp - (p->arg) - 3));
st._dump();
break;
case INS_STOREA:
fprintf(stderr, "(STOREA 0x%.2X) ", p->arg);
*(st.bottom() + bp - (p->arg) - 3) = pop();
st._dump();
break;
case INS_POPR:
fprintf(stderr, "(POPR 0x%.2X) ", p->arg);
ret = pop();
for(int i = 0; i < p->arg; i++){
pop();
}
push(ret);
st._dump();
break;
case INS_PRINT:
fprintf(stderr, "(PRINT 0x%.2X)\n", st.top());
printf("0x%.2X\n", st.top());
break;
case INS_END:
fprintf(stderr, "(END)\n");
goto end;
default:
fprintf(stderr, "\n");
break;
}
pc++;
}
end:
return(0);
}
<file_sep>/slstm/README.md
# SLSTM (Slacia Stack Machine)
This is toy stack machine for my study.
## build & run
```
make run
```
<file_sep>/rust-exam/dining_philosophers/Cargo.toml
[package]
name = "dining_philosophers"
version = "0.1.0"
authors = ["kamaboko123 <<EMAIL>>"]
[dependencies]
<file_sep>/va_arg/stdlibc.h
#ifndef STDLIBC_H
#define STDLIBC_H
#include <stdarg.h>
#include "my_arg.h"
#define TRUE 1
#define FALSE 0
//stdlib.c
void _sprintf(char *s, char *format, ...);
unsigned int _to_dec_asc(char *buf, int n);
unsigned int _to_dec_asc_sign(char *buf, int n);
unsigned int _to_hex_asc(char *buf, int n, int capital);
unsigned int _ndigit(unsigned int n, unsigned int base);
unsigned int _upow(unsigned int x, unsigned int n);
void _upcase(char *str, unsigned int n);
int _iscapital(char c);
int _atoi(char *s);
int _isdigit(char c);
char *_memcpy(char *buf1, char *buf2, int n);
int _memset(char *buf, char byte, int n);
#endif
<file_sep>/rust-exam/linkc/Cargo.toml
[package]
name = "linkc"
version = "0.1.0"
authors = ["kamaboko123 <<EMAIL>>"]
links = "hello"
build = "build.rs"
[dependencies]
libc = "0.2"
[build-dependencies]
gcc = "0.3"
<file_sep>/slstm/src/compiler.cpp
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unordered_map>
#define SYMBOLS_MAX 128
enum code{
SYM,
NUM,
PLUS,
MINUS
};
typedef struct Ast{
enum code op;
int val;
struct Symbol *sym;
struct Ast *l, *r;
} Ast;
typedef struct Symbol {
char name[16];
int val;
Ast *func_params;
Ast *func_body;
} Symbol;
Symbol sym_tbl[SYMBOLS_MAX];
uint16_t sym_tbl_size = 0;
Ast *make_ast(code op, Ast *l, Ast *r){
Ast *p;
p = (Ast *)malloc(sizeof(Ast));
p->op = op;
p->r = r;
p->l = l;
return p;
}
Ast *make_num(int val){
Ast *p;
p = (Ast *)malloc(sizeof(Ast));
p->op = NUM;
p->val = val;
return p;
}
Symbol *find_sym(const char *name){
Symbol *sp = nullptr;
for(int i = 0; i < SYMBOLS_MAX; i++){
if(strcmp(sym_tbl[i].name, name) == 0){
sp = &sym_tbl[i];
break;
}
}
if(sp == nullptr){
sp = &sym_tbl[sym_tbl_size++];
strncpy(sp->name, name, sizeof(sp->name));
}
return sp;
}
Ast *make_sym(const char *name){
Ast *p;
p = (Ast *)malloc(sizeof(Ast));
p->op = SYM;
p->sym = find_sym(name);
return p;
}
Symbol *get_sym(Ast *p){
if(p->op != SYM){
fprintf(stderr, "bad access to symbol.\n");
exit(-1);
}
return p->sym;
}
int main(void){
return 0;
}
<file_sep>/rust-exam/linkc/build.rs
extern crate gcc;
fn main(){
gcc::Config::new()
.file("src/c/hello.c")
.include("src")
.compile("libhello.a");
}
<file_sep>/va_arg/stdlibc.c
#include <stdio.h>
#include "stdlibc.h"
void _sprintf(char *s, char *format, ...){
my_va_list args;
char disp_digit;
int pad_flg;
unsigned int conv_len;
char tmp[16];
int i;
int data_int;
char pad_char;
my_va_start(args, format);
while(*format != '\0'){
pad_flg = FALSE;
conv_len = 0;
if(*format == '%'){
format++;
if(*format == 'c'){
format++;
*s = my_va_arg(args, char);
s++;
continue;
}
_memset(tmp, '\0', sizeof(tmp));
if(*format == '\0') break;
else if(*format == '%'){
*s = '%';
s++;
goto next;
}
else if(_isdigit(*format)){
pad_flg = TRUE;
if(*format == '0'){
pad_char = '0';
}
else{
pad_char = ' ';
}
disp_digit = _atoi(format);
while(_isdigit(*format)) format++;
}
if(*format == 'd'){
data_int = my_va_arg(args, int);
//printf("!%d!", data_int);
if((data_int & 0x8000) != 0){
if(pad_char == ' '){
*tmp = '-';
conv_len = _to_dec_asc(tmp + 1, ~data_int + 1) + 1;
}
else if(pad_char == '0'){
*s = '-';
s++;
conv_len = _to_dec_asc(tmp, ~data_int + 1);
disp_digit--;
}
}
else{
conv_len = _to_dec_asc(tmp, data_int);
}
}
if(*format == 'x'){
conv_len = _to_hex_asc(tmp, my_va_arg(args, int), FALSE);
}
if(*format == 'X'){
conv_len = _to_hex_asc(tmp, my_va_arg(args, int), TRUE);
}
if(pad_flg && (conv_len < disp_digit)){
for(i = conv_len; i < disp_digit; i++){
*s = pad_char;
s++;
}
}
_memcpy(s, tmp, conv_len);
s += conv_len;
}
else{
*s = *format;
s++;
}
next:
format++;
}
*s = *format;
//my_va_end(args);
}
unsigned int _to_dec_asc(char *buf, int n){
char *p;
unsigned int ret;
unsigned int i;
i = _ndigit(n, 10);
ret = i;
p = buf;
while(i > 0){
*p = ((n / _upow(10, i - 1)) % 10) + '0';
p++;
i--;
}
return(ret);
}
unsigned int _to_hex_asc(char *buf, int n, int capital){
char *p;
unsigned int ret;
unsigned int i;
char charset[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
i = _ndigit(n, 16);
ret = i;
p = buf;
while(i > 0){
*p = charset[((n / _upow(16, i - 1)) % 16)];
if(capital && !_isdigit(*p)){
*p -= 0x20;
}
p++;
i--;
}
return(ret);
}
unsigned int _ndigit(unsigned int n, unsigned int base){
unsigned int i = 1;
while(n >= base){
n /= base;
i++;
}
return(i);
}
unsigned int _upow(unsigned int x, unsigned int n){
if(n == 0) return(1);
if(n == 1) return(x);
return(x * _upow(x, n-1));
}
int _isdigit(char c){
return((c >= '0' && c <= '9'));
}
int _atoi(char *s){
int result = 0;
int sign = FALSE;
//符号付き
if(*s == '-'){
sign = TRUE;
s++;
}
while(_isdigit(*s)){
//すでに入ってるものを桁上げ + その桁の数値を加算
result = (result * 10) + (*s - '0');
s++;
}
if (sign) result *= -1;
return result;
}
int _iscapital(char c){
return((c >= 'A' && c <= 'Z'));
}
char *_memcpy(char *buf1, char *buf2, int n){
int i;
for(i = 0; i < n; i++){
buf1[i] = buf2[i];
}
return buf1;
}
int _memset(char *buf, char byte, int n){
int i;
for(i = 0; i < n; i++){
buf[i] = byte;
}
return(n);
}
<file_sep>/rust-exam/linkc/src/main.rs
#[link(name="hello", kind="static")]
extern{
fn hello();
}
fn main() {
unsafe {
hello();
};
}
<file_sep>/pyjq_test/jq.py
#!/usr/bin/python
import sys
import pyjq
import json
if __name__ == "__main__":
json_data = None
json_file = sys.argv[1]
with open(json_file, "r") as f:
json_data = json.loads(f.read())
print pyjq.all('.users[] | select (.data.age == 27) | .name', json_data)
print json.dumps(pyjq.all('.users[] | select (.data.age == 27 and .name=="Seri") | .name', json_data))
<file_sep>/slstm/Makefile
CC = g++
CFLAGS = -std=c++11 -Wall -g -O0
INCLUDE = -I ./include
SRC_DIR = ./src
SRC = $(wildcard $(SRC_DIR)/*.cpp)
TARGET_DIR = ./bin
all: stm test_bin compiler
run: stm test_bin
$(TARGET_DIR)/stm < $(TARGET_DIR)/stmbin.o
stm: $(SRC)
mkdir -p $(TARGET_DIR)
$(CC) $(CFLAGS) $(INCLUDE) -o $(TARGET_DIR)/stm $(SRC_DIR)/slstm.cpp
test_bin: $(SRC)
mkdir -p $(TARGET_DIR)
$(CC) $(CFLAGS) $(INCLUDE) -o $(TARGET_DIR)/test_bin_gen $(SRC_DIR)/test_bin_gen.cpp
rm -f $(TARGET_DIR)/stmbin.o
$(TARGET_DIR)/test_bin_gen $(TARGET_DIR)/stmbin.o
compiler: $(SRC)
mkdir -p $(TARGET_DIR)
$(CC) $(CFLAGS) $(INCLUDE) -o $(TARGET_DIR)/compiler $(SRC_DIR)/compiler.cpp
clean:
rm -rf $(TARGET_DIR)
<file_sep>/slstm/include/word.hpp
#ifndef INCLUED_SLSTM_WORD
#define INCLUED_SLSTM_WORD
#define INS_DUM 0x00
#define INS_PUSH 0x01
#define INS_POP 0x02
#define INS_ADD 0x03
#define INS_SUB 0x04
#define INS_MUL 0x05
#define INS_GT 0x06
#define INS_LT 0x07
#define INS_JMP 0x08
#define INS_LABEL 0x09
#define INS_BEQ0 0x0A
#define INS_ENTRY 0x0B
#define INS_FRAME 0x0C
#define INS_LOADL 0x0D
#define INS_STOREL 0x0E
#define INS_CALL 0x0F
#define INS_RET 0x10
#define INS_LOADA 0x11
#define INS_STOREA 0x12
#define INS_POPR 0x13
#define INS_PRINT 0x14
#define INS_END 0xFE
typedef uint16_t DATA_TYPE;
typedef struct Word{
uint8_t op;
DATA_TYPE arg;
} Word;
typedef struct slbin_header{
uint16_t size;
} slbin_header;
#endif
<file_sep>/ovsdb/ovs-client.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#OVSDB Manipulation library for Python
import socket
import json
import ipaddress
import uuid
from pprint import pprint
RCV_BUF = 8192
class OvsdbClient:
_ovsdb_ip = None
_ovsdb_port = None
_transact_id = 0
def __init__(self, ovsdb_port, ovsdb_ip="127.0.0.1"):
self._ovsdb_ip = ipaddress.ip_address(unicode(ovsdb_ip))
self._ovsdb_port = int(ovsdb_port)
def _send(self, query):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((str(self._ovsdb_ip), self._ovsdb_port))
s.send(json.dumps(query))
response = s.recv(8192)
return json.loads(response)
def get_ports(self):
query = {
"method":"transact",
"params":[
"Open_vSwitch",
{
"op" : "select",
"table" : "Port",
"where" : [],
}
],
"id":0
}
result = self._send(query)
if "error" not in result.keys() or result["error"] is not None:
raise Exception("なんかのエラー")
return result["result"][0]["rows"]
def get_bridges(self):
query = {
"method":"transact",
"params":[
"Open_vSwitch",
{
"op" : "select",
"table" : "Bridge",
"where" : [],
}
],
"id":0
}
result = self._send(query)
if "error" not in result.keys() or result["error"] is not None:
raise Exception("なんかのエラー")
ret = {}
return result["result"][0]["rows"]
"""
def get_bridge_config(self):
bridges = self.get_bridges()
ports = self.get_ports()
print bridges
print ports
ret = {}
for br in bridges:
ret[br["name"]] = {
"ports" : {}
}
for port_uuid in br["ports"]:
if port_uuid == "set":
continue
ret[br["name"]]["ports"][port_uuid] = ports[port_uuid]
return ret
"""
def get_interfaces(self):
query = {
"method":"transact",
"params":[
"Open_vSwitch",
{
"op" : "select",
"table" : "Interface",
"where" : [],
}
],
"id":0
}
result = self._send(query)
#pprint(result["result"][0]["rows"])
return(result["result"][0]["rows"])
def add_interface(self, bridge_name, interface_name, vlan=None):
for interface in self.get_interfaces():
if interface_name == interface["name"]:
raise Exception("the interface already exisit %s" % interface_name)
if interface["type"] == "internal":
continue
print("%s : %s" % (interface["name"], interface["_uuid"]))
print
target_bridge = None
ports = []
for bridge in self.get_bridges():
print("%s : %s" % (bridge["name"], bridge["_uuid"]))
if bridge_name == bridge["name"]:
target_bridge = bridge["_uuid"][1]
ports.append(bridge["ports"])
#print("!!%s" % bridge["ports"])
if target_bridge is None:
raise Exception("the bridge is not found : %s" % bridge_name)
print target_bridge
interface_tmp_id = "row%s" % str(uuid.uuid4()).replace("-", "_")
port_tmp_id = "row%s" % str(uuid.uuid4()).replace("-", "_")
ports.append(["named-uuid", port_tmp_id])
query = {
"method":"transact",
"params":[
"Open_vSwitch",
{
"uuid-name" : interface_tmp_id,
"op" : "insert",
"table" : "Interface",
"row":{
"name":interface_name,
"type":""
}
},
{
"uuid-name": port_tmp_id,
"op" : "insert",
"table" : "Port",
"row":{
"name" : interface_name,
"interfaces":[
"named-uuid",
interface_tmp_id
]
}
},
{
"where": [
[
"_uuid",
"==",
[
"uuid",
target_bridge
]
]
],
"row": {
"ports": [
"set",
ports
]
},
"op": "update",
"table": "Bridge"
}
],
"id":self._transact_id
}
self._transact_id += 1
if isinstance(vlan, list):
query["params"][2]["row"]["trunks"] = ["set", vlan]
#raise Exception("not supported configure trunk port")
if isinstance(vlan, int):
query["params"][2]["row"]["tag"] = vlan
pprint(query)
result = self._send(query)
pprint(result)
def del_interface(self, bridge_name, interface_name):
target_bridge = None
for br in self.get_bridges():
if br["name"] == bridge_name:
target_bridge = br
if target_bridge is None:
raise Exception("the bridge is not found : %s" % bridge_name)
print target_bridge
target_port = None
for port in self.get_ports():
if port["name"] == interface_name:
target_port = port
if target_port is None:
raise Exception("the interface is not found : %s" % interface_name)
print target_port
find_port = False
br_ports = target_bridge["ports"][1]
for port in br_ports:
if port[1] == target_port["_uuid"][1]:
find_port = True
if not find_port :
raise Exception("interface \"%s\" is not attached to bridge \"%s\"." % (interface_name, bridge_name))
set_port = []
for port in target_bridge["ports"][1]:
if port[1] == target_port["_uuid"][1]:
continue
set_port.append(port)
print set_port
query = {
"method":"transact",
"params":[
"Open_vSwitch",
{
"where": [
[
"_uuid",
"==",
[
"uuid",
target_bridge["_uuid"][1]
]
]
],
"row": {
"ports": [
"set",
set_port
]
},
"op": "update",
"table": "Bridge"
}
],
"id":self._transact_id
}
self._transact_id += 1
pprint(query)
result = self._send(query)
pprint(result)
if __name__ == '__main__':
ovsdb = OvsdbClient(5678)
#ovsdb.get_interface()
#ovsdb.add_interface("ovs-docker", "enp2s0", [100,200])
#ovsdb.add_interface("ovs-docker", "enp4s0")
#ovsdb.del_interface("ovs-docker", "enp4s0")
<file_sep>/README.md
# experiment
experimental codes before development
|
46fa1ef656bb516596889831f880f3a34549c589
|
[
"Markdown",
"TOML",
"Makefile",
"Rust",
"Python",
"C",
"C++"
] | 18
|
Python
|
shota-tsuji/experiment
|
fd086b8ff2f4eaf28373e510e292446d48a52d45
|
dc211d08431c9192e03d6ad745ab138c1921a72f
|
refs/heads/master
|
<file_sep>package bruna.questao5.programa;
import bruna.questao5.classe.Pessoa;
public class Main {
public static void main(String[] args){
try{
Pessoa pessoa = new Pessoa();
pessoa.setEmail("<EMAIL>");
pessoa.setIdade(30);
pessoa.setNome("<NAME>");
System.out.println(String.format("Seu nome: %s \n" + "Sua idade: %d \n" + "Seu email: %s\n",
pessoa.getNome(), pessoa.getIdade(), pessoa.getEmail()));
} catch (Exception e){
e.printStackTrace();
}
}
}
|
f8cf052b4872372a9be0370c51a2af5e8ab0847e
|
[
"Java"
] | 1
|
Java
|
BrunaBoo93/provac
|
2f06356dc3f2d1d22934db93ac7c0a3aab678430
|
5fa6bde91a7e7b205a31c562690db12e15dac2a8
|
refs/heads/master
|
<file_sep>#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>
#define STASSID "Honda-ASUS"
#define STAPSK "mobydick"
#define INT_MAX 2147483647
#define LATCH D1
#define CLOCK D2
#define DATA D0
#define OE1 D3
#define OE2 D4
#define OE3 D5
#define OE4 D6
#define PUMPS1 D7
#define PUMPS2 D8
byte leds = 0;
bool lightsOn = false;
ESP8266WebServer server(80);
char ptr[] = "<!DOCTYPE html>\n"
"<html lang=\"en\">\n"
"\n"
"<head>\n"
" <meta charset=\"UTF-8\">\n"
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
" <title>Document</title>\n"
"</head>\n"
"\n"
"<body>\n"
" <h1 id=\"displayPin\" style=\"text-align:center;height:30px\"></h1>\n"
" <div>\n"
" <button id=\"toggleLightsButton\" type=\"button\"\n"
" style=\"background-color:green;font-size:1.5em; width:30%;padding:0.5em;\">></button>\n"
" </div>\n"
" <h1 id=\"lightsStatus\" style=\"text-align:center;color:maroon;\">OFF</h4>\n"
"\n"
" <script>\n"
" let toggleLightsButton = document.getElementById(\"toggleLightsButton\");\n"
" let lightsStatus = document.getElementById(\"lightsStatus\");\n"
"\n"
" function toggleLights() {\n"
" let XHR = new XMLHttpRequest();\n"
" XHR.onload = () => {\n"
" console.log(XHR.responseText)\n"
" let body = JSON.parse(XHR.responseText);\n"
"\n"
" if (XHR.status == 200) {\n"
" lightsStatus.innerHTML = body[\"response\"];\n"
" } else {\n"
" lightsStatus.innerHTML = \"Error\";\n"
" }\n"
" }\n"
" XHR.onerror = () => { alert(\"Server Error\") };\n"
" XHR.open(\"GET\", \"http://\" + window.location.hostname + \"/toggleLights\");\n"
" XHR.send();\n"
" }\n"
"\n"
" toggleLightsButton.onclick = toggleLights;\n"
" </script>\n"
"</body>\n"
"\n"
"</html>\n";
void handleRoot() {
server.send(200, "text/html", ptr);
}
void handleNotFound(){
server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
}
void turnLightsON() {
leds = INT_MAX;
updateShiftRegister();
}
void turnLightsOff() {
leds = 0;
updateShiftRegister();
}
void toggleLights() {
if (lightsOn) {
turnLightsOff();
lightsOn = false;
}
else {
turnLightsOn();
lightsOn = true;
}
}
void setup()
{
Serial.begin(9600); // Initiate a serial communication
pinMode(LATCH, OUTPUT);
pinMode(DATA, OUTPUT);
pinMode(CLOCK, OUTPUT);
pinMode(OE1, OUTPUT);
pinMode(OE2, OUTPUT);
pinMode(OE3, OUTPUT);
pinMode(OE4, OUTPUT);
turnLightsOff();
setBrightness(255);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Connect Failed! Rebooting...");
delay(200);
ESP.restart();
}
ArduinoOTA.onStart([]() {
Serial.println("Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
ArduinoOTA.setHostname("hondaesp");
ArduinoOTA.setPassword("<PASSWORD>");
// <-------- API -------->
server.on("/", HTTP_GET, handleRoot);
server.on("/toggleLights", HTTP_GET, toggleLights);
server.onNotFound(handleNotFound);
server.begin();
Serial.print("http://");
Serial.println(WiFi.localIP());
}
void loop()
{
ArduinoOTA.handle();
server.handleClient();
}
void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
void setBrightness(byte brightness) // 0 to 255
{
analogWrite(OE1, 255-brightness);
analogWrite(OE2, 255-brightness);
analogWrite(OE3, 255-brightness);
analogWrite(OE4, 255-brightness);
}
|
7cd7c473a29473233981eba765e7e3e1e83118ba
|
[
"C++"
] | 1
|
C++
|
adambocco/waterfall
|
d02d50462202de00cd7888d99062198885b8efc5
|
5788c6dd7c367f2de614c008641916c7cd12a859
|
refs/heads/master
|
<repo_name>SteveYTan/SiriSays<file_sep>/SiriSays/ViewController.swift
//
// ViewController.swift
// SiriSays
//
// Created by <NAME> on 8/18/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var arrayLanguages = [["English", "en-US"], ["English-Male", "en-GB"], ["Aussie English", "en-AU"],["Arabic", "ar-SA"], ["Dutch", "nl-BE"], ["Greek", "el-GR"],["Chinese", "cs-CZ"], ["French", "fr-CA"],["Hebrew", "he-IL"],["Spanish", "es-ES"], ["German", "de-DE"], ["Hindi", "hi-IN"], ["Italian", "it-IT"], ["Japanese", "ja-JP"], ["Korean", "ko-KR"], ["Polish", "pl-PL"], ["Russian", "ru-RU"], ["Thai", "th-TH"], ["Turkish", "tr-TR"]]
//var arrayLanguages = ["English", "French", "Swift","Javo","IT", "Should","Scroll"]
var library = Phrase.all()
var currentlanguage = "en-US"
@IBOutlet weak var libraryButton: UIButton!
@IBOutlet weak var randomButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var customText: UITextField!
@IBAction func readButton(_ sender: UIButton) {
if customText.text! != ""
{
let string = customText.text!
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: currentlanguage)
utterance.rate = 0.1
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
view.endEditing(true)
}
}
@IBAction func saveButton(_ sender: UIButton) {
if customText.text! != ""
{
let phrase = Phrase(obj: customText.text!)
phrase.save()
customText.text = ""
view.endEditing(true)
}
}
@IBAction func randomButton(_ sender: UIButton) {
library = Phrase.all()
var x = library.count
x = Int(arc4random_uniform(UInt32(x)))
let string = library[x].objective
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: currentlanguage)
utterance.rate = 0.05
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeue the cell from our storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell")!
// if the cell has a text label, set it to the model that is corresponding to the row in array
cell.textLabel?.text = arrayLanguages[indexPath.row][0]
// return cell so that Table View knows what to draw in each row
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayLanguages.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
currentlanguage = arrayLanguages[indexPath.row][1]
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
randomButton.backgroundColor = UIColor.black
randomButton.layer.cornerRadius = 15
libraryButton.backgroundColor = UIColor.gray
libraryButton.layer.cornerRadius = 15
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/SiriSays/libraryViewController.swift
//
// libraryViewController.swift
// SiriSays
//
// Created by <NAME> on 8/18/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class LibraryViewController: UITableViewController {
var Library: [Phrase] = Phrase.all()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeue the cell from our storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "PhraseCell")!
cell.textLabel?.text = Library[indexPath.row].objective
// return cell so that Table View knows what to draw in each row
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
Library = Phrase.all()
return Library.count
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
Library[indexPath.row].destroy()
Library.remove(at: indexPath.row)
tableView.reloadData()
}
}
<file_sep>/README.md
# SiriSays
IOS app made using Swift 2.0
Uses AVFoundation framework to provide voice
Database is stored in Local Files
Allows you to enter and save messages and have Siri say them in various accents based on AVFoundation's language packages.
<file_sep>/SiriSays/Database.swift
//
// database.swift
// sirisays
//
// Created by Jie on 8/18/15.
// Copyright © 2015 Jie. All rights reserved.
//
import Foundation
class Database {
// get the full path to the Documents folder
static func documentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
return paths[0]
}
// get the full path to file of project
static func dataFilePath(_ schema: String) -> String {
return "\(Database.documentsDirectory())/\(schema)"
}
static func save(_ arrayOfObjects: [AnyObject], toSchema: String, forKey: String) {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(arrayOfObjects, forKey: "\(forKey)")
archiver.finishEncoding()
data.write(toFile: Database.dataFilePath(toSchema), atomically: true)
}
}
class Phrase: NSObject, NSCoding {
static var key: String = "Book"
static var schema: String = "theList"
var objective: String
var createdAt: Date
// use this init for creating a new Task
init(obj: String) {
objective = obj
createdAt = Date()
}
// MARK: - NSCoding protocol
// used for encoding (saving) objects
func encode(with aCoder: NSCoder) {
aCoder.encode(objective, forKey: "objective")
aCoder.encode(createdAt, forKey: "createdAt")
}
// used for decoding (loading) objects
required init?(coder aDecoder: NSCoder) {
objective = aDecoder.decodeObject(forKey: "objective") as! String
createdAt = aDecoder.decodeObject(forKey: "createdAt") as! Date
super.init()
}
// MARK: - Queries
static func all() -> [Phrase] {
var Book = [Phrase]()
let path = Database.dataFilePath("theList")
if FileManager.default.fileExists(atPath: path) {
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
Book = unarchiver.decodeObject(forKey: Phrase.key) as! [Phrase]
unarchiver.finishDecoding()
}
}
return Book
}
func save() {
var BookFromStorage = Phrase.all()
var exists = false
for i in 0 ..< BookFromStorage.count {
if BookFromStorage[i].createdAt == self.createdAt {
BookFromStorage[i] = self
exists = true
}
}
if !exists {
BookFromStorage.append(self)
}
Database.save(BookFromStorage, toSchema: Phrase.schema, forKey: Phrase.key)
}
func destroy() {
var bookFromStorage = Phrase.all()
for i in 0 ..< bookFromStorage.count {
if bookFromStorage[i].createdAt == self.createdAt {
bookFromStorage.remove(at: i)
}
}
Database.save(bookFromStorage, toSchema: Phrase.schema, forKey: Phrase.key)
}
}
<file_sep>/SiriSays/languageClass.swift
//
// languageClass.swift
// SiriSays
//
// Created by <NAME> on 8/18/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
|
3b59a55952e955a7220718703f4303b62e94a369
|
[
"Swift",
"Markdown"
] | 5
|
Swift
|
SteveYTan/SiriSays
|
990f08f7741af48683816640ab9307bd041bcb62
|
c44768a9dffc11f55676a15b4dd8fc1471465c0d
|
refs/heads/master
|
<repo_name>joelryerson/Little-U<file_sep>/Little U/Subview.swift
//
// Subview.swift
// Little U
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
struct Subview: View {
var imageString: String
var body: some View {
Image(imageString)
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFill()
.clipped()
.frame(width: 414, height: 896, alignment: .center)
.edgesIgnoringSafeArea([.all])
}
}
#if DEBUG
struct Subview_Previews: PreviewProvider {
static var previews: some View {
Subview(imageString: "strengthen bonds")
}
}
#endif
<file_sep>/Little U/Home.swift
//
// SwiftUIView.swift
// Little U
//
// Created by <NAME> on 7/25/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
struct SwiftUIView: View {
var body: some View {
VStack {
HStack {
VStack {
Button(action: {
print("Button action")
}) {
HStack {
Image("Search")
.resizable()
.frame(width:15, height:15)
.scaledToFit()
.aspectRatio(contentMode: .fit)
Spacer()
}
.padding()
.foregroundColor(ColorManager.PrimaryColor)
.frame(width:86, height:38)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(ColorManager.PrimaryColor, lineWidth: 5)
)
}
}.padding(.horizontal, 20)
Spacer()
VStack {
Image("Little U")
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFit()
.frame(height:38)
}.padding(.horizontal, 20)
}
//return message
}
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
<file_sep>/Little U/ColorManager.swift
//
// ColorManager.swift
// ESL Reading App
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
// ColorManager.swift created by <NAME>
import SwiftUI
struct ColorManager {
// create static variables for custom colors
static let DarkGray = Color("DarkGray")
static let PrimaryColor = Color("PrimaryColor")
static let MediumGray = Color("MediumGray")
//... add the rest of your colors here
}
<file_sep>/Little U/PageControl.swift
//
// PageControl.swift
// Little U
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import SwiftUI
struct PageControl: UIViewRepresentable {
var numberOfPages: Int
@Binding var currentPageIndex: Int
func makeUIView(context: Context) -> UIPageControl {
let control = UIPageControl()
control.numberOfPages = numberOfPages
control.currentPageIndicatorTintColor = UIColor.init(named: "PrimaryColor")
control.pageIndicatorTintColor = UIColor.init(named: "MediumGray")
return control
}
func updateUIView(_ uiView: UIPageControl, context: Context) {
uiView.currentPage = currentPageIndex
}
}
<file_sep>/Little U/OnboardingView.swift
//
// OnboardingView.swift
// Little U
//
// Created by <NAME> on 7/18/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
struct OnboardingView: View {
var subviews = [
UIHostingController(rootView: Subview(imageString: "onboarding view 1")),
UIHostingController(rootView: Subview(imageString: "onboarding view 2")),
UIHostingController(rootView: Subview(imageString: "onboarding view 3"))
]
var titles = ["Strengthen bonds", "Enrich language", "Spark imagination"]
@State var currentPageIndex = 0
var body: some View {
VStack{
VStack {
Image("Little U")
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFit()
.frame(width: 263, height: 71.23)
.clipped()
Text(titles[currentPageIndex])
.font(.custom("Love Is Complicated Again", size: 30))
.foregroundColor(ColorManager.DarkGray)
}.padding()
Spacer().frame(maxWidth: .infinity)
VStack {
PageControl(numberOfPages: subviews.count, currentPageIndex: $currentPageIndex)
Button(action: {
print("Button action")
}) {
Text("Get Started")
.frame(width: 218, height: 56.5)
.font(.custom("Poppins-SemiBold", size: 18))
.background(ColorManager.PrimaryColor)
.foregroundColor(.white)
.cornerRadius(68.75)
}
Button(action: {
print("Button action")
}) {
Text("Already a member? Log in")
.font(.custom("Poppins-Medium", size: 14))
.foregroundColor(ColorManager.MediumGray)
}.padding()
}
}.background(PageViewController(currentPageIndex: $currentPageIndex, viewControllers: subviews)
.edgesIgnoringSafeArea(.all))
}
}
#if DEBUG
struct OnboardingView_Previews: PreviewProvider {
static var previews: some View {
OnboardingView()
}
}
#endif
|
9d0e86446209149a8c635cdc2f3591e1e9446ed7
|
[
"Swift"
] | 5
|
Swift
|
joelryerson/Little-U
|
b6b4014be237869633696c1d0e8887fa993a14df
|
75b47ba241395538120f43dc79a46b41f64e1b59
|
refs/heads/master
|
<repo_name>nicolascafure/calculadora-avanzada<file_sep>/src/components/Input.js
import React from 'react';
const Input = ({setNumero, numero}) => {
const leerValor=(e)=>{
if(e.target.value ===""||Number(e.target.value)){
setNumero(Number(e.target.value))
}else{
return
}}
const resetValor =()=>{
setNumero(0)
}
return (<>
<input type="text" onInput={leerValor} value={numero} ></input>
<button onClick={resetValor}>Clear</button>
</>
);
}
export default Input;<file_sep>/src/utils/functionList.js
const funcionesCalculadora = [
{ title: "suma", result: 0 },
{ title: "resta", result: 0 },
{ title: "multiplicacion", result: 0 },
{ title: "division", result: 0 },
{ title: "potencia", result: 0 },
{ title: "raiz", result: 0 },
{ title: "hipotenusa", result: 0 },
];
export default funcionesCalculadora<file_sep>/src/components/Operation.js
import React from 'react';
const Operation = ({numeroA,numeroB, operation}) => {
function calculator(a, b, ope) {
Number(a)
Number(b)
const operations = {
suma: (a, b) => (a + b).toFixed(2),
resta: (a, b) => (a - b).toFixed(2),
multiplicacion: (a, b) => (a * b).toFixed(2),
division: (a, b) =>isNaN( a / b) ? 0: (a/b).toFixed(2),
raiz: (a,b) => `Raiz de ${a} = ${Math.sqrt(a).toFixed(2)} | Raiz de ${b} = ${Math.sqrt(b).toFixed(2)} ` ,
potencia: (a,b) => Math.pow(a, b).toFixed(2),
hipotenusa: (a,b) => (Math.hypot(a,b)).toFixed(2)
};
return operations[ope]?.(a, b)
}
return (
<div className="operacion">
<h1 className="titulo-operacion">{operation.charAt(0).toUpperCase() + operation.slice(1)}</h1>
<p className="resultado">{calculator(numeroA,numeroB,operation)}</p>
</div>
);
}
export default Operation;
|
b9ef7c088325fb1d93c949e57f1cb058dc908745
|
[
"JavaScript"
] | 3
|
JavaScript
|
nicolascafure/calculadora-avanzada
|
c0a77a23823cab20ba0b67990f27a57a31f4eb53
|
d68dd086f269f395e3d1ef56b01a43a4ab7237ea
|
refs/heads/master
|
<repo_name>it-academy-pl/KRK-Java-19-09-1-W<file_sep>/src/pl/itacademy/week9/hw/Box.java
package pl.itacademy.week9.hw;
import java.util.ArrayList;
import java.util.List;
public class Box<T> {
private List<T> items = new ArrayList<>();
public void addItem(T item) {
items.add(item);
}
public List<T> getItems() {
return items;
}
}
<file_sep>/src/pl/itacademy/week5/Pet.java
package pl.itacademy.week5;
public abstract class Pet extends Animal{
public Pet(String name, String breed) {
this.name = name;
this.breed = breed;
}
public void eat(String food) {
System.out.println("Im going to eat " + food);
}
protected void makeSound() {
System.out.println("Agrrrrr!");
}
@Override
public void runAway() {
System.out.println("Pet is running away!");
}
}
<file_sep>/src/pl/itacademy/week4/Laptop.java
package pl.itacademy.week4;
public class Laptop {
public final boolean hasDisplay = true;
public static int counter;
public String name;
public int weight;
public boolean isSwitchedOn;
public Laptop() {
System.out.println("New Laptop has been created!");
counter++;
}
public Laptop(int weight) {
this();
this.weight = weight;
}
public Laptop(String name) {
this(2);
this.name = name;
isSwitchedOn = false;
}
public void setName(String newName) {
this.name = newName;
System.out.println("Name has been changed to " + newName);
newName = null;
System.out.println("newName value is " + newName);
}
public static void main(String[] args) {
System.out.println("Created laptops so far: " + counter);
Laptop mac = new Laptop("MacBookPro");
System.out.println("Created laptops so far: " + counter);
Laptop dell = new Laptop ("Dell");
System.out.println("Created laptops so far: " + counter);
Laptop hp = new Laptop ("HP");
System.out.println("Created laptops so far: " + counter);
String acer = "ACER";
System.out.println(acer);
hp.setName(acer);
System.out.println(acer);
final Double pi = 3.1415;
Integer i = 5;
Integer j = new Integer(7);
String text = "Hello world";
text = new String("TEST");
}
}
<file_sep>/src/pl/itacademy/week7/Card.java
package pl.itacademy.week7;
import pl.itacademy.week7.accounts.Account;
import java.math.BigDecimal;
public class Card {
private String pin;
private String cardNumber;
private String bankName;
private long accountNumber;
public Card(String cardNumber, String bankName, long accountNumber) {
this.cardNumber = cardNumber;
this.bankName = bankName;
this.accountNumber = accountNumber;
pin = "0000";
}
public boolean checkPin(String enteredPin) {
return pin.equals(enteredPin);
}
public void changePin(String oldPin, String newPin) {
if (checkPin(oldPin)) {
pin = newPin;
} else {
System.out.println("Entered wrong pin code!");
}
}
public BigDecimal checkBalance() {
Account account = getCardAccount();
if (account != null) {
return account.getBalance();
}
return null;
}
private Account getCardAccount() {
Bank bank = BankRegistrator.getByName(bankName);
if (bank != null) {
return bank.getByNumber(accountNumber);
}
return null;
}
public BigDecimal topUp(BigDecimal amount) {
Account account = getCardAccount();
if(account != null) {
return account.topUp(amount);
}
return null;
}
public BigDecimal withDraw(BigDecimal amount) {
Account account = getCardAccount();
if(account != null) {
return account.withDraw(amount);
}
return null;
}
}
<file_sep>/src/pl/itacademy/week10/ExternalLibrariesTester.java
package pl.itacademy.week10;
import org.apache.commons.lang3.StringUtils;
public class ExternalLibrariesTester {
public static void main(String[] args) {
StringUtils.isEmpty("");
}
}
<file_sep>/src/pl/itacademy/week6/interfaces/Door.java
package pl.itacademy.week6.interfaces;
public class Door {
private String colour;
private String material;
private Size size;
private boolean opened;
private static int numberOfCreatedDoors = 0;
public Door(String colour, String material, Size size) {
this.colour = colour;
this.material = material;
this.size = size;
opened = false;
numberOfCreatedDoors++;
}
public static int getNumberOfCreatedDoors() {
return numberOfCreatedDoors;
}
public void open() {
opened = true;
System.out.println("Door has been opened");
}
public void close() {
opened = false;
System.out.println("Door has been closed");
}
public boolean isOpened() {
return opened;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
}
<file_sep>/src/pl/itacademy/week8/ComparableTester.java
package pl.itacademy.week8;
import java.time.LocalDate;
import java.util.*;
public class ComparableTester {
public static void main(String[] args) {
Person kowalski = new Person("Jan", "Kowalski", LocalDate.of(1970, 1, 1));
Person nowak = new Person("Janusz", "Nowak", LocalDate.of(1980, 6, 15));
//System.out.println(kowalski.compareTo(nowak));
Set<Person> persons = new TreeSet<>();
persons.add(kowalski);
persons.add(nowak);
System.out.println(persons);
Room firstRoom = new Room(10);
Room secondRoom = new Room(15);
Room thirdRoom = new Room(5);
Set<Room> rooms = new TreeSet<>(new RoomComparator());
rooms.add(firstRoom);
rooms.add(secondRoom);
rooms.add(thirdRoom);
System.out.println(rooms);
Map<Room, String> roomMap = new TreeMap<>(Comparator.nullsLast(new RoomComparator()));
roomMap.put(null, "test");
roomMap.put(firstRoom, "Nowak's room");
roomMap.put(secondRoom, "Kowalski's room");
System.out.println(roomMap);
Person sereda = new Person("Oleg", "Sereda", LocalDate.of(1900, 1, 1));
PriorityQueue<Person> goodLoodQueue = new PriorityQueue<>(Comparator.reverseOrder());
goodLoodQueue.add(nowak);
goodLoodQueue.add(kowalski);
goodLoodQueue.add(sereda);
System.out.println(goodLoodQueue);
}
}
<file_sep>/src/pl/itacademy/week9/OurComparator.java
package pl.itacademy.week9;
@FunctionalInterface
public interface OurComparator {
boolean compare(String a, String b);
static void printMessage(String message) {
System.out.println(message);
}
default void printAnotherMessage(String message) {
System.out.println(message);
}
}
<file_sep>/src/pl/itacademy/week5/Cat.java
package pl.itacademy.week5;
public class Cat extends Pet {
public Cat(String name, String breed) {
super(name, breed);
System.out.println("new cat born");
}
@Override
protected void makeSound() {
System.out.println("Meu-Meu");
}
public void catchMouse() {
System.out.println("mouse has been catch!");
}
@Override
public void chaseAnotherAnimal(Animal animal) {
System.out.println("Cat is chasing " + animal.name);
}
}
<file_sep>/src/pl/itacademy/week10/TimeSlot.java
package pl.itacademy.week10;
import java.lang.annotation.*;
@Repeatable(Schedule.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TimeSlot {
String value() default "";
String something() default "";
int number() default 0;
double person() default 0.0;
long test() default 1L;
}
<file_sep>/src/pl/itacademy/week8/WeatherTypes.java
package pl.itacademy.week8;
public enum WeatherTypes {
SMOG, RAIN, SNOW, SUN, WIND
}
<file_sep>/src/pl/itacademy/week7/BankomatTester.java
package pl.itacademy.week7;
import pl.itacademy.week7.accounts.Account;
import pl.itacademy.week7.accounts.CreditAccount;
import pl.itacademy.week7.accounts.DebitAccount;
import java.math.BigDecimal;
public class BankomatTester {
public static void main(String[] args) {
Bank ing = new Bank("ING");
BankRegistrator.registerBank(ing);
Account debitAccount = new DebitAccount();
Account creditAccount = new CreditAccount(BigDecimal.valueOf(1000));
ing.addAccount(debitAccount);
ing.addAccount(creditAccount);
System.out.println(debitAccount.getAccountNumber());
System.out.println(creditAccount.getAccountNumber());
Card debitCard = new Card("123", ing.getName(), debitAccount.getAccountNumber());
Card creditCard = new Card("234", ing.getName(), creditAccount.getAccountNumber());
//create accounts
//create banks
//create cards. put account numbers into cards
//put bank names into cards
//register accounts in banks
//register banks in bank registrator
//
//create different ATMs (bankomat, wplatomat, bankomat+wplatomat)
// try to top-up, withdraw different cards with different bankomats
}
}
<file_sep>/src/pl/itacademy/week9/hw/GenericShelf.java
package pl.itacademy.week9.hw;
import java.util.ArrayList;
import java.util.List;
public class GenericShelf {
private List<Box<?>> boxes = new ArrayList<>();
public void addBox(Box<?> box) {
boxes.add(box);
}
public List<Box<?>> getBoxes() {
return boxes;
}
}
<file_sep>/src/pl/itacademy/week10/hw/AnnotatedClass.java
package pl.itacademy.week10.hw;
public class AnnotatedClass {
@Execute(times = 3)
public void firstMethod() {
System.out.println("Execution of the first method");
}
public void secondMethod(String text) {
System.out.println("Execution of second method with text " + text);
}
@Execute(times = 5)
public void thirdMethod(String text, Integer number) {
System.out.println("Execution of third method with text " + text + " and number " + number);
}
}
<file_sep>/src/pl/itacademy/week7/atms/BankomatATM.java
package pl.itacademy.week7.atms;
import java.math.BigDecimal;
public class BankomatATM extends AbstractATM implements Bankomat {
@Override
public BigDecimal withDraw(BigDecimal amount) {
return null;
}
}
<file_sep>/src/pl/itacademy/week10/Lesson.java
package pl.itacademy.week10;
@TimeSlot(value = "today", something = "test")
@TimeSlot(something = "tomorrow")
@TimeSlot("anytime")
//@Schedule({@TimeSlot("today"),
// @TimeSlot("tomorrow")})
public class Lesson {
}
<file_sep>/src/pl/itacademy/week7/atms/WplatomatATM.java
package pl.itacademy.week7.atms;
import java.math.BigDecimal;
public class WplatomatATM extends AbstractATM implements Wplatomat {
@Override
public BigDecimal topUp(BigDecimal amount) {
return null;
}
}
<file_sep>/src/pl/itacademy/week8/FunctionalityTester.java
package pl.itacademy.week8;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.function.Predicate;
public class FunctionalityTester {
public static void main(String[] args) {
Person kowalski = new Person("Jan", "Kowalski", LocalDate.of(1990, 1, 1));
PersonTester ageMoreThan18Tester = new PersonTester() {
@Override
public boolean testPerson(Person person) {
return LocalDate.now()
.minus(18, ChronoUnit.YEARS)
.isAfter(person.getBirthDay());
}
};
// PersonTester ageLessThan65years = new PersonTester() {
// @Override
// public boolean testPerson(Person person) {
// return LocalDate.now()
// .minus(65, ChronoUnit.YEARS)
// .isBefore(person.getBirthDay());
// }
// };
System.out.println(checkPerson(kowalski, new PersonTester() {
@Override
public boolean testPerson(Person person) {
return LocalDate.now()
.minus(18, ChronoUnit.YEARS)
.isAfter(person.getBirthDay());
}
}));
// System.out.println(checkPerson(kowalski, ageLessThan65years));
System.out.println(checkPerson(kowalski, new PersonTester() {
@Override
public boolean testPerson(Person person) {
return LocalDate.now()
.minus(65, ChronoUnit.YEARS)
.isBefore(person.getBirthDay());
}
}));
System.out.println(checkPerson(kowalski, new PersonTester() {
@Override
public boolean testPerson(Person person) {
return "Kowalski".equals(person.getLastName());
}
}));
System.out.println(checkPerson(kowalski, (Person person) -> {
return "Kowalski".equals(person.getLastName());
}));
System.out.println(checkPerson(kowalski, (Person person) -> "Kowalski".equals(person.getLastName())));
System.out.println(checkPerson(kowalski, (person) -> "Kowalski".equals(person.getLastName())));
System.out.println(checkPerson(kowalski, person -> "Kowalski".equals(person.getLastName())));
System.out.println(checkPerson(kowalski, person -> "Nowak".equals(person.getLastName())));
System.out.println(checkPerson(kowalski, person -> LocalDate.now().minus(65, ChronoUnit.YEARS).isBefore(person.getBirthDay())));
System.out.println(checkPerson(kowalski, person -> LocalDate.now().minus(18, ChronoUnit.YEARS).isAfter(person.getBirthDay())));
System.out.println(checkPersonWithPredicate(kowalski, person -> LocalDate.now().minus(18, ChronoUnit.YEARS).isAfter(person.getBirthDay())));
}
private static boolean checkPerson(Person person, PersonTester personTester) {
return personTester.testPerson(person);
}
private static boolean checkPersonWithPredicate(Person person, Predicate<Person> predicate) {
return predicate.test(person);
}
}
<file_sep>/src/pl/itacademy/first/steps/FillTable.java
package pl.itacademy.first.steps;
import java.util.Arrays;
public class FillTable {
public static void main(String[] args) {
int[] tablica = new int[20];
int index = 0;
while(index < tablica.length) {
tablica[index] = index + 1;
index++;
}
System.out.println(Arrays.toString(tablica));
}
}<file_sep>/src/pl/itacademy/week10/Animal.java
package pl.itacademy.week10;
public class Animal {
public void sleep(int hours) {
System.out.println("animal sleeping " + hours + " hours");
}
/**
* Please, use sleep(hours) instead
*/
@Deprecated(since = "7.12.2019", forRemoval = true)
public void sleep2hours() {
System.out.println("animal sleeping 2 hours");
}
}
<file_sep>/src/pl/itacademy/week8/Room.java
package pl.itacademy.week8;
public final class Room {
private int area;
public Room(int area) {
this.area = area;
}
@Override
public String toString() {
return "Room{" +
"area=" + area +
'}';
}
public int getArea() {
return area;
}
}
<file_sep>/src/pl/itacademy/week7/atms/Bankomat.java
package pl.itacademy.week7.atms;
import java.math.BigDecimal;
public interface Bankomat {
BigDecimal withDraw(BigDecimal amount);
}
<file_sep>/src/pl/itacademy/week10/hw/Execute.java
package pl.itacademy.week10.hw;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Execute {
int times() default 1;
}
<file_sep>/src/pl/itacademy/week7/DateTester.java
package pl.itacademy.week7;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
public class DateTester {
public static void main(String[] args) throws ParseException {
Date now = new Date();
System.out.println(now);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(format.format(now));
Date anotherDay = format.parse("2019-12-31");
System.out.println(anotherDay);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(Calendar.MONTH, 1);
Date changedDate = calendar.getTime();
System.out.println(changedDate);
SimpleDateFormat anotherFormat = new SimpleDateFormat("MMMM-EEEE");
System.out.println(anotherFormat.format(changedDate));
LocalDate today = LocalDate.now();
System.out.println(today);
LocalTime timeNow = LocalTime.now();
System.out.println(timeNow);
LocalDateTime dateWithTime = LocalDateTime.now();
System.out.println(dateWithTime);
LocalDate incrementedDate = today.plus(10, ChronoUnit.DAYS);
System.out.println(incrementedDate);
LocalDate anotherDate = LocalDate.parse("2019-12-31");
System.out.println(anotherDate);
anotherDate = LocalDate.of(2019, 12, 31);
System.out.println(anotherDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate parsedDate = LocalDate.parse("01-01-2020", formatter);
System.out.println(parsedDate);
Date dateToday = new Date();
LocalDateTime localTime = dateToday.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
Date from = Date.from(localTime.atZone(ZoneId.systemDefault()).toInstant());
}
}
<file_sep>/src/pl/itacademy/week8/ExceptionTester.java
package pl.itacademy.week8;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionTester {
public static void main(String[] args) {
Car vw = new Car(10);
driveCar(vw, 100);
driveCar(vw, 100);
driveCar(vw, 100);
driveCar(vw, 100);
driveCar(vw, 100);
System.out.println("=====================================================");
//Do NOT repeat at home, only if you are using Java before 7
// FileInputStream inputStream = null;
// BufferedInputStream bufferedInputStream = null;
// try {
// inputStream = new FileInputStream("C:\\1\\test.txt");
// bufferedInputStream = new BufferedInputStream(inputStream);
// byte[] bytes = bufferedInputStream.readAllBytes();
// for (byte aByte : bytes) {
// System.out.print((char) aByte);
// }
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if(bufferedInputStream != null) {
// bufferedInputStream.close();
// }
// if(inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
String fileName = null;
try(FileInputStream inputStream = new FileInputStream(fileName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
byte[] bytes = bufferedInputStream.readAllBytes();
for (byte aByte : bytes) {
System.out.print((char) aByte);
}
} catch (FileNotFoundException e) {
System.out.println("File does not exists");
} catch (IOException | NullPointerException e) {
System.out.println("Can't read from file: " + fileName);
}
}
private static void driveCar(Car car, int kilometers) {
try {
car.go(kilometers);
} catch (EmptyTankException e) {
System.out.println(e.getMessage());
car.tank(10);
} finally {
System.out.println("Car ready to continue to go");
}
}
private static void tryWithoutCatch() throws IOException {
// try {
// System.out.println("Hello from try section");
// throw new IOException();
// } finally {
//
// }
try(FileInputStream fis = new FileInputStream("C:\\1\\test.txt")) {
System.out.println("Hello from try with resourses");
}
}
}
<file_sep>/src/pl/itacademy/first/steps/LoopsApp.java
package pl.itacademy.first.steps;
public class LoopsApp {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
/* String[] weekDays = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
for(String day : weekDays) {
if("Sat" == day || "Sun" == day){
System.out.println(day);
break;
}
}
*/
/* String[] tablica = new String[10];
for (int i = 0; i < 10; i++) {
tablica[i] = "Java" + i;
if (i == 5) {
break;
}
}
System.out.println(Arrays.toString(tablica));
*/
/* int[] tablica = new int[10];
int i = 0;
do {
tablica[i] = i + 1;
i++;
} while(i < tablica.length);
System.out.println(Arrays.toString(tablica));
*/
/* int counter = 5;
while (counter == 0) {
System.out.println("test");
//counter = counter - 1;
counter--;
}
*/
/* int index = 0;
while (index < args.length) {
System.out.println(args[index]);
index++;
}
*/
}
}<file_sep>/src/pl/itacademy/week6/interfaces/LockableDoor.java
package pl.itacademy.week6.interfaces;
public class LockableDoor extends Door implements Lockable {
private boolean locked;
public LockableDoor(String colour, String material, Size size) {
super(colour, material, size);
}
@Override
public void lock() {
locked = true;
System.out.println("Door has been locked");
}
@Override
public void unlock() {
locked = false;
System.out.println("Door has been unlocked");
}
}
<file_sep>/src/pl/itacademy/week7/accounts/CreditAccount.java
package pl.itacademy.week7.accounts;
import java.math.BigDecimal;
public class CreditAccount extends Account {
private BigDecimal creditLimit;
public CreditAccount(BigDecimal creditLimit) {
super();
this.creditLimit = creditLimit;
}
@Override
public BigDecimal topUp(BigDecimal amount) {
if(balance.add(amount).compareTo(BigDecimal.ZERO) > 0) {
System.out.println("Final balance will be more than 0! Current balance is: " + balance);
} else {
balance = balance.add(amount);
}
return balance;
}
@Override
public BigDecimal withDraw(BigDecimal amount) {
if (balance.subtract(amount).compareTo(creditLimit) > 0) {
balance = balance.subtract(amount);
} else {
System.out.println("Credit limit " + creditLimit + " reached. Current balance: " + balance);
}
return balance;
}
}
<file_sep>/src/pl/itacademy/week9/IteratorTester.java
package pl.itacademy.week9;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class IteratorTester {
public static void main(String[] args) {
List<Integer> numbers = new LinkedList<>();
for (int i = 0; i < 100_000; i++) {
numbers.add(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100_000; i++) {
numbers.get(i);
}
System.out.println((System.currentTimeMillis() - startTime)/1000.0 + " seconds");
startTime = System.currentTimeMillis();
for (Integer number : numbers) {
int n = number;
}
Iterator<Integer> numbersIterator = numbers.iterator();
while(numbersIterator.hasNext()) {
int n = numbersIterator.next();
}
System.out.println((System.currentTimeMillis() - startTime)/1000.0 + " seconds");
}
}
<file_sep>/src/pl/itacademy/week6/interfaces/Lockable.java
package pl.itacademy.week6.interfaces;
public interface Lockable {
boolean HAS_LOCK = true;
void lock();
void unlock();
// compilation error here
// static void removeLock() {
// HAS_LOCK = false;
// }
}
<file_sep>/src/pl/itacademy/week6/object/Kenny.java
package pl.itacademy.week6.object;
public class Kenny extends Person {
private int number;
public Kenny(String firstName, String lastName, int number) {
super(firstName, lastName);
this.number = number;
}
//NEVER do it at home!!
@Override
protected void finalize() throws Throwable {
System.out.println("Oh no! They kill Kenny! You are busters! " + number);
}
}
<file_sep>/src/pl/itacademy/week8/EmptyTankException.java
package pl.itacademy.week8;
public class EmptyTankException extends Exception {
public EmptyTankException(String message) {
super(message);
}
}
<file_sep>/src/pl/itacademy/week7/atms/AbstractATM.java
package pl.itacademy.week7.atms;
import pl.itacademy.week7.Card;
public abstract class AbstractATM {
protected Card card;
public void insertCard(Card card) {
this.card = card;
}
public void endSession() {
card = null;
}
public void changePin(String oldPin, String newPin) {
if(card != null) {
card.changePin(oldPin, newPin);
} else {
System.out.println("Insert card firstly!");
}
}
}
<file_sep>/src/pl/itacademy/week7/MapTester.java
package pl.itacademy.week7;
import java.util.Map;
import java.util.TreeMap;
public class MapTester {
public static void main(String[] args) {
// Map<Person, String> beerLovers = new LinkedHashMap<>();
Map<Person, String> beerLovers = new TreeMap<>();
Person kowalski = new Person ("Jan", "Kowalski");
Person nowak = new Person ("Piotr", "Nowak");
Person sereda = new Person ("Oleg", "Sereda");
beerLovers.put(kowalski, "Jasne");
beerLovers.put(nowak, "ciemne");
beerLovers.put(sereda, "bezalkoholowe");
System.out.println(kowalski + " lubie " + beerLovers.get(kowalski) + " piwo");
System.out.println(nowak + " lubie " + beerLovers.get(nowak) + " piwo");
System.out.println(sereda + " lubie " + beerLovers.get(sereda) + " piwo");
beerLovers.put(kowalski, "bezalkoholowe");
System.out.println(kowalski + " lubie " + beerLovers.get(kowalski) + " piwo");
System.out.println("++++++++++++++++++++++++++++");
System.out.println(beerLovers);
}
}
<file_sep>/src/pl/itacademy/week5/Animal.java
package pl.itacademy.week5;
public abstract class Animal {
String name;
String breed;
public void sleep() {
System.out.println("im going to sleep now");
}
public void eat() {
System.out.println("im going to eat something");
}
public abstract void runAway();
public abstract void chaseAnotherAnimal(Animal animal);
}
<file_sep>/src/pl/itacademy/week9/hw/Tale.java
package pl.itacademy.week9.hw;
public class Tale extends Book {
}
<file_sep>/src/pl/itacademy/week5/Dog.java
package pl.itacademy.week5;
public class Dog extends Pet {
public Dog(String name, String breed) {
super(name, breed);
System.out.println("we have a new dog from shelter");
}
@Override
protected void makeSound() {
super.makeSound();
System.out.println("Wof! Wof!");
}
@Override
public void chaseAnotherAnimal(Animal animal) {
System.out.println("Dog is chasing " + animal.name);
}
}
<file_sep>/src/pl/itacademy/week9/hw/Book.java
package pl.itacademy.week9.hw;
public abstract class Book {
}
<file_sep>/src/pl/itacademy/week5/PetTester.java
package pl.itacademy.week5;
public class PetTester {
public static void main(String[] args) {
Cat tom = new Cat("Tom", "british");
tom.eat();
tom.sleep();
tom.makeSound();
tom.catchMouse();
Dog killer = new Dog("Killer", "Bulldog");
killer.eat();
killer.sleep();
killer.makeSound();
System.out.println("===PETS SECTION===");
Pet pet1 = new Cat("Tom", "British");
Pet pet2 = new Dog("Killer", "Bulldog");
pet1.makeSound();
//pet1.catchMouse(); //Compilation error!
pet2.makeSound();
Pet[] pets = new Pet[3];
pets[0] = pet1;
pets[1] = tom;
pets[2] = killer;
for (Pet pet : pets) {
pet.makeSound();
playWithPet(pet);
}
tom.eat("Milk");
Animal animal = new Cat("Jerry", "cat");
animal.runAway();
//Animal mouse = new Animal(); //compilation error
Cat kitten = new Cat("Kitten", "Pers");
Dog spike = new Dog("Spike", "Bulldog");
spike.chaseAnotherAnimal(kitten);
spike.runAway();
}
public static void playWithPet(Pet pet) {
System.out.println("Playing with " + pet.name);
}
}
<file_sep>/src/pl/itacademy/week7/accounts/Account.java
package pl.itacademy.week7.accounts;
import java.math.BigDecimal;
import java.util.Objects;
public abstract class Account {
private static long accountNumberCounter = 0;
private Long accountNumber;
protected BigDecimal balance;
public Account() {
accountNumber = accountNumberCounter + 1;
accountNumberCounter++;
balance = BigDecimal.ZERO;
}
public abstract BigDecimal topUp(BigDecimal amount);
public abstract BigDecimal withDraw(BigDecimal amount);
public Long getAccountNumber() {
return accountNumber;
}
public BigDecimal getBalance() {
return balance;
}
@Override
public String toString() {
return "Account{" +
"accountNumber=" + accountNumber +
", balance=" + balance +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return Objects.equals(accountNumber, account.accountNumber);
}
@Override
public int hashCode() {
return Objects.hash(accountNumber);
}
}
<file_sep>/src/pl/itacademy/week9/hw/Shelf.java
package pl.itacademy.week9.hw;
import java.util.ArrayList;
import java.util.List;
public class Shelf<T> {
private List<Box<T>> boxes = new ArrayList<>();
public void addBox(Box<T> box) {
boxes.add(box);
}
public List<Box<T>> getBoxes() {
return boxes;
}
}
<file_sep>/src/pl/itacademy/first/steps/HelloWorldApp.java
package pl.itacademy.first.steps;
import java.util.Scanner;
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello Java World!!\n");
System.out.println(); //empty line
System.out.println("IT Academy");
System.out.println(2019);
System.out.println("First " + "Second");
System.out.println(5+4);
System.out.println("5"+"4");
int integerNumber = 10;
integerNumber = integerNumber + 10; //20
integerNumber += 10; //20
int anotherNumber = 15;
double doubleNumber = integerNumber + anotherNumber;
System.out.println(integerNumber);
integerNumber++;
System.out.println(integerNumber);
System.out.println(integerNumber + anotherNumber);
System.out.println(doubleNumber);
boolean boolValue = true;
boolean anotherBoolValue = !boolValue;
System.out.println(anotherBoolValue);
System.out.print("First");
System.out.print("Second");
System.out.print("Third");
System.out.println();
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Hello " + name);
}
}
<file_sep>/src/pl/itacademy/week9/OurComparatorTester.java
package pl.itacademy.week9;
public class OurComparatorTester {
public static void main(String[] args) {
String a = "test";
String b = "TEST";
OurComparator ourComparator = new OurComparator() {
@Override
public boolean compare(String a, String b) {
return a.equalsIgnoreCase(b);
}
};
System.out.println(compare(a, b, (first, second) -> first.equals(second)));
System.out.println(compare(a, b, String::equals));
System.out.println(compare(a, b, String::equalsIgnoreCase));
OurComparator.printMessage("Hello comparator!");
Person kowalski = createPerson(() -> new Person("Jan", "Kowalski"));
System.out.println(kowalski);
//Person emptyPerson = createPerson(() -> new Person());
Person emptyPerson = createPerson(Person::new);
System.out.println(emptyPerson);
emptyPerson.setFirstName("Ola");
emptyPerson.setLastName("Nowak");
System.out.println(emptyPerson);
}
private static boolean compare(String a, String b, OurComparator comparator) {
comparator.printAnotherMessage("Hello from default method!");
return comparator.compare(a, b);
}
private static Person createPerson(PersonSupplier supplier) {
return supplier.get();
}
}
<file_sep>/README.md
# KRK-Java-19-09-1-W
Sources from Java fundamental lessons
|
4f9bbbe2538e1976f39242f1171580d691dc1322
|
[
"Markdown",
"Java"
] | 44
|
Java
|
it-academy-pl/KRK-Java-19-09-1-W
|
9ae4f5ad133125816b88e5f6041bba52624888b2
|
fd97d09b49160d8cfc3219209ce760317b109c69
|
refs/heads/master
|
<repo_name>JoseDavidRodrigruez/Aplicacion2Bimestre4<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Ejercicio2Unidad4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Elige una opcion:");
Console.WriteLine("1 - Crear");
Console.WriteLine("2 - Editar");
Console.WriteLine("3 - Mostrar");
Console.WriteLine("4 - Salir");
string op = Console.ReadLine();
switch (op)
{
case ("1"):
Console.Clear();
Crear(); break;
case ("2"):
Console.Clear();
Edit(); break;
case ("3"):
Console.Clear();
Leer(); break;
case ("4"):
Console.Clear();
Salir(); break;
}
}
static void Crear()
{
StreamWriter archivo;
string nombre;
Console.WriteLine("Escribe el nombre del archivo.");
nombre = Console.ReadLine();
archivo = File.CreateText(nombre + ".txt");
}
static void Edit()
{
StreamWriter edit;
string nombre, texto;
Console.WriteLine("Ingresa el nombre del archivo a editar.");
nombre = Console.ReadLine();
Console.WriteLine("Ingresa texto");
texto = Console.ReadLine();
edit = File.AppendText(nombre + ".txt");
edit.WriteLine(texto);
edit.Close();
}
static void Leer()
{
TextReader Leer;
string nombre, texto;
Console.WriteLine("Que archivo quieres ver?");
nombre = Console.ReadLine();
Console.WriteLine("");
Leer = File.OpenText(nombre + ".txt");
texto = Leer.ReadToEnd();
Console.WriteLine(texto);
Leer.Close();
Console.ReadKey();
}
static void Salir() { return; }
}
}
}
|
4ad5d68d8940dcbd28c191207f5d7ac84bac4b84
|
[
"C#"
] | 1
|
C#
|
JoseDavidRodrigruez/Aplicacion2Bimestre4
|
c3f9b51443ccdb649ab45e9aadbc4560b77e511a
|
2322bf0ed5a0a10636fcf3c6ec291ed4bb666a0e
|
refs/heads/master
|
<repo_name>CheezItMan/Composition_sample<file_sep>/ActsLike2.rb
# ActsLike.rb
module Speak
def speak(sound)
puts sound
end
end
class EnglishPerson
extend Speak
end
class FrenchPerson
extend Speak
end
class CanadianPerson
extend Speak
end
# Create Instance Variables
EnglishPerson.speak("Good Morning!")
<file_sep>/ActsLike.rb
# ActsLike.rb
module Speak
def speak(sound)
puts sound
end
end
class EnglishPerson
include Speak
end
class FrenchPerson
include Speak
end
class CanadianPerson
include Speak
end
# Create Instance Variables
french = FrenchPerson.new
french.speak("Bonjour")
canadian = CanadianPerson.new()
canadian.speak("Good Morning eh")
<file_sep>/Car.rb
# car
module Car
class Wheel
def act
puts "Wheel Rolling!"
end
end
class Horn
def act
puts "Honk Honk!"
end
end
class Car
attr_accessor :wheels, :horn
def initialize
@horn = Horn.new
@wheels = []
4.times do
@wheels << Wheel.new()
end
end
def drive(honking)
@wheels.each do |wheel|
wheel.act()
end
if honking
horn.act
end
end
end
end
my_car = Car::Car.new()
my_car.drive true
|
cd47d3cef5c3f0243148c497085a9e1d7fad3fbe
|
[
"Ruby"
] | 3
|
Ruby
|
CheezItMan/Composition_sample
|
c3b049bf0ffdb2f23f69ce52cca0e79a7b6d3fab
|
312815ab216dfabf1ae7b8d10e346b67bfd7c2dc
|
refs/heads/master
|
<repo_name>jmoscat/thanxup-web<file_sep>/app/controllers/web_controller.rb
class WebController < ApplicationController
def index
end
def test
end
end
<file_sep>/app/mailers/question_mailer.rb
class QuestionMailer < ActionMailer::Base
default :from => "<EMAIL>"
def question_email(wazzup)
@wazzup = wazzup
mail(:to => "<EMAIL>", :subject => "Hey Charly, nuevo mensaje de la web")
end
end
<file_sep>/app/controllers/wazzups_controller.rb
class WazzupsController < ApplicationController
def new
@wazzup = Wazzup.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @wazzup }
end
end
# POST /wazzups
# POST /wazzups.json
def create
@wazzup = Wazzup.new(params[:wazzup])
respond_to do |format|
if @wazzup.save
format.html { redirect_to root_path, notice: 'Your question has been sent!' }
QuestionMailer.question_email(@wazzup).deliver
else
format.html { render action: "new" }
format.json { render json: @wazzup.errors, status: :unprocessable_entity }
end
end
end
end
<file_sep>/test/unit/helpers/wazzups_helper_test.rb
require 'test_helper'
class WazzupsHelperTest < ActionView::TestCase
end
<file_sep>/test/functional/wazzups_controller_test.rb
require 'test_helper'
class WazzupsControllerTest < ActionController::TestCase
setup do
@wazzup = wazzups(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:wazzups)
end
test "should get new" do
get :new
assert_response :success
end
test "should create wazzup" do
assert_difference('Wazzup.count') do
post :create, wazzup: @wazzup.attributes
end
assert_redirected_to wazzup_path(assigns(:wazzup))
end
test "should show wazzup" do
get :show, id: @wazzup
assert_response :success
end
test "should get edit" do
get :edit, id: @wazzup
assert_response :success
end
test "should update wazzup" do
put :update, id: @wazzup, wazzup: @wazzup.attributes
assert_redirected_to wazzup_path(assigns(:wazzup))
end
test "should destroy wazzup" do
assert_difference('Wazzup.count', -1) do
delete :destroy, id: @wazzup
end
assert_redirected_to wazzups_path
end
end
|
77210d36b9bbe5cee4207b014effa634fd8edddb
|
[
"Ruby"
] | 5
|
Ruby
|
jmoscat/thanxup-web
|
4d708c18cb137faa05bdd3d3a499bc47579b6a58
|
28ecd4484fdfa5efb6c8c1605a68c417e231492f
|
refs/heads/master
|
<repo_name>valiants/lista-de-tarea-meteor<file_sep>/server/started.js
if(Tasks.find().count() === 0){
Tasks.insert({
text:'Hello wordl',
fecha: new Date()
});
}
|
475aa96ad108525cfe1700b3f8612e08e080c6e2
|
[
"JavaScript"
] | 1
|
JavaScript
|
valiants/lista-de-tarea-meteor
|
1312090b9ddb3daf8e54eace8dd6e5377ee23e54
|
e897b87d2aae33cdc60dddeb25c68fcfe2982034
|
refs/heads/master
|
<repo_name>Kaendan/Pong<file_sep>/Assets/Scripts/Controller.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Abstract class : Used by ControllerPlayer and ControllerAI - Controls a paddle
public abstract class Controller : MonoBehaviour
{
// the paddle's Speed
public float _Speed = 5;
// Axis used to move the paddle : Only used for debugging on computer
public string _Axis = "Horizontal";
// Whether the paddle is at top or the bottom
public bool _Top = false;
public Collider2D _Collider;
// The Y direction of the paddle
protected int _DirectionY;
// Size of the collider bounds
protected Vector2 _Size;
// Paddle bounds : Used to restrain movements
protected float _MinBound = -2.2f;
protected float _MaxBound = 2.2f;
void Start()
{
if (_Top) {
_DirectionY = -1;
} else {
_DirectionY = 1;
}
_Size = _Collider.bounds.size;
}
void FixedUpdate()
{
// Manages inputs
float x = _Speed * ManageInputs() * Time.deltaTime;
// Moves the paddle
transform.Translate(x, 0, 0);
// Prevents the paddle from going out of its bounds
if (transform.position.x > _MaxBound) {
transform.position = new Vector3(_MaxBound, transform.position.y, 0);
} else if (transform.position.x < _MinBound) {
transform.position = new Vector3(_MinBound, transform.position.y, 0);
}
}
public Vector2 GetSize()
{
return _Size;
}
public int GetDirectionY()
{
return _DirectionY;
}
// Manages inputs and returns the new X position
public abstract float ManageInputs();
}
<file_sep>/Assets/Scripts/ControllerAI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Controls a paddle with an AI's inputs
public class ControllerAI : Controller
{
GameObject _Ball;
Rigidbody2D _BallBody;
public void SetBall(Ball ball)
{
_Ball = ball.gameObject;
_BallBody = _Ball.GetComponent<Rigidbody2D>();
}
// Manages inputs and returns the new X position
public override float ManageInputs()
{
float x = 0;
if (_Ball != null) {
// If the ball is going up
if (_BallBody.velocity.y > 0) {
// Follow the ball's position so that the paddle is able to hit the ball
// I could have done that with raycast too. To guess where the ball will hit the paddle and plan to move the paddle there with a delay (so that it's not unbeatable)
if (_Ball.transform.position.x > this.transform.position.x + _Size.x / 2) {
x = 1;
} else if (_Ball.transform.position.x < this.transform.position.x - _Size.x / 2) {
x = -1;
}
}
} else {
// If there is no ball move the paddle to the center of screen
if (0 > this.transform.position.x + 0.1f) { //
x = 1;
} else if (0 < this.transform.position.x - 0.1f) {
x = -1;
}
}
return x;
}
}
<file_sep>/Assets/Scripts/MenuManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
// Manages the menu buttons
public class MenuManager : MonoBehaviour
{
// Called by Button1 : Activates 1 Player game mode and loads the game scene
public void Load1Player()
{
GameParameters._TwoPlayers = false;
SceneManager.LoadScene("Game");
}
// Called by Button2 : Activates 2 Player game mode and loads the game scene
public void Load2Players()
{
GameParameters._TwoPlayers = true;
SceneManager.LoadScene("Game");
}
}
<file_sep>/Assets/Scripts/Goal.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// Represents a goal. When it's hit by a ball, it destroys the ball
public class Goal : MonoBehaviour
{
private int _Score = 0;
// Current score
private int _MaxScore = 5;
// Score to win
public string _Name;
// Name displayed at victory
public Text _ScoreText;
// Text to display the score
public GameManager _GameManager;
public Text _VictoryText;
// Text to display the victory text
public GameObject _Line;
public GameObject _RetryButton;
public Vector2 _Direction;
// Direction used to spawn the ball depending on the victory
public GameObject _Particles;
public AudioSource _AudioSource;
// Use this for initialization
void Start()
{
UpdateScore();
}
void OnTriggerEnter2D(Collider2D other)
{
// When the ball enters the collider : Updates score and destroys the ball
if (other.tag == "Ball") {
_Score++;
UpdateScore();
_AudioSource.Play();
Instantiate(_Particles, other.transform.position, Quaternion.identity);
Destroy(other.gameObject);
// Check for victory
if (CheckVictory()) {
_Line.SetActive(false);
_VictoryText.gameObject.SetActive(true);
_VictoryText.text = _Name + " Wins!";
_RetryButton.SetActive(true);
} else {
StartCoroutine("RespawnBall");
}
}
}
// Used to spawn a new ball after a some time
IEnumerator RespawnBall()
{
yield return new WaitForSeconds(1f);
_GameManager.SpawnBall(_Direction);
}
void UpdateScore()
{
_ScoreText.text = _Score.ToString();
}
// Returns whether the player wins or not
bool CheckVictory()
{
return _Score >= _MaxScore;
}
}
<file_sep>/Assets/Scripts/OneShotParticles.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Destroys the attached ParticleSystem's GameObject when it's over
public class OneShotParticles : MonoBehaviour
{
public ParticleSystem _ParticleSystem;
// Update is called once per frame
void Update()
{
// Destroys the attached ParticleSystem's GameObject if it's over
if (!_ParticleSystem.IsAlive()) {
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/ControllerPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Controls a paddle with a player's inputs
public class ControllerPlayer : Controller
{
// Manages inputs and returns the new X position
public override float ManageInputs()
{
float x = Input.GetAxisRaw(_Axis);
Vector2 pos = Vector2.zero;
for (int i = 0; i < Input.touchCount; i++) {
pos = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
// If there is a touch in the "paddle zone"
if (_Top && pos.y > 0 || !_Top && pos.y < 0) {
if (pos.x < 0) { // Moves it to the left if the left side of the screen is touched
x = -1;
} else { // Moves it to the right if the right side of the screen is touched
x = 1;
}
break;
}
}
return x;
}
}
<file_sep>/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
// Manages game elements
public class GameManager : MonoBehaviour
{
public GameObject _Paddle2;
public ControllerAI _PaddleAI;
public GameObject _BallPrefab;
// Use this for initialization
void Start()
{
// Activates the Paddle2 or the AI whether it's 1 Player mode or 2 Player mode
if (GameParameters._TwoPlayers) {
_Paddle2.SetActive(true);
} else {
_PaddleAI.gameObject.SetActive(true);
}
// Spawns a new ball and randomly define it's direction (up or down)
SpawnBall(new Vector2(0, Random.Range(0, 2) * 2 - 1));
}
// Update is called once per frame
void Update()
{
// Go back to the menu if back is touched
if (Input.GetKeyDown(KeyCode.Escape)) {
SceneManager.LoadScene("Menu");
}
}
// Reloads the scene to restart the game
public void RetryButton()
{
SceneManager.LoadScene("Game");
}
// Spawns a new ball at 0,0 with the given direction
public void SpawnBall(Vector2 direction)
{
Ball ball = Instantiate(_BallPrefab).GetComponent<Ball>() as Ball;
ball.SetVelocity(direction);
if (!GameParameters._TwoPlayers) {
_PaddleAI.SetBall(ball);
}
}
}
<file_sep>/Assets/Scripts/Ball.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
// Ball's speed
public float _Speed = 3f;
// Maximum speed
public float _MaxSpeed = 9f;
// Sound played when a Paddle is hit
public AudioClip _PaddleSound;
// Sound played when a Wall is hit
public AudioClip _WallSound;
public AudioSource _AudioSource;
public Collider2D _Collider;
public Rigidbody2D _Body;
public GameObject _Particles;
public TrailRenderer _Trail;
// Size of the collider bounds
private Vector2 _Size;
// The true velocity of the ball before it's modified by Unity's physic
private Vector2 _TrueVelocity = new Vector2(0, 0);
void Start()
{
_Size = _Collider.bounds.size;
}
public Vector2 GetSize()
{
return _Size;
}
public float GetSpeed()
{
return _Speed;
}
public void SetSpeed(float speed)
{
// Only set the speed if it's not greater than the maximum speed
if (speed <= _MaxSpeed) {
_Speed = speed;
}
}
public void SetVelocity(Vector2 direction)
{
_TrueVelocity = direction * _Speed;
_Body.velocity = _TrueVelocity;
}
public void SetDirection(Vector2 direction)
{
// Change the velocity x and y signs depending on the given direction
Vector2 newDirection = _Body.velocity;
newDirection.x = Mathf.Abs(newDirection.x) * direction.x;
newDirection.y = Mathf.Abs(newDirection.y) * direction.y;
_Body.velocity = newDirection;
}
public Vector2 GetVelocity()
{
return _Body.velocity;
}
public Vector2 GetTrueVelocity()
{
return _TrueVelocity;
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Paddle") { // if a paddle is hit
// Play sound
_AudioSource.PlayOneShot(_PaddleSound);
// Particle effect
Instantiate(_Particles, transform.position, Quaternion.identity);
Controller paddle = other.gameObject.GetComponent<Controller>();
float x = (transform.position.x - other.transform.position.x) / paddle.GetSize().x;
SetSpeed(GetSpeed() * 1.1f); // Increases the ball's speed
SetVelocity(new Vector2(x, paddle.GetDirectionY()).normalized);
} else if (other.gameObject.tag == "Wall") { // if a wall is hit
// Play sound
_AudioSource.PlayOneShot(_WallSound);
// Particle effect
Instantiate(_Particles, transform.position, Quaternion.identity);
// If the paddle hits a Ball : Changes the ball's velocity depending on its X coordinate
SetVelocity(new Vector2(_TrueVelocity.x * -1, _TrueVelocity.y).normalized);
}
}
}
<file_sep>/Assets/Scripts/GameParameters.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Contains global game parameters
public static class GameParameters
{
// Game mode
public static bool _TwoPlayers = false;
}
|
6588b6ddf767f6337879a785bd2b367b239f5dfa
|
[
"C#"
] | 9
|
C#
|
Kaendan/Pong
|
683926b5d1a31d3553c528cf5b797a8e67ed9cc4
|
43abbf6343651c6dd7387a1983373f5e243a5af7
|
refs/heads/master
|
<file_sep>package com.coign.sam;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class details extends Activity {
String name1,s,br1,qual,exp,phnum,sub,desig,email,deptid;
Dbhandler myDbHelper;
SQLiteDatabase Mydatabase;
TextView tv,tv1,tv2,tv3,tv4,tv5;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView nam=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.num);
tv1=(TextView)findViewById(R.id.add);
tv2=(TextView)findViewById(R.id.textView6);
tv3=(TextView)findViewById(R.id.textView8);
tv4=(TextView)findViewById(R.id.email);
tv5=(TextView)findViewById(R.id.subject);
Bundle b=getIntent().getExtras();
name1=b.getString("name");
nam.setText(name1);
br1=b.getString("branch");
System.out.println("%%%%%%%%%%%%%%%%% "+name1);
openAndQueryDatabase();
}
private void openAndQueryDatabase() {
// TODO Auto-generated method stub
try{
this.myDbHelper=new Dbhandler(this);
FetchingData();
Mydatabase=myDbHelper.getReadableDatabase();
//String s=myDbHelper.values();
Cursor c=Mydatabase.rawQuery("SELECT * FROM EmployeeDetails inner join Dept on EmployeeDetails.DeptID=Dept.DeptID WHERE EmployeeDetails.EmpName='"+name1+"' and Dept.DeptName='"+br1+"' " , null);
c.moveToFirst();
if(c!=null){
int c1=c.getColumnIndex("EmpQualification");
int c2=c.getColumnIndex("EmpDesignation");
int c3=c.getColumnIndex("EmpExp");
int c4=c.getColumnIndex("EmpPhnum");
int c5=c.getColumnIndex("Empemailid");
int c6=c.getColumnIndex("subject");
int c8=c.getColumnIndex("EmpType");
int c7=c.getColumnIndex("DeptID");
do{
qual=c.getString(c1);
tv.setText(qual);
desig=c.getString(c2);
tv1.setText(desig);
exp=c.getString(c3);
tv2.setText(exp);
phnum=c.getString(c4);
tv3.setText(phnum);
email=c.getString(c5);
tv4.setText(email);
sub=c.getString(c6);
tv5.setText(sub);
deptid=c.getString(c7);
System.out.println("$$$$$$$$$$$$$$ "+s);
String type=c.getString(c8);
//Toast.makeText(getApplicationContext(), "retrived value is "+s, 10).show();
}while(c.moveToNext());
//Toast.makeText(getApplicationContext(), "retrived value is "+s, 10).show();
}
}catch(SQLiteException se){
}
}
private void FetchingData() {
// TODO Auto-generated method stub
try {
myDbHelper.onCreateDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
Mydatabase = myDbHelper.getWritableDatabase();
System.out.println("executed");
}catch(SQLException sqle){
throw sqle;
}
// TODO Auto-generated method stub
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add("call");
menu.add("message");
menu.add("Edit");
menu.add("Delete");
menu.add("Mail");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
String m1=(String) item.getTitle();
if(m1.equalsIgnoreCase("call")){
Intent it=new Intent(details.this,call.class);
it.putExtra("num", phnum);
startActivity(it);
}
if(m1.equalsIgnoreCase("message")){
Intent it=new Intent(details.this,MessageSending.class);
it.putExtra("num", phnum);
startActivity(it);
}
if(m1.equalsIgnoreCase("Mail")){
Intent mailIntent = new Intent(android.content.Intent.ACTION_SEND);
mailIntent.setType("plain/text");
mailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { email });
mailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Invitation");
mailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(mailIntent);
}
if(m1.equalsIgnoreCase("Edit")){
Intent it=new Intent(details.this,AddEmployee.class);
it.putExtra("uname", name1);
it.putExtra("branch", br1);
it.putExtra("deptid", deptid);
startActivity(it);
}
if(m1.equalsIgnoreCase("Delete")){
alertbox("Confirmation !","Are You Sure Do You Want TO Upload ?");
}
return super.onOptionsItemSelected(item);
}
private void alertbox(String string, String string2) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setMessage("are you sure! you want to delete")
.setTitle("Delete")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Delete();
Intent it1=new Intent(details.this,sam.class);
startActivity(it1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
protected void Delete() {
// TODO Auto-generated method stub
this.myDbHelper=new Dbhandler(this);
FetchingData();
Mydatabase=myDbHelper.getReadableDatabase();
Mydatabase.execSQL("DELETE FROM EmployeeDetails WHERE EmpName='"+name1+"' and EmpPhnum='"+phnum+"'");
Toast.makeText(getApplicationContext(), "Record Deleted sucessfully", 80).show();
}
}
<file_sep>package com.coign.sam;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class sam extends Activity {
Dbhandler myDbHelper;
SQLiteDatabase Mydatabase;
ArrayList<String> aa,depts;
Button btn,btn1,btn2,btn3,btn4,btn5,btn6;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getdepartmentdetails();
final MediaPlayer mp=MediaPlayer.create(this, R.raw.ocean);
final MediaPlayer mp1=MediaPlayer.create(this,R.raw.button);
// mp.start();
btn=(Button)findViewById(R.id.cse);
btn1=(Button)findViewById(R.id.ece);
btn2=(Button)findViewById(R.id.eee);
btn3=(Button)findViewById(R.id.mech);
btn4=(Button)findViewById(R.id.chem);
btn5=(Button)findViewById(R.id.civil);
for(int k=0;k<depts.size();k++)
{
if(depts.get(k).equals("CSE"))
btn.setVisibility(Button.VISIBLE);
else if(depts.get(k).equals("ECE"))
btn1.setVisibility(Button.VISIBLE);
else if(depts.get(k).equals("EEE"))
btn2.setVisibility(Button.VISIBLE);
else if(depts.get(k).equals("MECH"))
btn3.setVisibility(Button.VISIBLE);
else if(depts.get(k).equals("CHEM"))
btn4.setVisibility(Button.VISIBLE);
else if(depts.get(k).equals("CIVIL"))
btn5.setVisibility(Button.VISIBLE);
System.out.println("VVVVVVVVVVVVVVVVVVVVVv "+depts.get(k));
}
// final EditText et=(EditText)findViewById(R.id.editText1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String cse=btn.getText().toString();
it.putExtra("branch", cse);
startActivity(it);
//CSE();
}
});
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String ece=btn1.getText().toString();
it.putExtra("branch", ece);
startActivity(it);
//CSE();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String eee=btn2.getText().toString();
it.putExtra("branch", eee);
startActivity(it);
//CSE();
}
});
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String mech=btn3.getText().toString();
it.putExtra("branch", mech);
startActivity(it);
//CSE();
}
});
btn4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String chem=btn4.getText().toString();
it.putExtra("branch", chem);
startActivity(it);
//CSE();
}
});
btn5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,dept.class);
final String civil=btn5.getText().toString();
it.putExtra("branch", civil);
startActivity(it);
//CSE();
}
});
/*btn6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp1.start();
Intent it=new Intent(sam.this,List.class);
final String mech=btn3.getText().toString();
it.putExtra("branch", mech);
startActivity(it);
//CSE();
}
});*/
}
private void getdepartmentdetails() {
// TODO Auto-generated method stub
this.myDbHelper=new Dbhandler(this);
FetchingData();
System.out.println(" $$$$$$$$$$$$$$$$$$$$$$$ fetchdata completed @@@@@@@@@@@@@@@@@@@@@");
Mydatabase=myDbHelper.getReadableDatabase();
depts=this.myDbHelper.getDeparments(Mydatabase);
//System.out.println(depts.toString());
}
/*protected void CSE() {
// TODO Auto-generated method stub
this.myDbHelper=new Dbhandler(this);
FetchingData();
System.out.println(" $$$$$$$$$$$$$$$$$$$$$$$ fetchdata completed @@@@@@@@@@@@@@@@@@@@@");
Mydatabase=myDbHelper.getReadableDatabase();
aa=this.myDbHelper.employee(Mydatabase,"CSE");
System.out.println("$%^&*^^&&&&&&&&&&&&& "+aa);
}*/
protected void FetchingData() {
// TODO Auto-generated method stub
try {
myDbHelper.onCreateDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
Mydatabase = myDbHelper.getWritableDatabase();
System.out.println("executed");
}catch(SQLException sqle){
throw sqle;
}
// TODO Auto-generated method stub
}
}<file_sep>package com.coign.sam;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class dept extends Activity{
Button teac,nonteach;
String type;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dept);
Bundle b2=getIntent().getExtras();
final String br=b2.getString("branch");
teac=(Button)findViewById(R.id.button1);
nonteach=(Button)findViewById(R.id.button2);
teac.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it=new Intent(dept.this,List.class);
type=(String) teac.getText();
Toast.makeText(getApplicationContext(), type, 100).show();
it.putExtra("branch", br);
it.putExtra("type", type);
startActivity(it);
}
});
nonteach.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it=new Intent(dept.this,List.class);
type=(String) nonteach.getText();
Toast.makeText(getApplicationContext(), type, 100).show();
it.putExtra("branch", br);
it.putExtra("type", type);
startActivity(it);
}
});
}
}
|
eaca6d04cba00ff1cb268492816369c54f42cc5f
|
[
"Java"
] | 3
|
Java
|
Adithya-123/Collegephonebook
|
b4ed4a54dc9f091812181509bcfa7598fac5c5ca
|
612cba60660ffdcb59af4c7856cfcda3ffe3f346
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.