branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>roua914/autocomplete-<file_sep>/index.js //Get input element var input = document.getElementById('select-book'); // Update the placeholder text. input.placeholder = "Loading books..."; function getData() { // Create a new XMLHttpRequest. var request = new XMLHttpRequest(); request.open('GET', 'userData.json', true); request.onload = function () { if (request.status >= 200 && request.status < 400) { // Success! input.placeholder = "Select a book"; //desactivate the spinner document.getElementById("spinner").style.display = "none"; //Parse JSON var books = JSON.parse(request.responseText).books; //Create elment options var options = ''; books.forEach((book, index) => { options += '<option value="' + book.title + '" />'; }) document.getElementById('books').innerHTML = options; } else { // it returned an error console.log(request.responseText); } }; request.onerror = function () { // a connection error }; request.send(); } setTimeout(() => getData(), 3000);
63010ed080feeb6960e036a1632027dc62ec5675
[ "JavaScript" ]
1
JavaScript
roua914/autocomplete-
6089dacd9a54660c967e34e1433bf604a776440c
7af472dc9e31c26284cf392863ea2c3b3fb67776
refs/heads/master
<repo_name>hollberg/FIM_bots<file_sep>/screencap.py """profile_merge.py Pass 2 column list of FIMS IDs; merge first into the second""" import pyautogui as bot import time time.sleep(3) region = (0,0, 1920,1080) bot.screenshot('img/message_global_change_done_1366x768.png', region=region)<file_sep>/build_dc_zips.py """ build_dc_zips.py Build *.zip files and associated 1003.txt file for Donor Central fund statement uploads. By: <NAME> (<EMAIL>) Created: 4/30/2020 Last Update: 4/30/2020 """ # Imports import zipfile import os from os.path import basename # Configuration Values source_dir = r'P:\00_Common\FinanceCommon\DonorStatements\2020\2020Q1\2020Q1_Manual' destination_dir = r'N:\found\eAdvisor\Statements\DonorCentral\2020Q1_V2' zipfile_prefix = r'2020Q1_DC_Zip_' begin_date = '1/1/2020' end_date = '3/31/2020' fname = 'contents1003.txt' contents = '' max_size = 15_000_000 # Max size of all files in zip running_size = 0 zipfile_number = 1 def make_contents_line(fundid, fname, begin_date, end_date): """ Create a new line of the 'contents1003.txt' file """ values = ['0142', fundid, fname, begin_date, end_date, '1003'] return '\t'.join(values) + '\n' # print(make_contents_line('fund', 'foo.txt', '1/1/2020', '3/31/2020')) # Loop over files in 'source_dir'; Make zip file with 'contents1003.txt' file number_of_files = len(os.listdir(source_dir)) for i, file in enumerate(os.listdir(source_dir)): # Define output zip file output_zip_filepath = os.path.join(destination_dir, zipfile_prefix+str(zipfile_number)+'.zip') with zipfile.ZipFile(output_zip_filepath, 'a') as output_zip: # Get next statement.pdf filepath = os.path.join(source_dir, file) # Format of (C:\mytext.txt) fundid = file.split('_')[0] # fname of format 'FUNDID_BEGINDATE.pdf' output_zip.write(filepath, basename(file)) contents += make_contents_line(fundid=fundid, fname=file, begin_date=begin_date, end_date=end_date) file_stats = os.stat(filepath) running_size += file_stats.st_size # In bytes; 1,000,000 = 1MB if (running_size >= max_size) \ or (i + 1 == number_of_files): # File's big enough/last loop with open(fname, 'w') as contents_file: contents_file.write(contents) # Write file (without full filepath) to zip # See stackoverflow.com/questions/16091904 output_zip.write(fname) # Reset/Update values zipfile_number += 1 running_size = 0 contents = '' <file_sep>/prof_merge_fast.py """prof_merge_fastpy Pass 2 column list of FIMS IDs; merge first into the second""" import pyautogui as bot import pandas as pd import xlrd import time import gui_tools screen_res = str(bot.size()[0]) + 'x' + str(bot.size()[1]) def merge_profiles(copy_from_id, copy_to_id): """ :param copy_from_id: :param copy_to_id: :return: """ # Click File Maint #click_item('file_maint') bot.press('alt', interval=.1) bot.press('f', interval=.1) # Click "File Maintenance" -> "Profiles" #click_item('profiles') bot.press('enter', interval=.1) # click_item('combine_2_profiles') gui_tools.press_x_times('c', 3, .2) # Press "C" 3 times bot.press('enter', interval=1) time.sleep(3) # Enter "From", then "To" FIMS IDs to merge bot.typewrite(copy_from_id) # Tab to next entry bot.press('tab', interval=.5) bot.typewrite(copy_to_id, interval=.5) gui_tools.press_x_times('tab', 2, .25) # Press 'tab' twice bot.press('enter', interval=1) # Selects "OK" button #Do you want to delete copy from? bot.press('tab') # Toggles from "No" selected to "Yes: bot.press('enter') # Clicks/selects the "yes" button print('Sleeping for 5 seconds') time.sleep(.6) # Choose "yes" on the "Ready to Proceed" window bot.press('tab') # Toggles from "No" selected to "Yes: bot.press('enter') # Clicks/selects the "yes" button # Wait/check until the window labeled "Message" with text # "Profiles Combined!" appears. Then click "OK time.sleep(30) for i in range(20): print('Checking for "profiles combined" box') xy = bot.locateCenterOnScreen( 'img/message_box_profiles_combined_1920x1080.png', grayscale=True) if xy is not None: # Then merge is complete bot.press('enter') print('Merged ' + copy_from_id + ' into ' + copy_to_id) break # Exit loop else: time.sleep(30) # time.sleep(45) # Click "OK" bot.press('enter') return True time.sleep(3) # Read in Excel file of "From->To" mappings FROM_TO_FILE = r'P:\03_FinanceOperations\InformationManagement\Data Quality\MergeTemplates\to_merge.xlsx' df_from_to = pd.read_excel(FROM_TO_FILE) for index, row in df_from_to.iterrows(): from_id = str(row.From_ID) to_id = str(row.To_ID) print(f'Merging id {from_id} to id -> {to_id}') merge_profiles(from_id, to_id) <file_sep>/contact_record_create.py """contact_record_create.py Read data from external file; build a contact record in FIMS Follow toolbar path: View -> Contacts -> """ #Imports # Standard Library import time # Local Modules import gui_tools as gt # External Libraries import pyautogui as bot import pandas as pd IMG_DIR = 'img/contact_record_create/' def new_contact(fims_id:str, tickle_date:str = None, tickle_who:str = None, contact_date:str = None, next_action:str = None, contact_type:str = None, contact_time:str = None, contact_priority:int = None, solicitor:str = None, staff:str = None, fund:str = None, contact_comment:str = None, contact_grant:str = None): """ From a full-screen FIMS launch screen, open and populate a new Contact record :return: None """ # Select "View" -> "Contacts" menu path via Alt-V -> "C" -> <enter> # bot.hotkey('alt', 'v') # time.sleep(.2) # bot.typewrite(['c', 'enter'], interval=.5) # Launch "Contacts" window - shortcut ctrl^alt^T # bot.hotkey('ctrl', 'alt', 't') # See if contact window has launched # Wait until Contacts window appears # TODO - reinstate code below, but get updated # new_record_xy = None # while new_recor d_xy is None: # The screen hasn't opened yet, sleep # time.sleep(2) # new_record_xy = bot.locateCenterOnScreen(IMG_DIR + 'new_record.png') time.sleep(10) # Assume contacts window is a pop-under; alt-tab to view it #bot.hotkey('alt', 'tab', interval=0.1) # Create new record ('Alt^W') print('About to alt W') bot.hotkey('alt', 'W') # Move mouse and click to activate window # bot.click(400,400) # # Click the "New" icon (piece of paper) to launch new contact window # bot.click(new_record_xy[0], new_record_xy[1]) # time.sleep(2) # New Contact record window launches with "Grant" field highlighted. gt.tab_then_type(2, fims_id) # tab twice to get to FIMS ID gt.tab_then_type(4, tickle_date) # Tab 4 times to get to "Tickle Date" gt.tab_then_type(1, tickle_who) # Tab to get to 'Tickle Who' gt.tab_then_type(1, contact_date) # Tab to get to contact date gt.tab_then_type(1, next_action) # Tab to get to Next Action (date) gt.tab_then_type(1, contact_type) # Tab once to get to Contact Type gt.tab_then_type(1, contact_time) # Tab to get to Time gt.tab_then_type(1, contact_priority) # Tab to get to priority gt.tab_then_type(3, solicitor) # Tab **3 times** to get to solicitor gt.tab_then_type(1, staff) # Tab to get to staff gt.tab_then_type(1, fund) # Tab to get to fund gt.tab_then_type(1, contact_comment) # Tab to get to comment # gt.tab_then_type(1, contact_grant) # Tab to get to grant # # Click the save (floppy disk) icon # gt.click_pic(IMG_DIR + 'new_contact_save_icon.png') print('About to save') bot.hotkey('alt', 'S') # Save keyboard shortcut time.sleep(3) #print('About to alt f4') # Select "File" -> Close Tab via "Alt" -> F -> F -> <Alt-F4> # bot.press(['alt', 'f', 'f', 'enter'], interval=1) # bot.hotkey('alt', 'f4') # Cleanup - Move mouse to lower left corner) # bot.moveTo(0, bot.size()[1]) return None def main(): time.sleep(2) contact_filepath = r'P:\03_FinanceOperations\InformationManagement\Databases\FIM_Bots_data' contact_file = r'FIM_Bots_contacts_Spark_1_20190514.xlsx' df_contacts = pd.read_excel(contact_filepath + r'\\' + contact_file) df_contacts.fillna('', inplace=True) # Launch "Contacts" window - shortcut ctrl ^ alt ^ T bot.hotkey('ctrl', 'alt', 't') time.sleep(30) for index, row in df_contacts.iterrows(): fims_id = str(row['FIMSID']) staff = row['StaffCode'] contact_comment = gt.clean_text(row['Comment']) + '\n' \ + '<Bulk entry 20190516>' contact_type = row['CntctType'] eff_date = pd.to_datetime(row['EffDate']) contact_date = f'{str(eff_date.month)}/{str(eff_date.day)}/{str(eff_date.year)}' print(f'preparing to' f' load for {fims_id}') new_contact(fims_id=fims_id, staff=staff, contact_type=contact_type, contact_date=contact_date, contact_comment=contact_comment) time.sleep(2) main() <file_sep>/program_area.py """program_area.py Load entries to the "Program Area" (NTEE) codes in FIMS File Maintenance -> Grants -> Grant Code Maintenance -> Program Area -> (NEW) Alt^F (file maintenance) G G [Enter] (Grants) G G [Enter] (Grant Code Maintenance) P P [Enter] (Program Area) Code | Description | Budget | Field | Active new record is Alt^w """ # Standard import time #External Libraries import pandas as pd import pyautogui as bot #Local External Modules import gui_tools as gt # Read Excel File xl_path = r'P:\03_FinanceOperations\InformationManagement\F2RE\Cleanup\FIMS_NTEE_Load.xlsx' df_ntee = pd.read_excel(xl_path) print(df_ntee.head()) time.sleep(1) for row in df_ntee.iterrows(): time.sleep(2) ntee_code = row[1]['ntee'] ntee_desc = row[1]['description'] # Create new record ('Alt^W') bot.hotkey('alt', 'w') # cursor will be in "Code" column time.sleep(.2) bot.typewrite(ntee_code, interval=.1) # NTEE/Program Code time.sleep(.2) gt.tab_then_type(1, ntee_desc) # Program Description time.sleep(.2) bot.press('tab') # Budget (ignore) time.sleep(.2) gt.tab_then_type(1, "S") # Field ([P]rimary or [S]econdary) time.sleep(.2) bot.press('tab') # Active, defaults to Yes time.sleep(.2) bot.press('tab') # To next row, launches save dialog time.sleep(1) bot.press('Y') # Switch from "no" to "Yes" <file_sep>/relationships.py """ relationships.py Build Relationship records in FIMS """ import gui_tools as gt """ Tools/Steps to leverage 1) Launch FIMS, open PROFILES module. Set to Search by: ID Code 2) Select the "Relationships" tab. From Main Search Screen, with cursor in "Find Record" a) Type FIMS ID 1 b) Enter c) Alt^W (New) d) Tab x 2 e) Paste other FIMS ID f) Tab x 2 g) Paste RELATIONSHP TYPE h) tab x 1 i) Alt^S (Save) j) Alt^V (Create inverse relationship) k) Tab (select's "Yes" in dialog) l) Enter (hits enter) m) F3 (returns to 'Search' screen (step (a), above) """<file_sep>/changeGL.py """changeGL.py Automate remapping a FIMS GL Account code via Tools -> System Utilities -> Admin Utilities -> Finance Utilities -> Change Natural Account """ import pyautogui as bot import pandas as pd import xlrd import time import gui_tools as gt import yrdata def map_gl(fisc_yr, gl_old, gl_new): time.sleep(1) pics_to_click = [ 'menu_tools_highlighted.png', 'menu_tools_systemutilities.png', 'menu_tools_systemutilities_adminutilities.png', 'menu_tools_systemutilities_adminutilities_financeUtilities.png', 'menu_tools_systemutilities_adminutilities_financeUtilities_ChangeNaturalAccount.png' ] photo_folder = 'img/GLChng/' # Tools -> System Utilities -> Admin Utilities -> Finance Utilities -> Change Natural Account for pic in pics_to_click: path = photo_folder + pic gt.click_pic(path, sleep=1, logging=True) time.sleep(1) # # Confirm message box appears # msg_box_xy = bot.locateOnScreen(photo_folder + # 'message_box_ChangeNaturalAccountNumber.png') # # # if msg_box_xy is None: #Box not found! # print('***ERROR*** Message box did not appear') # # time.sleep(1) # Click the "OK" button on the message box bot.press('enter') time.sleep(1) # Enter data in "Global Change for GL Natural Account" window # steps: 1) Enter "Old" Account number; /tab # 2) Enter "New" Account number; /tab*3 # 3) Select FY: Type number "2" n times (once = 2000, twice=2001...) # 4) /tab*3, type "Enter" (Selects "OK" button) bot.typewrite(gl_old) bot.press('tab') time.sleep(1) bot.typewrite(gl_new) # Tab 3 times to select GL Year option bot.press('tab') bot.press('tab') bot.press('tab') time.sleep(1) # Enter "2" enough times to cycle to desired fiscal yr number_of_2s = fisc_yr - 1999 for _ in range(number_of_2s): bot.press('2', pause=.2) time.sleep(1) # Tab 3 times to select "Proceed" button bot.press('tab') bot.press('tab') bot.press('tab') # "Proceed" button is highlighted; hit "enter" to run process bot.press('enter') # Process will run for a long time. Check to see when completion message box # "Global Change for GL Natural Account" window appears - then click "Enter" for i in range(30): print('Cycle Number ' + str(i)) time.sleep(30) gl_error_box_xy = \ bot.locateOnScreen(photo_folder + 'Error_box.png') if gl_error_box_xy is not None: bot.press('enter') done_msg_box_xy = \ bot.locateOnScreen(photo_folder + 'message_box_Global_Change_for_GL_nat_account.png') if done_msg_box_xy is not None: #box appeared bot.press('enter') # Selects "OK" button on window break # Exit for loop for entry in yrdata.mapping: gl_yr = entry[0] old_gl = entry[1] new_gl = entry[2] map_gl(fisc_yr=gl_yr, gl_old=old_gl, gl_new=new_gl)<file_sep>/gui_tools.py import pyautogui as bot import time import re # Issues with 4k monitors? Per comments at # https://github.com/asweigart/pyautogui/issues/33 from ctypes import windll user32 = windll.user32 user32.SetProcessDPIAware() def click_pic(path_to_photo, sleep = 0, logging = False, region = None): """given the filepath to a lossless imagage format (like *.png), find the (x,y) coordinates of that image on the screen, and click the mouse there """ if logging: print('Looking for location of ' + path_to_photo) if region: xy = bot.locateCenterOnScreen(path_to_photo, region=region, grayscale=True) else: xy = bot.locateCenterOnScreen(path_to_photo, grayscale=True) if xy is None: print(path_to_photo + ' image not found') return None else: if logging: print('Photo ' + path_to_photo + ' located at (' + str(xy[0]) + ',' + str(xy[1])) bot.click(xy) if sleep != 0: time.sleep(abs(sleep)) return True def screencapt(output_file, region=(0,0, 1920, 1080)): """ :param output_file: :param region: :return: """ bot.screenshot(output_file, region=region) return True def get_screenres(): screen_res = str(bot.size()[0]) + 'x' + str(bot.size()[1]) return screen_res def track_mouse(): """ Utility function to keep running log of current mouse X,Y position :return: """ for i in range(1999): time.sleep(.1) x,y = bot.position() print(str(x) + ", " + str(y)) def press_x_times(input_key:str, repetitions:int, interval=.2): """ Press 'key' characters 'repetitions' number of times :param input_key: String, key(s) to press :param repetitions: Int, number of times to repeat :return: None """ for _ in range(repetitions): bot.press(input_key) time.sleep(interval) return None def tab_then_type(tab_count:int = 1, input_value:str=None): """ Convenience script. Tab "tab_count" times to advance selected cell. Then, type in the 'input_value' into selected field :param tab_count: Number of times to 'tab' and advance selected input :param input_value: Value to paste into selected cell :return: None """ press_x_times('tab', tab_count, interval=1) if input_value: bot.typewrite(input_value) print(str(input_value)) return None def clean_text(input_text:str)->str: """ Given a text string, clean out all non-printing characters except 'enter' :param input_text: :return: Cleaned text """ re_chars_and_hard_return = re.compile('[^A-Za-z0-9 !@#$%^&*(){}[]/<>-+=_;:"\',.\n]') cleaned_text = re_chars_and_hard_return.sub('',input_text) return cleaned_text <file_sep>/img/test36.py import pyautogui as bot # bot.screenshot('chrome_icon.png') x,y = bot.locateCenterOnScreen('chrome_icon.png') bot.lo<file_sep>/mouse_location.py import pyautogui as bot import time import gui_tools as gt from collections import namedtuple # resolution_location = namedtuple(['resolution, x_loc, y_loc']) # x, y = bot.size() # print(str(x) + ", " + str(y)) time.sleep(2) # gt.screencapt('img/contact_record_create/new_contact.png') gt.track_mouse() <file_sep>/changeGLfast.py """changeGL.py Automate remapping a FIMS GL Account code via Tools -> System Utilities -> Admin Utilities -> Finance Utilities -> Change Natural Account """ import pyautogui as bot import pandas as pd import xlrd import time from datetime import datetime import yrdata # bot.FAILSAFE = False # disables the fail-safe screen_res = str(bot.size()[0]) + 'x' + str(bot.size()[1]) # Dict of dicts, storing (x,y) location of menu item for a given screen # resolution (assumes FIMS is running at full screen). # Format is: {'MENU LOCATION': {ScreenResolution: (X,Y)}} menu_locations = {'tools': {'1366x768': (420,32)}, 'system_utils': {'1366x768': (493,189)}, 'admin_utils': {'1366x768': (789,595)}, 'fin_utils': {'1366x768': (1044,665)}, 'change_net_account': {'1366x768': (786, 503)}, 'file_maint': {'1366x768': (353, 33)}, 'profiles': {'1366x768': (349,57)}, 'combine_2_profiles': {'1366x768': (579,325)}, } def click_item(menu_item, screen_res = screen_res, menu_locations=menu_locations): """ Given a menu item name, click the mouse at the x,y coords :param menu_item: :return: """ x,y = menu_locations[menu_item][screen_res] bot.click(x,y) time.sleep(1) print('clicked ' + menu_item) return True def map_gl(fisc_yr, gl_old, gl_new): time.sleep(1) click_item('tools') click_item('system_utils') click_item('admin_utils') click_item('fin_utils') click_item('change_net_account') time.sleep(1) # Click the "OK" button on the message box bot.press('enter') time.sleep(1) # Enter data in "Global Change for GL Natural Account" window # steps: 1) Enter "Old" Account number; /tab # 2) Enter "New" Account number; /tab*3 # 3) Select FY: Type number "2" n times (once = 2000, twice=2001...) # 4) /tab*3, type "Enter" (Selects "OK" button) bot.typewrite(gl_old) bot.press('tab') time.sleep(1) bot.typewrite(gl_new) # Tab 3 times to select GL Year option bot.press('tab') bot.press('tab') bot.press('tab') time.sleep(1) # Enter "2" enough times to cycle to desired fiscal yr number_of_2s = fisc_yr - 1999 for _ in range(number_of_2s): bot.press('2', pause=.2) time.sleep(1) # Tab 3 times to select "Proceed" button bot.press('tab') bot.press('tab') bot.press('tab') # "Proceed" button is highlighted; hit "enter" to run process bot.press('enter') err_count = 0 # Process will run for a long time. Check to see when completion message box # "Global Change for GL Natural Account" window appears - then click "Enter" for i in range(1000): print('Cycle Number ' + str(i)) time.sleep(10) # Check to see if an error box pops up; click "OK" if it does gl_error_box_xy = \ bot.locateOnScreen('img/' + 'error_global_change_for_gl.png', region=(479,307, 888,467)) if gl_error_box_xy is not None: print('Error found converting GL Account ' + gl_old) bot.screenshot('img/errors/' + gl_old + '_' + str(err_count) + '.png') err_count += 1 bot.press('enter') done_msg_box_xy = \ bot.locateOnScreen('img/message_global_change_done_1366x768.png', region=(473,307, 888,467)) if done_msg_box_xy is not None: #box appeared bot.press('enter') # Selects "OK" button on window print('Completed conversion of GL Account ' + gl_old + ' to ' + gl_new) break # Exit for loop for entry in yrdata.mapping: fisc_yr, gl_old, gl_new = entry # gl_yr = entry[0] # old_gl = entry[1] # new_gl = entry[2] time_begin = datetime.now() map_gl(fisc_yr=fisc_yr, gl_old=gl_old, gl_new=gl_new) print('*** mapping account ' + gl_old + ' to ' + gl_new + ' took ' + str((datetime.now()-time_begin)/60) + ' minutes')
31144b730220c6add3a88c7513a71d28dc3918e4
[ "Python" ]
11
Python
hollberg/FIM_bots
c9e5e01a11abbc23b60ea49f8888326c27e7024a
c6313f3225fbed4270c45210bb8d7ccb955984b4
refs/heads/master
<file_sep>Time machine and shutdown ============================== 2016-10-16 Launch time machine then shut your mac in one line. This script starts a time machine backup, and when done, it shuts down your mac. ```bash sudo tmutil startbackup --block; sudo shutdown -h now; exit ``` I personally make a tmdown alias for it, which makes it very easy to backup the pc before going to bed. <file_sep>sudo tmutil startbackup --block; sudo shutdown -h now; exit
d64b9295b4c8c89b0d60e747d78db99520fc2aaf
[ "Markdown", "Shell" ]
2
Markdown
lingtalfi/Time-machine-and-shutdown
a6e27121927f310998d0cccf3cd3904787c30d9d
5a236fe3db79322170bd61c00997d47eececa23a
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package OWLapi; import MCommon.Global; import MDataProcessing.Assertion.ConceptAssertion; import MDataProcessing.ConceptProcessing; import static MDataProcessing.ConceptProcessing.CFCFFVgetIndividuals; import MDataProcessing.DataProcessing; import MDataProcessing.Individual.ConceptIndividuals; import MDataProcessing.RoleProcessing; import MKnowledge.KnowledgeBase; import static com.clarkparsia.owlapiv3.OWL.factory; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.semanticweb.owlapi.model.AddAxiom; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; import org.semanticweb.owlapi.model.OWLDataProperty; import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLIndividual; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLOntologyFormat; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import static org.semanticweb.owlapi.vocab.OWL2Datatype.Category.URI; /** * * @author thangdn */ public class HomeForm extends javax.swing.JFrame { /** * Creates new form HomeForm */ public HomeForm() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jMenuBar2 = new javax.swing.JMenuBar(); jMenu8 = new javax.swing.JMenu(); jMenu9 = new javax.swing.JMenu(); jScrollPane1 = new javax.swing.JScrollPane(); jtreeConcept = new javax.swing.JTree(); jScrollPane2 = new javax.swing.JScrollPane(); jTreeRole = new javax.swing.JTree(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); lists = new javax.swing.JList(); jScrollPane4 = new javax.swing.JScrollPane(); jTreeData = new javax.swing.JTree(); javax.swing.JPanel jPanelRole = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jtfRangeRole = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jtfDomainRole = new javax.swing.JTextField(); jbAddRole = new javax.swing.JButton(); jPanelConcept = new javax.swing.JPanel(); jtfnameConcept = new javax.swing.JTextField(); jbAddConcept = new javax.swing.JButton(); jPanelData = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jtfDataRange = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jtfDataDomain = new javax.swing.JTextField(); jbadData = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jbtSave = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jmbtLoadOntology = new javax.swing.JCheckBoxMenuItem(); jCheckBoxMenuItem2 = new javax.swing.JCheckBoxMenuItem(); jmbtExit = new javax.swing.JRadioButtonMenuItem(); jMenu2 = new javax.swing.JMenu(); jCheckBoxMenuItem3 = new javax.swing.JCheckBoxMenuItem(); jCheckBoxMenuItem4 = new javax.swing.JCheckBoxMenuItem(); jmAbout = new javax.swing.JMenu(); jmbtAbout = new javax.swing.JCheckBoxMenuItem(); jMenu8.setText("File"); jMenuBar2.add(jMenu8); jMenu9.setText("Edit"); jMenuBar2.add(jMenu9); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); jtreeConcept.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jScrollPane1.setViewportView(jtreeConcept); treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); jTreeRole.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jScrollPane2.setViewportView(jTreeRole); jLabel1.setText("Concepts"); jLabel2.setText("Roles"); lists.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { listsValueChanged(evt); } }); jScrollPane3.setViewportView(lists); treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); jTreeData.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jScrollPane4.setViewportView(jTreeData); jLabel4.setText("Range:"); jLabel5.setText("Domain:"); jbAddRole.setText("Add Role"); jbAddRole.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAddRoleActionPerformed(evt); } }); javax.swing.GroupLayout jPanelRoleLayout = new javax.swing.GroupLayout(jPanelRole); jPanelRole.setLayout(jPanelRoleLayout); jPanelRoleLayout.setHorizontalGroup( jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelRoleLayout.createSequentialGroup() .addGroup(jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtfRangeRole) .addComponent(jtfDomainRole))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelRoleLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbAddRole) .addContainerGap()) ); jPanelRoleLayout.setVerticalGroup( jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelRoleLayout.createSequentialGroup() .addGroup(jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jtfRangeRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanelRoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jtfDomainRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbAddRole) .addGap(0, 0, Short.MAX_VALUE)) ); jbAddConcept.setText("Add Concept"); jbAddConcept.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAddConceptActionPerformed(evt); } }); javax.swing.GroupLayout jPanelConceptLayout = new javax.swing.GroupLayout(jPanelConcept); jPanelConcept.setLayout(jPanelConceptLayout); jPanelConceptLayout.setHorizontalGroup( jPanelConceptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelConceptLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelConceptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtfnameConcept) .addGroup(jPanelConceptLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jbAddConcept)))) ); jPanelConceptLayout.setVerticalGroup( jPanelConceptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelConceptLayout.createSequentialGroup() .addComponent(jtfnameConcept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbAddConcept) .addGap(34, 34, 34)) ); jLabel6.setText("Range:"); jLabel7.setText("Domain:"); jbadData.setText("Add Data"); jbadData.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbadDataActionPerformed(evt); } }); javax.swing.GroupLayout jPanelDataLayout = new javax.swing.GroupLayout(jPanelData); jPanelData.setLayout(jPanelDataLayout); jPanelDataLayout.setHorizontalGroup( jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDataLayout.createSequentialGroup() .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtfDataRange) .addComponent(jtfDataDomain))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDataLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbadData) .addContainerGap()) ); jPanelDataLayout.setVerticalGroup( jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDataLayout.createSequentialGroup() .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfDataRange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(15, 15, 15) .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jtfDataDomain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbadData)) ); jLabel3.setText("Name:"); jbtSave.setText("Save"); jbtSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtSaveActionPerformed(evt); } }); jMenu1.setText("File"); jmbtLoadOntology.setSelected(true); jmbtLoadOntology.setText("Load ontology"); jmbtLoadOntology.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmbtLoadOntologyActionPerformed(evt); } }); jMenu1.add(jmbtLoadOntology); jCheckBoxMenuItem2.setSelected(true); jCheckBoxMenuItem2.setText("Save"); jMenu1.add(jCheckBoxMenuItem2); jmbtExit.setSelected(true); jmbtExit.setText("Exit"); jmbtExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmbtExitActionPerformed(evt); } }); jMenu1.add(jmbtExit); jMenuBar1.add(jMenu1); jMenu2.setText("reasoner"); jCheckBoxMenuItem3.setSelected(true); jCheckBoxMenuItem3.setText("Hermit"); jMenu2.add(jCheckBoxMenuItem3); jCheckBoxMenuItem4.setSelected(true); jCheckBoxMenuItem4.setText("Pellet"); jMenu2.add(jCheckBoxMenuItem4); jMenuBar1.add(jMenu2); jmAbout.setText("About"); jmbtAbout.setSelected(true); jmbtAbout.setText("About"); jmbtAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmbtAboutActionPerformed(evt); } }); jmAbout.add(jmbtAbout); jMenuBar1.add(jmAbout); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelConcept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE) .addComponent(jPanelRole, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jbtSave))) .addGap(34, 34, 34)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jLabel2))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelRole, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelConcept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jPanelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtSave)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jmbtExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmbtExitActionPerformed System.exit(0); }//GEN-LAST:event_jmbtExitActionPerformed private void jmbtAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmbtAboutActionPerformed new About().setVisible(true); }//GEN-LAST:event_jmbtAboutActionPerformed private void jmbtLoadOntologyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmbtLoadOntologyActionPerformed JFileChooser fileChooser = new JFileChooser("\\home\\thangdn"); int returnValue = fileChooser.showOpenDialog(null); jtreeConcept.removeAll(); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); Global.iriFileInput = IRI.create(selectedFile); Global.knowledgeBase = new KnowledgeBase(Global.iriFileInput); OWLOntologyFormat format = Global.knowledgeBase.getOntologyManager().getOntologyFormat(Global.knowledgeBase.getOntology()); ConceptProcessing.createFrequentConceptsForFullVersion(Global.knowledgeBase); RoleProcessing.createFrequentRolesForFullVersion(Global.knowledgeBase); DataProcessing.createFrequentDatasForFullVersion(Global.knowledgeBase); jtreeConcept.setModel(new DefaultTreeModel(ConceptProcessing.top)); jTreeRole.setModel(new DefaultTreeModel(RoleProcessing.top)); jTreeData.setModel(new DefaultTreeModel(DataProcessing.top)); jtreeConcept.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } public void mousePressed ( MouseEvent e ) { if ( SwingUtilities.isRightMouseButton ( e ) ) { TreePath path = jtreeConcept.getPathForLocation ( e.getX (), e.getY () ); Rectangle pathBounds = jtreeConcept.getUI ().getPathBounds ( jtreeConcept, path ); if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) ) { JPopupMenu menu = new JPopupMenu (); JMenuItem menuItem = new JMenuItem(new AbstractAction("Add new individual") { public void actionPerformed(ActionEvent e) { System.out.print("xx"); } }); menu.add (menuItem); menu.show ( jtreeConcept, pathBounds.x, pathBounds.y + pathBounds.height ); } } } }); jTreeRole.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClickedRole(me); } public void mousePressed ( MouseEvent e ) { if ( SwingUtilities.isRightMouseButton ( e ) ) { TreePath path = jTreeRole.getPathForLocation ( e.getX (), e.getY () ); Rectangle pathBounds = jTreeRole.getUI ().getPathBounds ( jTreeRole, path ); if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) ) { JPopupMenu menu = new JPopupMenu (); JMenuItem menuItem = new JMenuItem(new AbstractAction("Add new Relationship") { public void actionPerformed(ActionEvent e) { System.out.print("xx"); } }); menu.add (menuItem); menu.show ( jTreeRole, pathBounds.x, pathBounds.y + pathBounds.height ); } } } }); jTreeData.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClickedData(me); } public void mousePressed ( MouseEvent e ) { if ( SwingUtilities.isRightMouseButton ( e ) ) { TreePath path = jTreeData.getPathForLocation ( e.getX (), e.getY () ); Rectangle pathBounds = jTreeData.getUI ().getPathBounds ( jTreeData, path ); if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) ) { JPopupMenu menu = new JPopupMenu (); JMenuItem menuItem = new JMenuItem(new AbstractAction("Add new Relationship") { public void actionPerformed(ActionEvent e) { System.out.print("xx"); } }); menu.add (menuItem); menu.show ( jTreeData, pathBounds.x, pathBounds.y + pathBounds.height ); } } } }); JPopupMenu popupMenu = new JPopupMenu(); popupMenu.add(new JMenuItem(new AbstractAction("Show") { public void actionPerformed(ActionEvent e) { //ConceptProcessing.createFrequentConceptsForFullVersion(Global.knowledgeBase); //RoleProcessing.createFrequentRolesForFullVersion(Global.knowledgeBase); //DataProcessing.createFrequentDatasForFullVersion(Global.knowledgeBase); InfoIndividualForm aa = new InfoIndividualForm(); aa.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); aa.setVisible(true); } })); popupMenu.add(new JPopupMenu.Separator()); popupMenu.add(new JMenuItem(new AbstractAction("Paste to Role's Domain") { public void actionPerformed(ActionEvent e) { jtfDomainRole.setText(InfoIndividualForm.nameIndividual); } })); popupMenu.add(new JMenuItem(new AbstractAction("Paste to Role's Range") { public void actionPerformed(ActionEvent e) { jtfRangeRole.setText(InfoIndividualForm.nameIndividual); } })); popupMenu.add(new JMenuItem(new AbstractAction("Paste to Data's Domain") { public void actionPerformed(ActionEvent e) { jtfDataDomain.setText(InfoIndividualForm.nameIndividual); } })); popupMenu.add(new JMenuItem("Clear")); lists.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (SwingUtilities.isRightMouseButton(me) && !lists.isSelectionEmpty() && lists.locationToIndex(me.getPoint()) == lists.getSelectedIndex()) { popupMenu.show(lists, me.getX(), me.getY()); InfoIndividualForm.nameIndividual= lists.getSelectedValue().toString(); } } } ); } }//GEN-LAST:event_jmbtLoadOntologyActionPerformed private void listsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listsValueChanged }//GEN-LAST:event_listsValueChanged private void jbAddConceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAddConceptActionPerformed for (OWLClass col : Global.knowledgeBase.getOntology().getClassesInSignature()) { if(Global.cutNameOfIRI(col.getIRI().toString()+">").equals(tp.getPathComponent(tp.getPathCount()-1).toString())) { OWLNamedIndividual mary = Global.knowledgeBase.getDataFactory().getOWLNamedIndividual(jtfnameConcept.getText(), Global.knowledgeBase.getPrefix()); OWLClassAssertionAxiom classAssertion = Global.knowledgeBase.getDataFactory().getOWLClassAssertionAxiom(col, mary); Global.knowledgeBase.getOntologyManager().addAxiom(Global.knowledgeBase.getOntology(), classAssertion); ConceptProcessing.addIndividualConcept(jtfnameConcept.getText(),Global.cutNameOfIRI(col.getIRI().toString())); break; } } }//GEN-LAST:event_jbAddConceptActionPerformed private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSaveActionPerformed try { Global.knowledgeBase.getOntologyManager().saveOntology(Global.knowledgeBase.getOntology()); } catch (OWLOntologyStorageException ex) { Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jbtSaveActionPerformed private void jbAddRoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAddRoleActionPerformed for (OWLObjectProperty col : Global.knowledgeBase.getOntology().getObjectPropertiesInSignature()) { if(Global.cutNameOfIRI(col.getIRI().toString()+">").equals(tprole.getPathComponent(tprole.getPathCount()-1).toString())) { OWLIndividual matthew = Global.knowledgeBase.getDataFactory().getOWLNamedIndividual(IRI.create(Global.knowledgeBase.getIRI().toString()+ "#" + jtfDomainRole.getText())); OWLIndividual peter = Global.knowledgeBase.getDataFactory().getOWLNamedIndividual(IRI.create(Global.knowledgeBase.getIRI().toString() + "#" + jtfRangeRole.getText())); OWLObjectPropertyAssertionAxiom assertion = Global.knowledgeBase.getDataFactory().getOWLObjectPropertyAssertionAxiom(col,matthew, peter); Global.knowledgeBase.getOntologyManager().addAxiom(Global.knowledgeBase.getOntology(), assertion); RoleProcessing.addIndividualRole(jtfDomainRole.getText(),jtfRangeRole.getText(),Global.cutNameOfIRI(col.getIRI().toString())); break; } } }//GEN-LAST:event_jbAddRoleActionPerformed private void jbadDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbadDataActionPerformed for (OWLDataProperty col : Global.knowledgeBase.getOntology().getDataPropertiesInSignature()) { if(Global.cutNameOfIRI(col.getIRI().toString()+">").equals(tpdata.getPathComponent(tpdata.getPathCount()-1).toString())) { OWLNamedIndividual A = Global.knowledgeBase.getDataFactory().getOWLNamedIndividual(IRI.create(Global.knowledgeBase.getIRI().toString()+ "#" + jtfDataDomain.getText())); OWLLiteral lit = factory.getOWLLiteral(jtfDataRange.getText()); OWLDataPropertyAssertionAxiom ax = factory.getOWLDataPropertyAssertionAxiom(col, A, lit); AddAxiom addAx = new AddAxiom(Global.knowledgeBase.getOntology(), ax); Global.knowledgeBase.getOntologyManager().applyChange(addAx); RoleProcessing.addIndividualRole(jtfDataDomain.getText(),jtfDataRange.getText(),Global.cutNameOfIRI(col.getIRI().toString())); break; } } }//GEN-LAST:event_jbadDataActionPerformed private TreePath tp; private void doMouseClicked(MouseEvent me) { //TreePath tp = jtreeConcept.getPathForLocation(me.getX(), me.getY()); tp=jtreeConcept.getPathForLocation(me.getX(), me.getY()); if (tp != null) { System.out.print(tp.getPathComponent(tp.getPathCount()-1).toString()); listConceptsValueChanged(tp); } } private TreePath tprole; private void doMouseClickedRole(MouseEvent me) { tprole=jTreeRole.getPathForLocation(me.getX(), me.getY()); if (tprole != null) { System.out.print(tprole.getPathComponent(tprole.getPathCount()-1).toString()); //listConceptsValueChanged(tprole); } } private TreePath tpdata; private void doMouseClickedData(MouseEvent me) { tpdata=jTreeData.getPathForLocation(me.getX(), me.getY()); if (tprole != null) { System.out.print(tpdata.getPathComponent(tpdata.getPathCount()-1).toString()); //listConceptsValueChanged(tprole); } } private void listConceptsValueChanged(TreePath tp) { // TODO add your handling code here: ConceptAssertion conceptAssertion = ConceptProcessing.getConceptAssertionFromFrequentConceptsFull(tp.getPathComponent(tp.getPathCount()-1).toString()); lists.removeAll(); if (conceptAssertion != null) { ConceptIndividuals individuals = conceptAssertion.getIndividuals(); Set<String> nameOfIndividuals = individuals.getIndividualsName(); DefaultListModel modelIndividuals = new DefaultListModel(); lists.setModel(modelIndividuals); modelIndividuals.clear(); for (String strNameIndividual : nameOfIndividuals) { modelIndividuals.addElement(strNameIndividual); } //lblIndividuals.setText("Individuals_concept: " + String.valueOf(nameOfIndividuals.size())); }else{ System.out.println("coceptAssertion null"); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(HomeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HomeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HomeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HomeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HomeForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem3; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu8; private javax.swing.JMenu jMenu9; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuBar jMenuBar2; private javax.swing.JPanel jPanelConcept; private javax.swing.JPanel jPanelData; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTree jTreeData; private javax.swing.JTree jTreeRole; private javax.swing.JButton jbAddConcept; private javax.swing.JButton jbAddRole; private javax.swing.JButton jbadData; private javax.swing.JButton jbtSave; private javax.swing.JMenu jmAbout; private javax.swing.JCheckBoxMenuItem jmbtAbout; private javax.swing.JRadioButtonMenuItem jmbtExit; private javax.swing.JCheckBoxMenuItem jmbtLoadOntology; private javax.swing.JTextField jtfDataDomain; private javax.swing.JTextField jtfDataRange; private javax.swing.JTextField jtfDomainRole; private javax.swing.JTextField jtfRangeRole; private javax.swing.JTextField jtfnameConcept; private javax.swing.JTree jtreeConcept; private javax.swing.JList lists; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package MDataProcessing.Assertion; import MCommon.Global; import MDataProcessing.Individual.ConceptIndividuals; import java.util.Objects; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; /** * * @author tdminh */ public class ConceptAssertion { @Override public int hashCode() { int hash = 5; hash = 41 * hash + Objects.hashCode(this.iriConcept); hash = 41 * hash + Objects.hashCode(this.individuals); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ConceptAssertion other = (ConceptAssertion) obj; if (!Objects.equals(this.iriConcept, other.iriConcept)) { return false; } if (!Objects.equals(this.individuals, other.individuals)) { return false; } return true; } private IRI iriConcept; private ConceptIndividuals individuals; public ConceptAssertion(IRI iriConcept, ConceptIndividuals individuals) { this.iriConcept = iriConcept; this.individuals = individuals; } public IRI getIRIConcept() { return this.iriConcept; } public String getConceptName() { return Global.cutNameOfIRI(this.iriConcept.toString()); } public ConceptIndividuals getIndividuals() { return this.individuals; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package MDataProcessing.Individual; /** * * @author DoTienChi */ public class RoleIndividual { private String strDomain, strRange; public RoleIndividual(String strDomain, String strRange) { this.strDomain = strDomain; this.strRange = strRange; } public String getDomain() { return strDomain; } public String getRange() { return strRange; } public String getId(){ return this.strDomain + this.strRange; } @Override public int hashCode(){ return this.getId().hashCode(); } public boolean equals (Object obj){ return ((obj instanceof RoleIndividual) && ( ((RoleIndividual) obj).strDomain.equals(this.strDomain))&& ((RoleIndividual)obj).strRange.equals(this.strRange) ); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package OWLapi; import MCommon.Global; import MDataProcessing.Assertion.ConceptAssertion; import MDataProcessing.Assertion.DataAssertion; import MDataProcessing.Assertion.RoleAssertion; import MDataProcessing.ConceptProcessing; import MDataProcessing.DataProcessing; import MDataProcessing.Individual.DataIndividual; import MDataProcessing.Individual.RoleIndividual; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.SystemColor; import java.awt.Toolkit; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * * @author thangdn */ public class InfoIndividualForm extends javax.swing.JFrame { public static String nameIndividual; private String mainNameIndividual; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); /** * Creates new form InfoIndividualForm */ public InfoIndividualForm() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(screenSize.width - 50 ,screenSize.height - 200); initComponents(); setIndivisual(InfoIndividualForm.nameIndividual); getInforIndividual(); } public void setIndivisual(String nameIndividual) { this.mainNameIndividual=nameIndividual; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 552, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 378, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void getInforIndividual() { JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(0,0,this.getSize().width-5,this.getSize().height); //scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); getContentPane().add(scrollPane); JPanel borderlaoutpanel = new JPanel(); scrollPane.setViewportView(borderlaoutpanel); borderlaoutpanel.setLayout(new BorderLayout(0, 0)); JPanel columnpanel = new JPanel(); borderlaoutpanel.add(columnpanel, BorderLayout.NORTH); columnpanel.setLayout(new GridLayout(0, 1, 0, 1)); columnpanel.setBackground(Color.gray); int i=0; for(ConceptAssertion a:Global.allFrequentConceptsFull) { for (String col : a.getIndividuals().getIndividualsName()) { if(col.equals(this.mainNameIndividual)) { JButton ka=new JButton(new AbstractAction(a.getConceptName()) { public void actionPerformed(ActionEvent e) { System.out.print("xx"); }}); JPanel rowPanel = new JPanel(); rowPanel.setPreferredSize(new Dimension(300,30)); columnpanel.add(rowPanel); rowPanel.setLayout(null); JLabel as = new JLabel(this.mainNameIndividual + " is "); as.setBounds(20, 5, 200, 23); rowPanel.add(as); ka.setBounds(200, 5, 200, 23); rowPanel.add(ka); if(i%2==0) rowPanel.setBackground(SystemColor.inactiveCaptionBorder); i++; } } } for(RoleAssertion a:Global.allFrequentRolesFull) { for (RoleIndividual col : a.getIndividuals().getIndividuals()) { if(col.getDomain().equals(this.mainNameIndividual)||col.getRange().equals(this.mainNameIndividual)) { JButton ka=new JButton(new AbstractAction(a.getRoleName()) { public void actionPerformed(ActionEvent e) { System.out.print("xx"); }}); JPanel rowPanel = new JPanel(); rowPanel.setPreferredSize(new Dimension(300,30)); columnpanel.add(rowPanel); rowPanel.setLayout(null); JLabel as = new JLabel(col.getDomain() + " "); as.setBounds(20, 5, 200, 23); rowPanel.add(as); ka.setBounds(200, 5, 200, 23); rowPanel.add(ka); JLabel ass = new JLabel(" "+col.getRange()); ass.setBounds(400, 5, 200, 23); rowPanel.add(ass); if(i%2==0) rowPanel.setBackground(SystemColor.inactiveCaptionBorder); i++; } } } for(DataAssertion a:Global.allFrequentDatasFull) { //if(DataProcessing.isLeaf(a.getDataName())) for (DataIndividual col : a.getIndividuals().getIndividuals()) { if(col.getDomain().equals(this.mainNameIndividual)||col.getRange().equals(this.mainNameIndividual)) { JButton ka=new JButton(new AbstractAction(a.getDataName()) { public void actionPerformed(ActionEvent e) { System.out.print("xx"); }}); JPanel rowPanel = new JPanel(); rowPanel.setPreferredSize(new Dimension(300,30)); columnpanel.add(rowPanel); rowPanel.setLayout(null); JLabel as = new JLabel(col.getDomain() + " "); as.setBounds(20, 5, 200, 23); rowPanel.add(as); ka.setBounds(200, 5, 200, 23); rowPanel.add(ka); JLabel ass = new JLabel(" "+col.getRange()); ass.setBounds(400, 5, 200, 23); rowPanel.add(ass); if(i%2==0) rowPanel.setBackground(SystemColor.inactiveCaptionBorder); i++; } } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InfoIndividualForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InfoIndividualForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InfoIndividualForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InfoIndividualForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InfoIndividualForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package MDataProcessing.Assertion; import MCommon.Global; import MDataProcessing.Individual.RoleIndividuals; import org.semanticweb.owlapi.model.IRI; /** * * @author tdminh */ public class RoleAssertion { private IRI iriRole; private RoleIndividuals individuals; public RoleAssertion(IRI iriRole, RoleIndividuals individuals) { this.iriRole = iriRole; this.individuals = individuals; } public IRI getIRIRole() { return this.iriRole; } public String getRoleName() { return Global.cutNameOfIRI(this.iriRole.toString()); } public RoleIndividuals getIndividuals() { return this.individuals; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package MDataProcessing.Individual; import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.IRI; /** * * @author tdminh */ public class ConceptIndividuals { private Set<String> individualsName; public ConceptIndividuals() { this.individualsName = new HashSet<String>(); } public Set<String> getIndividualsName() { return this.individualsName; } public void addIndividual(String strIndividual) { this.individualsName.add(strIndividual); } public boolean checkIndividual(String strIndividual) { return this.individualsName.contains(strIndividual); } public int size() { return individualsName.size(); } }
8ba28b33c5726f3897da104f6f17c3cf736ab546
[ "Java" ]
6
Java
gsanou/owlapi-1
60bb326520648bf1c4fd85caa97891b15e41c798
8b3e18818705e50c9f6bff5559faf6dc5c2805b5
refs/heads/master
<repo_name>tetsuhiko-dev/sw-runes-builder<file_sep>/js/summoner_war.js const monstersJson = require('../datas/monsters.json'); const runeUpgradeJson = require('../datas/runeUpgrade.json'); const runeEffectJson = require('../datas/runeEffect.json'); const _ = require('lodash') const baseArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; class Monsters { #monsters; constructor() { this.#monsters = monstersJson; } filter(name, element, starStr) { let star = parseInt(starStr); return this.#monsters.filter(monster => this.#filterFunc(monster, name, element, starStr)).sort(this.#sort); } get(idStr) { let id = parseInt(idStr); return this.#monsters.find(monster => monster.Id === id); } #filterFunc(monster, name, element, starStr) { let useName = name?.length !== 0; let useElement = element?.length !== 0; let useStar = starStr?.length !== 0; let star = useStar ? parseInt(starStr) : null; let checkName = monster.Name.toLowerCase().includes(name); let checkNameAwaken = monster.NameAwaken.toLowerCase().includes(name); let checkElement = monster.Element === element; let checkStar = monster.Star === star; let result = true; if (useName) { result = result && (checkName || checkNameAwaken); } if (useElement) { result = result && checkElement; } if (useStar) { result = result && checkStar; } return result; } #sort(a, b) { if (a.Star > b.Star) return -1; if (a.Star < b.Star) return 1; if (a.Name < b.Name) return -1; if (a.Name > b.Name) return 1; if (a.NameAwaken < b.NameAwaken) return -1; if (a.NameAwaken > b.NameAwaken) return 1; } } class BonusStats { rune1; rune2; rune3; rune4; rune5; rune6; constructor() { } slot1(value) { this.rune1 = new Rune(1, value); } slot2(value) { this.rune2 = new Rune(2, value); } slot3(value) { this.rune3 = new Rune(3, value); } slot4(value) { this.rune4 = new Rune(4, value); } slot5(value) { this.rune5 = new Rune(5, value); } slot6(value) { this.rune6 = new Rune(6, value); } stats0(){ return [this.rune1.rune.stat0.value, this.rune2.rune.stat0.value, this.rune3.rune.stat0.value, this.rune4.rune.stat0.value, this.rune5.rune.stat0.value, this.rune6.rune.stat0.value]; } getBonusIndex(){ let group = _.groupBy([this.rune1, this.rune2, this.rune3, this.rune4, this.rune5, this.rune6], "rune.type"); let bonusIndex = []; Object.keys(group).forEach(keyStr => { let key = parseInt(keyStr); for(let i=0; key !== -1 && i<Math.floor(group[keyStr].length / runeEffectJson[key].count);i++){ bonusIndex.push(key); } }); return bonusIndex; } getBonusRunes() { let group = _.groupBy([this.rune1, this.rune2, this.rune3, this.rune4, this.rune5, this.rune6], "rune.type"); let bonus = _.cloneDeep(baseArray); Object.keys(group).forEach(keyStr => { let key = parseInt(keyStr); if(key !== -1 && runeEffectJson[key].stat !== -1){ bonus[runeEffectJson[key].stat] = runeEffectJson[key].value * Math.floor(group[keyStr].length / runeEffectJson[key].count); } }); return bonus; } result() { return [this.rune1.getStatsArray(),this.rune2.getStatsArray(),this.rune3.getStatsArray(), this.rune4.getStatsArray(),this.rune5.getStatsArray(),this.rune6.getStatsArray(), this.getBonusRunes()].reduce((a, b) => a.map((c, i) => c + b[i])); } } class Rune { type; rune; constructor(slot, rune) { this.rune = rune; if (this.rune.stat0.id === -1) return; this.rune.stat0.value = this.rune.level === 15 ? runeUpgradeJson[this.rune.stat0.id][this.rune.star - 1].max : runeUpgradeJson[this.rune.stat0.id][this.rune.star - 1].base + runeUpgradeJson[this.rune.stat0.id][this.rune.star - 1].increment * this.rune.level; } getStatsArray() { let stats = _.cloneDeep(baseArray); if(this.rune.innate.id !== -1){ stats[this.rune.innate.id] = this.rune.innate.value; } if (this.rune.stat0.id !== -1) { stats[this.rune.stat0.id] = this.rune.stat0.value; } if (this.rune.stat1.id !== -1) { stats[this.rune.stat1.id] = this.rune.stat1.value; } if (this.rune.stat2.id !== -1) { stats[this.rune.stat2.id] = this.rune.stat2.value; } if (this.rune.stat3.id !== -1) { stats[this.rune.stat3.id] = this.rune.stat3.value; } if (this.rune.stat4.id !== -1) { stats[this.rune.stat4.id] = this.rune.stat4.value; } return stats; } } module.exports.Monsters = Monsters; module.exports.BonusStats = BonusStats;<file_sep>/js/preload.js const IpcRenderer = require('electron').ipcRenderer; const Remote = require('electron').remote; const $ = require('jquery'); const _ = require('lodash'); const logger = require('electron-log') let currentMonster = undefined; $(document).ready(function () { $("#close").on("click", function () { Remote.getCurrentWindow().close(); }); }); // **************** FILTER ********************* // $(document).ready(function () { $('#name-field').on('input', onFilterChange); $('#element-field').on('change', onFilterChange); $('#star-field').on('change', onFilterChange); onFilterChange(); }); function onFilterChange() { let name = $('#name-field').val(); let element = $('#element-field').val(); let star = $('#star-field').val(); IpcRenderer.send("filterMonsterRequest", {name: name, element: element, star: star}); } IpcRenderer.on('filterMonsterResult', (event, arg) => { $("#monster-list").empty(); arg.forEach(monster => { if (monster) { let html = drawMonsterCard(monster); $("#monster-list").append(html); } }); $(".card-monster").on("click", onClickMonster); }); function drawMonsterCard(monster) { let name = monster.Name; let nameAwaken = monster.NameAwaken; let element = monster.Element; let star = monster.Star; let url0 = monster.ImageBase; let url1 = monster.ImageAwaken; let starHmtl = ""; for (let i = 1; i <= star; i++) { starHmtl += "<span class='base-text-color' style=\"font-size: 15px;\"><i class=\"fas fa-star\"></i></span>\n"; } let card = "<div monster-id='" + monster.Id + "' class=\"card mb-3 mr-2 ml-2 card-monster\" style=\"max-width: 540px; max-height: 100px\">\n" + " <div class=\"row no-gutters\">\n" + " <div class=\"col-md-3 p-2\">\n" + " <img src=\"images/monsters/" + url0 + "\" class=\"card-img rounded-circle\">\n" + " </div>\n" + " <div class=\"col-md-3 p-2\">\n" + " <img src=\"images/monsters/" + url1 + "\" class=\"card-img rounded-circle\">\n" + " </div>\n" + " <div class=\"col-md-6 pl-1 mt-1\">\n" + " <h5 class=\"card-title mb-1 text-center base-text-color\">" + name + "</h5>\n" + " <h5 class=\"card-title mb-1 text-center awaken-text-color\">" + nameAwaken + "</h5>\n" + " <div class=\"text-center\">\n" + " <img src=\"images/icons/" + element + ".png\" class=\"card-img rounded-circle img-icon\">\n" + starHmtl + " </div>\n" + " </div>\n" + " </div>\n" + " </input>"; return card; } // ********************************************* // // ****************** Monster ***************** // function onClickMonster() { try { a = 8/0; IpcRenderer.send('getMonsterRequest', $(this).attr("monster-id")); } catch (e) { logger.error(e); } } IpcRenderer.on('getMonsterResult', (event, arg) => { currentMonster = arg; $("#monster-name").text(currentMonster.Name); $("#monster-name-awaken").text(currentMonster.NameAwaken); $("#monster-element").empty().append('<img src="images/icons/' + currentMonster.Element + '.png" class="card-img rounded-circle img-element">'); let star = ""; for (let i = 1; i <= currentMonster.Star; i++) { star += '<span class="base-text-color" style="font-size: 20px;"><i class="fas fa-star"></i></span>\n'; } $("#monster-star").empty().append(star).append('<span class="pl-2" style="font-size: 20px">' + currentMonster.Type + '</span>'); let imgs = '<div class="col-md-6 pl-2 pb-2">\n' + ' <img src="images/monsters/' + currentMonster.ImageBase + '" class="card-img rounded-circle img-monster">\n' + ' </div>\n' + ' <div class="col-md-6 pl-2 pb-2">\n' + ' <img src="images/monsters/' + currentMonster.ImageAwaken + '" class="card-img rounded-circle img-monster">\n' + ' </div>'; if (currentMonster.HasSecondAwaken) { imgs = '<div class="col-md-4 pl-2 pb-2">\n' + ' <img src="images/monsters/' + currentMonster.ImageBase + '" class="card-img rounded-circle img-monster">\n' + ' </div>\n' + ' <div class="col-md-4 pl-2 pb-2">\n' + ' <img src="images/monsters/' + currentMonster.ImageAwaken + '" class="card-img rounded-circle img-monster">\n' + ' </div>' + ' <div class="col-md-4 pl-2 pb-2">\n' + ' <img src="images/monsters/' + currentMonster.ImageAwakenSecond + '" class="card-img rounded-circle img-monster">\n' + ' </div>'; } $("#monster-img").empty().append(imgs); $("#input-star").empty(); for (let i = currentMonster.Star; i <= 6; i++) { let option = ''; if (i === 6) { option = '<option selected value="' + i + '">' + i + '*</option>'; } else { option = '<option value="' + i + '">' + i + '*</option>'; } $("#input-star").append(option); } $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="40">40</option>'); if (currentMonster.HasSecondAwaken) { $("#input-awaken").empty().append('<option value="0">Base</option>') .append('<option value="1">Awaken</option>') .append('<option selected value="2">Second Awaken</option>'); } else { $("#input-awaken").empty().append('<option value="0">Base</option>') .append('<option selected value="1">Awaken</option>'); } updateStat(); $(".main-div").removeClass('hide'); }); $(document).ready(function () { $("#input-star").on('change', function () { let star = parseInt($(this).val()); if (star === 1) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="15">15</option>'); } else if (star === 2) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="20">20</option>'); } else if (star === 3) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="25">25</option>'); } else if (star === 4) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="30">30</option>'); } else if (star === 5) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="35">35</option>'); } else if (star === 6) { $("#input-level").empty().append('<option value="1">1</option>') .append('<option selected value="40">40</option>'); } updateStat(); }); $("#input-level").on("change", updateStat); $("#input-awaken").on("change", updateStat); }); function updateStat() { let star = parseInt($("#input-star").val()); let level = parseInt($("#input-level").val()); let awaken = parseInt($("#input-awaken").val()); let statsMinor = undefined; let statsMajor = undefined; if (awaken === 0) { statsMinor = currentMonster.BaseMinorStats; statsMajor = currentMonster.BaseMajorStats.find(stats => stats.Level === level && stats.Star === star); } else if (awaken === 1) { statsMinor = currentMonster.AwakenMinorStats; statsMajor = currentMonster.AwakenMajorStats.find(stats => stats.Level === level && stats.Star === star); } else if (awaken === 2) { statsMinor = currentMonster.AwakenSecondMinorStats; statsMajor = currentMonster.AwakenSecondMajorStats.find(stats => stats.Level === level && stats.Star === star); } $("#base-hp").text(statsMajor.HealthPoint); $("#base-atk").text(statsMajor.Attack); $("#base-def").text(statsMajor.Defense); $("#base-spd").text(statsMinor.Speed); $("#base-crir").text(statsMinor.CriticalRate + '%'); $("#base-crid").text(statsMinor.CriticalDamage + '%'); $("#base-res").text(statsMinor.Resistance + '%'); $("#base-acc").text(statsMinor.Accuracy + '%'); updateTotalCalculation(); } function updateRuneCalculated() { runeCalculationFixe("hp"); runeCalculationFixe("atk"); runeCalculationFixe("def"); runeCalculationFixe("spd"); runeCalculationPer("crir"); runeCalculationPer("crid"); runeCalculationPer("res"); runeCalculationPer("acc"); updateTotalCalculation(); } function updateTotalCalculation() { $("#total-hp").text(parseInt($("#base-hp").text()) + parseInt($("#calculated-hp").text())); $("#total-atk").text(parseInt($("#base-atk").text()) + parseInt($("#calculated-atk").text())); $("#total-def").text(parseInt($("#base-def").text()) + parseInt($("#calculated-def").text())); $("#total-spd").text(parseInt($("#base-spd").text()) + parseInt($("#calculated-spd").text())); $("#total-crir").text(parseInt($("#base-crir").text().replace('%', '')) + parseInt($("#calculated-crir").text().replace('%', '')) + '%'); $("#total-crid").text(parseInt($("#base-crid").text().replace('%', '')) + parseInt($("#calculated-crid").text().replace('%', '')) + '%'); $("#total-res").text(parseInt($("#base-res").text().replace('%', '')) + parseInt($("#calculated-res").text().replace('%', '')) + '%'); $("#total-acc").text(parseInt($("#base-acc").text().replace('%', '')) + parseInt($("#calculated-acc").text().replace('%', '')) + '%'); } function runeCalculationFixe(stat) { let baseInt = parseInt($("#base-" + stat).text().replace('%', '')); let fixeInt = parseInt($("#modified-" + stat + "-fixe").text().replace('%', '')); let perInt = parseInt($("#modified-" + stat + "-per").text().replace('%', '')); let leader = parseInt($("#leader-" + stat).text().replace('%', '')); let resultInt = Math.round((baseInt * (perInt + leader) / 100.0 + fixeInt)); $("#calculated-" + stat).text(resultInt); } function runeCalculationPer(stat) { let perInt = parseInt($("#modified-" + stat + "-per").text().replace('%', '')); let perInt2 = parseInt($("#leader-" + stat).text().replace('%', '')); let resultInt = perInt2 + perInt; $("#calculated-" + stat).text(resultInt); } // ********************************************* // const defaultStats = ["HP", "%HP", "Atk", "%Atk", "Def", "%Def", "Speed", "Cri Rate", "Cri Dmg", "Res", "Acc"] const defaultInnate = ["Strong", "Tenacious", "Ferocious", "Powerful", "Sturdy", "Durable", "Quick", "Fatal", "Cruel", "Resistant", "Intricate"] const defaultRuneStats = [null, ["", "", "Atk", "", "", "", "", "", "", "", ""], ["HP", "%HP", "Atk", "%Atk", "Def", "%Def", "Speed", "", "", "", ""], ["", "", "", "", "Def", "", "", "", "", "", ""], ["HP", "%HP", "Atk", "%Atk", "Def", "%Def", "", "Cri Rate", "Cri Dmg", "", ""], ["HP", "", "", "", "", "", "", "", "", "", ""], ["HP", "%HP", "Atk", "%Atk", "Def", "%Def", "", "", "", "Res", "Acc"]]; let rune_stat = [null, _.cloneDeep(defaultStats), _.cloneDeep(defaultStats), _.cloneDeep(defaultStats), _.cloneDeep(defaultStats), _.cloneDeep(defaultStats), _.cloneDeep(defaultStats)]; let rune_innate = [null, _.cloneDeep(defaultInnate), _.cloneDeep(defaultInnate), _.cloneDeep(defaultInnate), _.cloneDeep(defaultInnate), _.cloneDeep(defaultInnate), _.cloneDeep(defaultInnate)]; let rune_primary_stat = _.cloneDeep(defaultRuneStats); function getStar(slot) { return $("#rune" + slot + "-star"); } function getType(slot) { return $("#rune" + slot + "-type"); } function getLevel(slot) { return $("#rune" + slot + "-level"); } function getStatType(slot, id) { return $("#rune" + slot + "-stat" + id); } function getStatValue(slot, id) { return $("#rune" + slot + "-stat" + id + "-value"); } function getStatText(slot, id) { return $("#rune" + slot + "-stat" + id + "-text"); } function getInnate(slot) { return $("#rune" + slot + "-innate"); } function getInnateValue(slot) { return $("#rune" + slot + "-innate-value"); } function getInnateText(slot) { return $("#rune" + slot + "-innate-text"); } function getRune(slot) { let type = parseInt(getType(slot).val()); let star = parseInt(getStar(slot).val()); let level = parseInt(getLevel(slot).val()); let stat0 = parseInt(getStatType(slot, 0).val()); let innate = parseInt(getInnate(slot).val()); let innateValue = parseInt(getInnateValue(slot).val()); let stat1 = parseInt(getStatType(slot, 1).val()); let stat1Value = parseInt(getStatValue(slot, 1).val()); let stat2 = parseInt(getStatType(slot, 2).val()); let stat2Value = parseInt(getStatValue(slot, 2).val()); let stat3 = parseInt(getStatType(slot, 3).val()); let stat3Value = parseInt(getStatValue(slot, 3).val()); let stat4 = parseInt(getStatType(slot, 4).val()); let stat4Value = parseInt(getStatValue(slot, 4).val()); return { type: type, star: star, level: level, stat0: {id: stat0, value: 0}, innate: {id: innate, value: innateValue}, stat1: {id: stat1, value: stat1Value}, stat2: {id: stat2, value: stat2Value}, stat3: {id: stat3, value: stat3Value}, stat4: {id: stat4, value: stat4Value} }; } function setStatOption(slot, id, options) { let select = getStatType(slot, id); let index = parseInt(select.val()); select.empty(); if (index === -1) { select.append('<option value="-1" selected>Stat</option>'); } else { select.append('<option value="-1">Stat</option>'); } for (let i = 0; i < options.length; i++) { if (options[i] === "" && index !== i) continue; if (index === i) { let option = options[i] === "" ? defaultStats[i] : options[i]; select.append('<option value="' + i + '" selected>' + option + '</option>'); } else { select.append('<option value="' + i + '">' + options[i] + '</option>'); } } } function setInnateOption(slot, options) { let select = getInnate(slot); let index = parseInt(select.val()); select.empty(); if (index === -1) { select.append('<option value="-1" selected>Innate</option>'); } else { select.append('<option value="-1">Innate</option>'); } for (let i = 0; i < options.length; i++) { if (options[i] === "" && index !== i) continue; if (index === i) { let option = options[i] === "" ? defaultInnate[i] : options[i]; select.append('<option value="' + i + '" selected>' + option + '</option>'); } else { select.append('<option value="' + i + '">' + options[i] + '</option>'); } } } $(document).ready(function () { for (let s = 1; s <= 6; s++) { for (let i = 0; i < 5; i++) { getStatType(s, i).on("change", function () { let oldValue = parseInt($(this).data('val')); let newValue = parseInt($(this).val()); $(this).data('val', newValue); if (oldValue !== -1) { rune_primary_stat[s][oldValue] = defaultRuneStats[s][oldValue]; rune_stat[s][oldValue] = defaultStats[oldValue]; rune_innate[s][oldValue] = defaultInnate[oldValue] } rune_primary_stat[s][newValue] = ""; rune_stat[s][newValue] = ""; rune_innate[s][newValue] = ""; for (let j = 0; j < 5; j++) { if (i === j) continue; setStatOption(s, j, j===0?rune_primary_stat[s] : rune_stat[s]); } setInnateOption(s, rune_innate[s]); sendRunes(); }); getStatValue(s, i).on('change', function () { sendRunes(); }); } getInnateValue(s).on('change', function () { sendRunes(); }); getInnate(s).on('change', function () { let oldValue = parseInt($(this).data('val')); let newValue = parseInt($(this).val()); $(this).data('val', newValue); if (oldValue !== -1) { rune_primary_stat[s][oldValue] = defaultRuneStats[s][oldValue]; rune_stat[s][oldValue] = defaultStats[oldValue]; rune_innate[s][oldValue] = defaultInnate[oldValue] } rune_primary_stat[s][newValue] = ""; rune_stat[s][newValue] = ""; rune_innate[s][newValue] = ""; getInnateText(s).text((defaultStats[newValue] === undefined ? "" : defaultStats[newValue])); for (let j = 0; j < 5; j++) { setStatOption(s, j, j===0?rune_primary_stat[s] : rune_stat[s]); } sendRunes(); }); getLevel(s).on('change', function () { sendRunes(); }); getType(s).on('change', function () { sendRunes(); }); getStar(s).on('change', function () { sendRunes(); }); } }); function sendRunes() { let array = [getRune(1), getRune(2), getRune(3), getRune(4), getRune(5), getRune(6)]; IpcRenderer.send('sendRuneRequest', array); } IpcRenderer.on('sendRuneResult', ((event, args) => { $('#modified-hp-fixe').text(args[0]); $('#modified-hp-per').text(args[1] + "%"); $('#modified-atk-fixe').text(args[2]); $('#modified-atk-per').text(args[3] + "%"); $('#modified-def-fixe').text(args[4]); $('#modified-def-per').text(args[5] + "%"); $('#modified-spd-fixe').text(args[6]); $('#modified-spd-per').text(args[11] + "%"); $('#modified-crir-per').text(args[7] + "%"); $('#modified-crid-per').text(args[8] + "%"); $('#modified-res-per').text(args[9] + "%"); $('#modified-acc-per').text(args[10] + "%"); updateRuneCalculated(); })); IpcRenderer.on('sendStats0', (event, args) => { for (let i = 0; i < args.length; i++) { getStatValue(i + 1, 0).val(args[i]); } updateRuneCalculated(); }); IpcRenderer.on('sendRuneBonusIndex', (event, args) => { let imgs = ''; for(let i=0; i<args.length; i++){ imgs += '<img src="images/icons/Effect{}.png" width="25" height="25">'.format(args[i]); } let html = '<span style="font-size: 17px">Runes Set : {}</span>'.format(imgs); $("#rune-effect").empty().append(html); }); // UPDATER IpcRenderer.on('update-available', (event, args) => { $("#update-check").addClass("hide"); $("#update-available").removeClass("hide"); }); IpcRenderer.on('update-not-available', (event, args) => { document.location = "index.html"; }); IpcRenderer.on('update-progress', (event, info) => { let progress = info.percent; let speed = (info.bytesPerSecond / 1000000.0).toFixed(2); let total_second = (info.total - info.transferred) / info.bytesPerSecond; let minutes = Math.floor(total_second / 60); let seconds = Math.floor(total_second % 60); $("#progress-bar").css('width', progress+'%'); $("#progress-speed").text("{} MB/s - {} min {} sec".format(speed, minutes, seconds)); }); $(document).ready(function () { $("#update-yes").on('click', function () { $("#update-available").addClass("hide"); $("#update-progress").removeClass("hide"); IpcRenderer.send('update-download'); }); $("#update-no").on('click', function () { document.location = "index.html"; }); IpcRenderer.on("app-version", (event, args) =>{ $("#title").text("Summoner Wars : Runes Builder - v{}".format(args.version)); }); IpcRenderer.send("app-version"); });<file_sep>/README.md # Summoners War : Runes Builder This app allow you to create and test all the runes builds you want ! If you have any bug, feel free to send an issue with `bug` tag's :smile: If you want a feature, feel free to send an issue with `feature request` tag's :smile:
2d512d619c32e6f2ea1a61c2557aa928d509ded5
[ "JavaScript", "Markdown" ]
3
JavaScript
tetsuhiko-dev/sw-runes-builder
a85f2b2d644bef27a0e22d88910edc2db8e739be
f9bb13396e04dad70976fbef88dcab77e0cbdffc
refs/heads/master
<file_sep> # print Hello # # This functions prints Hello # @param fname # @param last-name # @examples # hello (fname="Rashid",last_name ="Ali") hello <- function (fname , last_name ) { cat (paste("Hello ",fname,last_name)) }
103e5cd5b6bddd8394d2890c2a9f62c4b841e628
[ "R" ]
1
R
IBC-RashidAli/rpackage
00f8802f994c09d59bdd06f1e0d94619b63d2281
ab8f475ecb391597ff2840b5f52937be0376b998
refs/heads/main
<file_sep>import React from "react"; const ProfileTable = ({profiles, getProfiles, getProfileDetails}) => { const renderHeader = () => { let headerElement = ['name', 'height', 'mass'] return headerElement.map((key, index) => { return <th key={index}>{key.toUpperCase()}</th> }) } const renderBody = () => { return profiles && profiles.results && profiles.results.map(profile => { return ( <tr onClick={() => getProfileDetails(profile)}> <td>{profile.name}</td> <td>{profile.height}</td> <td>{profile.mass}</td> </tr> ) }) } return ( <div className="profile-list"> <table> <thead> <tr>{renderHeader()}</tr> </thead> <tbody> {renderBody()} </tbody> </table> <button onClick={() => getProfiles(profiles.previous)} disabled={!profiles.previous}>previous</button> <button onClick={() => getProfiles(profiles.next)} disabled={!profiles.next}>next</button> </div> ) } export default ProfileTable;<file_sep>import React from "react"; import FilmList from './FilmList'; const ProfileDetails = ({id, name, birth_year, gender, films}) => { return ( <div id={id} className="profile-details"> <div>Name: {name}</div> <div>Birth year: {birth_year}</div> <div>Gender: {gender}</div> <br /> <div> List of Films: <FilmList films={films} /> </div> </div> ) } export default ProfileDetails;<file_sep> import React, { useState, useEffect } from "react"; /* services */ import profileService from './services/profiles' /* components */ import ProfileTable from './components/ProfileTable'; import ProfileDetails from './components/ProfileDetails'; import './App.css'; function App() { const [profiles, setProfiles] = useState([]) const [currentProfile, setCurrentProfile] = useState(null) const getProfiles = ( url ) => { profileService.getByUrl( url ) .then((profiles) => { setProfiles(profiles) }) } const getProfileDetails = async ( profile ) => { setCurrentProfile(profile); } useEffect(() => { profileService.getAll() .then((profiles) => { setProfiles(profiles) }) }, []) return ( <div className="App"> <ProfileTable profiles={profiles} getProfiles={getProfiles} getProfileDetails={getProfileDetails}/> <ProfileDetails {...currentProfile} /> </div> ); } export default App; <file_sep>import React from "react"; import FilmItem from './FilmItem'; const FilmList = ({films}) => { return ( <ul className="film-list"> {films && films.map(film => <li><FilmItem key={film} url={film} /></li> )} </ul> ) } export default FilmList;<file_sep>import axios from 'axios' const baseURL = "https://swapi.dev" /** * Get a list of all people from the api * @return {Promise} Promise that will resolve to the response data */ const getAll = async () => { const response = await axios.get(baseURL + "/api/people/") return response.data } const getByUrl = async (url) => { const response = await axios.get(url) return response.data } export default {getAll, getByUrl}<file_sep>import React, { useEffect, useState } from "react"; import filmService from '../services/films' const FilmItem = ({url}) => { const [filmDetails, setFilmDetails] = useState(null) useEffect( async () => { setFilmDetails( await filmService.getFilmDetails(url) ) },[url]) return ( <div className="film"> {filmDetails && filmDetails.title || 'loading...'} </div> ) } export default FilmItem;
950a1dab8bb4ed4e11bdabcf081fd08aead719e0
[ "JavaScript" ]
6
JavaScript
kentkobi/starwars-directory
a80dd94bd3fa67abbe3ff56f0a7764a4744c83bc
663bdd386e2718f14a25b35928644d19cbbaf558
refs/heads/master
<repo_name>acheng96/map-routes<file_sep>/README.md # map-routes Exploring Google Maps route drawing <file_sep>/map-routes/map-routes/MapViewController.swift // // MapViewController.swift // map-routes // // Created by <NAME> on 2/15/17. // Copyright © 2017 AnnieCheng. All rights reserved. // import UIKit import GoogleMaps class MapViewController: UIViewController, GMSMapViewDelegate { var mapView: GMSMapView! override func viewDidLoad() { super.viewDidLoad() let camera = GMSCameraPosition.camera(withLatitude: 42.446916, longitude: -76.484639, zoom: 15) let mapView = GMSMapView.map(withFrame: .zero, camera: camera) mapView.delegate = self self.mapView = mapView view = mapView } }
1d5e556c3536de2112d2068b84143ccc566dc7ff
[ "Markdown", "Swift" ]
2
Markdown
acheng96/map-routes
8fe6f1f8cfbb069d0709e15adb832090495e536d
c5c1cabc2c776189a7c13f2fff7ea59bbbf4964e
refs/heads/master
<repo_name>TomHarrop/readfish-test<file_sep>/test_commands.sh #!/usr/bin/env bash set -eux # testing only! mount the reads directory, e.g. sshfs -o ro host:/path data/reads # open the shell # add the following to troubleshoot? # -B toml:/opt/ont/minknow/conf/package/sequencing \ singularity shell \ --writable-tmpfs \ --nv \ -B tmp/var:/var,tmp/run:/run \ readfish_14ddf60.sif # something is happening with the singularity filesystem overlay. When I run # MinKNOW once inside the container, it won't detect the changes to the .toml # file. The only way I can get it to detect them is to add the toml file in a new # container, reboot the system and run again. find /tmp -iname "*minknow*" -type f rm -rf tmp/var/* tmp/run/* rm -rf ~/.singularity/cache/ rm -rf ~/.singularity/ # sudo rm -rf /root/.singularity/ singularity shell \ --nv \ -B tmp/var:/var,tmp/run:/run \ simulation.sif # do i need --writable-tmpfs \ # launch the gui nohup bash -c \ '/opt/ont/minknow/bin/mk_manager_svc & /opt/ont/ui/kingfisher/MinKNOW' &> /var/ui.log & # old version < 20 nohup bash -c \ '/opt/ont/minknow/bin/mk_manager_svc & /opt/ont/minknow-ui/MinKNOW' &> /var/ui.log & # launch a guppy server (to test) nohup guppy_basecall_server \ --port 5555 \ --log_path /var/guppy_server \ --config /opt/ont/guppy/data/dna_r9.4.1_450bps_hac.cfg \ --device "cuda:0" \ &> /var/guppy_server.log & # old version (3.4.5) nohup /guppy/bin/guppy_basecall_server \ --port 5555 \ --log_path /var/guppy_server \ --config /guppy/data/dna_r9.4.1_450bps_hac.cfg \ --device "cuda:0" \ &> /var/guppy_server.log & # edit /opt/ont/minknow/conf/package/sequencing/sequencing_MIN106_DNA.toml # /home/tom/Projects/readfish-test/data/reads/FAL06258_67bb20e2_42.fast5 cp \ toml/sequencing_MIN106_DNA.toml \ /opt/ont/minknow/conf/package/sequencing/ # check it cat /opt/ont/minknow/conf/package/sequencing/sequencing_MIN106_DNA.toml # start run in minknow (can leave basecalling off) # TEST UNBLOCK # WORKS in ubuntu 18.04 image with readfish 77c11e2 readfish unblock-all \ --device MN30649 \ --experiment-name "Testing ReadFish Unblock All" # works up to readfish point # readfish 0.0.5a3 has an error about the --cache parameter # readfish from the tidy branch (commit 77c11e2) doesn't install pyguppyclient properly # TEST MINIMAP # start a guppy server (does it work inside container?) nohup bash -c \ 'guppy_basecall_server \ --port 5557 \ --log_path guppy_server_log \ --flowcell "FLO-MIN106" \ --kit "SQK-LSK109" \ --device "cuda:0" ' \ &> /var/guppy_server.log & # index the human genome, wtf? minimap2 -x map-ont -d data/reference.mmi data/GRCh38_latest_genomic.fna # check the toml file readfish validate toml/human_chr_selection.toml # try read until # WORKS! but way too slow # 2020-10-20 16:31:10,674 ru.ru_gen 48R/0.47153s # 2020-10-20 16:31:11,787 ru.ru_gen 71R/1.11320s # 2020-10-20 16:31:13,672 ru.ru_gen 142R/1.88378s # 2020-10-20 16:31:15,332 ru.ru_gen 156R/1.65936s # 2020-10-20 16:31:17,089 ru.ru_gen 159R/1.75595s # 2020-10-20 16:31:18,910 ru.ru_gen 158R/1.81971s # 2020-10-20 16:31:20,893 ru.ru_gen 160R/1.98052s # 2020-10-20 16:31:23,004 ru.ru_gen 157R/2.10987s # 2020-10-20 16:31:25,203 ru.ru_gen 157R/2.19829s # 2020-10-20 16:31:28,259 ru.ru_gen 164R/3.05491s # 2020-10-20 16:31:31,521 ru.ru_gen 162R/3.26116s # 2020-10-20 16:31:35,626 ru.ru_gen 162R/4.10308s # 2020-10-20 16:31:39,873 ru.ru_gen 162R/4.24531s # 2020-10-20 16:31:44,415 ru.ru_gen 134R/4.54154s # 2020-10-20 16:31:52,295 ru.ru_gen 145R/7.87831s readfish targets \ --device MN30649 \ --experiment-name "RU Test basecall and map" \ --toml toml/human_chr_selection.toml \ --log-file /var/ru_test.log # change model to fast -> works better # performance gradually degrades. need to try a faster setup # 2020-10-20 16:38:00,086 ru.ru_gen 45R/0.22684s # 2020-10-20 16:38:00,505 ru.ru_gen 47R/0.24472s # 2020-10-20 16:38:00,946 ru.ru_gen 56R/0.28537s # 2020-10-20 16:38:01,320 ru.ru_gen 49R/0.25801s # 2020-10-20 16:38:01,847 ru.ru_gen 67R/0.38474s # 2020-10-20 16:38:02,044 ru.ru_gen 25R/0.18057s # 2020-10-20 16:38:02,542 ru.ru_gen 59R/0.27796s # 2020-10-20 16:38:02,900 ru.ru_gen 43R/0.23589s # 2020-10-20 16:38:03,301 ru.ru_gen 40R/0.23518s # 2020-10-20 16:38:03,799 ru.ru_gen 57R/0.33295s # 2020-10-20 16:38:04,080 ru.ru_gen 33R/0.21257s # 2020-10-20 16:38:04,512 ru.ru_gen 47R/0.24469s # 2020-10-20 16:38:05,026 ru.ru_gen 46R/0.35670s # 2020-10-20 16:38:05,338 ru.ru_gen 58R/0.26815s # 2020-10-20 16:38:05,751 ru.ru_gen 48R/0.28014s # 2020-10-20 16:38:06,067 ru.ru_gen 30R/0.19581s # 2020-10-20 16:38:06,505 ru.ru_gen 40R/0.23340s # 2020-10-20 16:38:06,973 ru.ru_gen 52R/0.30009s # 2020-10-20 16:38:07,292 ru.ru_gen 39R/0.21826s # 2020-10-20 16:38:07,801 ru.ru_gen 61R/0.32724s # 2020-10-20 16:38:08,068 ru.ru_gen 26R/0.19329s # 2020-10-20 16:38:08,687 ru.ru_gen 55R/0.41134s # 2020-10-20 16:38:08,983 ru.ru_gen 44R/0.29496s # 2020-10-20 16:38:09,309 ru.ru_gen 38R/0.22035s # 2020-10-20 16:38:09,815 ru.ru_gen 54R/0.32522s # 2020-10-20 16:38:10,123 ru.ru_gen 38R/0.23294s # 2020-10-20 16:38:10,526 ru.ru_gen 35R/0.23459s # 2020-10-20 16:38:11,021 ru.ru_gen 49R/0.32931s # 2020-10-20 16:38:11,344 ru.ru_gen 40R/0.25104s # 2020-10-20 16:38:11,809 ru.ru_gen 50R/0.31448s # 2020-10-20 16:38:12,096 ru.ru_gen 28R/0.20125s # 2020-10-20 16:38:12,627 ru.ru_gen 55R/0.33121s # basecall the reads (from outside) singularity exec \ --nv \ simulation.sif \ guppy_basecaller_supervisor \ --port 5557 \ --num_clients 5 \ --input_path tmp/var/lib/minknow/data/RU_Test_basecall_and_map/NOTT_Hum_wh1rs2_60428/ \ --save_path "basecalled/RU_Test_basecall_and_map" \ --flowcell "FLO-MIN106" \ --kit "SQK-LSK109" \ --verbose_logs \ --recursive \ --trim_strategy dna \ --qscore_filtering singularity exec \ --nv \ -B tmp/var:/var,tmp/run:/run \ simulation.sif \ readfish summary \ toml/human_chr_selection.toml \ basecalled/RU_Test_basecall_and_map # 1 GB singularity overlay? # THIS WORKS mkdir -p overlay/upper overlay/work dd if=/dev/zero of=overlay.img bs=1M count=1000 mkfs.ext3 -d overlay overlay.img singularity shell \ --nv \ --overlay overlay.img \ -B tmp/var:/var,tmp/run:/run \ readfish_77c11e2.sif # put the modified TOML in place cp toml/sequencing_MIN106_DNA.core4.toml \ /opt/ont/minknow/conf/package/sequencing/sequencing_MIN106_DNA.toml # restore ONT's copy cp toml/sequencing_MIN106_DNA.ont_default.toml \ /opt/ont/minknow/conf/package/sequencing/sequencing_MIN106_DNA.toml # is it the pycache directory? dunno, it's not there when running without # persistent overlay singularity shell \ --nv \ --writable-tmpfs \ -B tmp/var:/var,tmp/run:/run \ readfish_77c11e2.sif <file_sep>/toml/sequencing_MIN106_DNA.core4.toml script = "sequencing/sequencing.py" [meta] exp_script_purpose = "sequencing_run" [meta.protocol] experiment_type = "sequencing" flow_cells = ["FLO-MIN106", "FLO-FLG001", "FLO-FLGOP1"] kits = [ "SQK-16S024", "SQK-CAS109", "SQK-CS9109", "SQK-LSK108", "SQK-LSK109", "SQK-LSK109-XL", "SQK-LSK110", "SQK-RAD004", "SQK-RBK004", "SQK-RBK096", "SQK-DCS108", "SQK-DCS109", "SQK-PCB109", "SQK-PCS108", "SQK-PCS109", "SQK-PRC109", "VSK-VSK002", "VSK-VMK002", "SQK-RAB204", "SQK-LRK001", "SQK-PBK004", "SQK-PSK004", "SQK-RPB004", ] default_basecall_model = "dna_r9.4.1_450bps_fast.cfg" available_basecall_models = ["dna_r9.4.1_450bps_fast.cfg", "dna_r9.4.1_450bps_hac.cfg", "dna_r9.4.1_450bps_modbases_dam-dcm-cpg_hac.cfg"] [meta.protocol.flongle] default_basecall_model = "dna_r9.4.1_450bps_hac.cfg" [meta.protocol.gridion] default_basecall_model = "dna_r9.4.1_450bps_hac.cfg" [meta.context_tags] package = "bream4" experiment_type = "genomic_dna" [compatibility] minknow_core = "4.0" bream = "6.0.0" [device] import = "shared/default_device_settings.toml" sample_rate = 4000 unblock_voltage = -300 [writer_configuration] import = "shared/default_writer.toml" [writer_configuration.sequencing_summary] enable = [[1, 3000]] [writer_configuration.read_fast5] modifications_table = [[1,3000]] [basecaller_configuration] enable = false [basecaller_configuration.read_filtering] min_qscore = 7 # Set via UI as there are no defaults known at build time # [basecaller_configuration.alignment_configuration] # reference_files = ["..."] # bed_file = "" # [basecaller_configuration.barcoding_configuration] # barcoding_kits = [] # trim_barcodes = false # require_barcodes_both_ends = false # detect_mid_strand_barcodes = false # min_score = 60 # min_score_rear = 60 # min_score_mid = 60 [analysis_configuration.read_detection] mode = "transition" minimum_delta_mean = 80.0 look_back = 2 break_reads_after_events = 250 break_reads_after_seconds = 0.4 break_reads_on_mux_changes = true open_pore_min = 150.0 open_pore_max = 250.0 [analysis_configuration.read_classification] classification_strategy = "modal" selected_classifications = ["strand"] scheme_module = "parsed" [analysis_configuration.read_classification.parameters] rules_in_execution_order = [ "multiple= (local_median,gt,350)&(local_median,lt,990)&(local_median_sd,gt,1.5)&(local_median_dwell,gt,0.005)&(duration,gt,0.02)", "pore_1= (local_median,gt,160)&(local_median,lt,280)&(median_sd,gt,0.9)&(median_sd,lt,5)&(local_range,lt,35)&(duration,gt,15)", "pore= (local_median,gt,160)&(local_median,lt,280)&(median_sd,gt,0.9)&(median_sd,lt,5)&(local_range,lt,35)", "event= (median_before,gt,160)&(median_before,lt,280)&(median_before,gt,median)&(median,lt,140)&(median,gt,20)&(duration,lt,0.1)&(event_count,lt,20)", "adapter= (median_before,gt,160)&(median_before,lt,280)&(median,lt,120)&(median,gt,50)&(event_count,lt,120)&(event_count,gt,7)&(median_sd,gt,1)&(median_sd,lt,5)&(local_range,lt,75)&(duration,lt,1)", "strand= (local_median,gt,50)&(local_median,lt,150)&(local_range,gt,20)&(local_range,lt,44)&(local_median_sd,gt,0.9)&(local_median_sd,lt,5)&(event_count,gt,119)&(local_median_dwell,lt,0.006)", "strand2= (local_median,gt,50)&(local_median,lt,150)&(local_range,gt,5)&(local_range,lt,44)&(local_median_sd,gt,0.9)&(local_median_sd,lt,5)&(event_count,gt,119)&(local_median_dwell,lt,0.015)", "unavailable= (local_median,gt,10)&(local_median,lt,250)&(local_median_sd,gt,0.6)", "zero= (local_median,gt,-25)&(local_median,lt,10)", "unknown_positive=(local_median,gt,0)&(local_median,lt,999)", "unknown_negative=(local_median,gt,-999)&(local_median,lt,0)" ] [analysis_configuration.event_detection] peak_height = 1.0 threshold = 4.13 window_size = 10 events_to_base_ratio = 1.8 break_on_mux_changes = true max_mux_change_back_shift = 5 [analysis_configuration.channel_states] import = "sequencing/sequencing_channel_states.toml" ############################### # Sequencing Feature Settings # ############################### # basic_settings # [custom_settings] enable_relative_unblock_voltage = true unblock_voltage_gap = 480 run_time = 172800 # (seconds) 1hr=3600 start_bias_voltage = -180 simulation = '/home/tom/Projects/readfish-test/data/PLSP57501_20170308_FNFAF14035_MN16458_sequencing_run_NOTT_Hum_wh1rs2_60428.fast5' # UI parameters translocation_speed_min = 300 translocation_speed_max = 425 q_score_min = 7 [custom_settings.temperature] target = 34.0 timeout = 300 tolerance = 0.1 min_stable_duration = 15 # Seconds [custom_settings.temperature.flongle] target = 35.0 #-------- Channel States Disable ---------# [custom_settings.channel_states_disable] states_to_disable = ['multiple', 'saturated'] enabled = true #-------- Group Manager ---------# [custom_settings.group_manager] # If this is true, and a channel becomes disabled/locked then swap the channel for another well if possible swap_out_disabled_channels = true # If this is True then when the groups determined by the mux scan reach the final mux it will loop back around to the # first group. If this is disabled, once the groups have reached the last tier the channel will be disabled until the # groups are refreshed, (by say another mux scan) cycle_groups = false # How many muxes to include per channel, if possible. Only applies if cycle_groups is true cycle_limit_per_channel = 3 [custom_settings.group_manager.global_mux_change] interval = 28800 # (seconds) enabled = false #-------- Global Flicks ---------# [custom_settings.global_flick] enabled = false interval = 3600 # Timing between flicks (in seconds) # voltage, pause, voltage, pause, voltage, pause perform_relative_flick = true rest_voltage = 0 rest_duration = 1.0 flick_duration = 3.0 voltage_gap = 300 #-------- Progressive Unblock ---------# [custom_settings.progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 15, 30 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable', 'zero'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked', 'disabled'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager [custom_settings.progressive_unblock.flongle] rest_duration = [ 3, 3, 15, 300 ] #-------- Drift Correction ---------# [custom_settings.drift_correction] enabled = true interval = 600 # Try to correct this often (seconds) setpoint = 30.0 # Try to keep (q90-q10) range close to this value (in pA) channels_threshold = 50 # This many channels need to have classification to count classification = "strand" # Use this as the source ### Small adjustment lower_threshold = 0.8 # if average of observed medians is below the setpoint by this threshold then adjust upper_threshold = 1.5 # if average of observed medians is above the setpoint by this threshold then adjust initial_pA_adjustment_per_minimum_voltage_adjustment = 1 ewma_factor = 0.3 # exponentially weighted moving average weight factor. Closer to 1 == weight newest information more voltage_fallback = -250 # Once voltage goes outside this, use fallback static voltage_fallback_interval = 5400 # If not corrected in this long (seconds), or in fallback, adjust by the minimum_voltage_adjustment # Don't go out of these limits voltage_max = -170 voltage_min = -250 [custom_settings.drift_correction.flongle] channels_threshold = 5 # A lot less channels to work with [custom_settings.static_drift_correction] enabled = false interval = 5400 # Correct this often (seconds) voltage_max = -170 voltage_min = -250 ############ # Mux Scan # ############ [custom_settings.mux_scan] threshold = 2.5 # 2.5 seconds of time in well must be pore/strand/adapter to be eligible to be picked collection_time_per_well = 10 enabled = true percentile_cut_off = 25 filter_percentile = false interval = 5400 # (seconds) 1hr=3600 [custom_settings.mux_scan.global_flick] enabled = true # voltage, pause, voltage, pause, voltage, pause perform_relative_flick = true rest_voltage = 0 rest_duration = 1.0 flick_duration = 3.0 voltage_gap = 300 [custom_settings.mux_scan_progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 15, 30 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked', 'disabled'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager ##################### # Channel Wind Down # ##################### [custom_settings.channel_wind_down] timeout = 60 enabled = true [custom_settings.channel_wind_down.channel_states_disable] states_to_disable = ['pore', 'saturated', 'multiple', 'unknown_negative', 'unknown_positive', 'zero'] enabled = true stop_feature_manage_enabled = true min_channel_threshold = 10 active_states = ['strand'] [custom_settings.channel_wind_down.channel_states_disable.flongle] min_channel_threshold = 2 [custom_settings.channel_wind_down.progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 3, 3 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable', 'zero'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked', 'disabled'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager <file_sep>/toml/human_chr_selection.toml [caller_settings] config_name = "dna_r9.4.1_450bps_fast" host = "127.0.0.1" port = 5557 [conditions] reference = "data/reference.mmi" [conditions.0] name = "select_chr_21_22" control = false min_chunks = 0 max_chunks = inf targets = ["NC_000021.9", "NC_000022.11"] single_on = "stop_receiving" multi_on = "stop_receiving" single_off = "unblock" multi_off = "unblock" no_seq = "proceed" no_map = "proceed" <file_sep>/toml/sequencing_MIN106_DNA.toml script = "sequencing/sequencing.py" [meta] exp_script_purpose = "sequencing_run" [meta.protocol] experiment_type = "sequencing" flow_cells = ["FLO-MIN106", "FLO-FLG001"] kits = [ "SQK-16S024", "SQK-CAS109", "SQK-CS9109", "SQK-LSK108", "SQK-LSK109", "SQK-LSK109-XL", "SQK-RAD004", "SQK-RBK004", "SQK-DCS108", "SQK-DCS109", "SQK-PCB109", "SQK-PCS108", "SQK-PCS109", "SQK-PRC109", "VSK-VSK002", "VSK-VMK002", "SQK-RAB204", "SQK-LRK001", "SQK-PBK004", "SQK-PSK004", "SQK-RPB004", ] default_basecall_model = "dna_r9.4.1_450bps_fast.cfg" available_basecall_models = ["dna_r9.4.1_450bps_fast.cfg", "dna_r9.4.1_450bps_hac.cfg", "dna_r9.4.1_450bps_modbases_dam-dcm-cpg_hac.cfg"] [meta.protocol.flongle] default_basecall_model = "dna_r9.4.1_450bps_hac.cfg" [meta.protocol.gridion] default_basecall_model = "dna_r9.4.1_450bps_hac.cfg" [meta.context_tags] package = "bream4" experiment_type = "genomic_dna" [compatibility] minknow_core = "3.6" bream = "4.3.1" [device] import = "shared/default_device_settings.toml" sample_rate = 4000 unblock_voltage = -300 [writer_configuration] import = "shared/default_writer.toml" [writer_configuration.sequencing_summary] enable = [[1, 3000]] [writer_configuration.read_fast5] modifications_table = [[1,3000]] [basecaller_configuration] enable = false [basecaller_configuration.read_filtering] min_qscore = 7 [analysis_configuration.read_detection] mode = "transition" minimum_delta_mean = 80.0 look_back = 2 break_reads_after_events = 250 break_reads_after_seconds = 1.0 break_reads_on_mux_changes = 1 open_pore_min = 150.0 open_pore_max = 250.0 [analysis_configuration.read_classification] classification_strategy = "modal" selected_classifications = "strand" scheme_module = "parsed" [analysis_configuration.read_classification.parameters] type = "ParsedParameters" rules_in_execution_order = [ "multiple= (local_median,gt,350)&(local_median,lt,990)&(local_median_sd,gt,1.5)&(local_median_dwell,gt,0.005)", "pore_1= (local_median,gt,160)&(local_median,lt,280)&(median_sd,gt,0.9)&(median_sd,lt,5)&(local_range,lt,35)&(duration,gt,15)", "pore= (local_median,gt,160)&(local_median,lt,280)&(median_sd,gt,0.9)&(median_sd,lt,5)&(local_range,lt,35)", "event= (median_before,gt,160)&(median_before,lt,280)&(median_before,gt,median)&(median,lt,140)&(duration,lt,0.1)&(event_count,lt,20)", "adapter= (median_before,gt,160)&(median_before,lt,280)&(median,lt,120)&(median,gt,50)&(event_count,lt,120)&(event_count,gt,7)&(median_sd,gt,1)&(median_sd,lt,5)&(local_range,lt,75)&(duration,lt,1)", "strand= (local_median,gt,50)&(local_median,lt,150)&(local_range,gt,20)&(local_range,lt,44)&(local_median_sd,gt,0.9)&(local_median_sd,lt,5)&(event_count,gt,119)&(local_median_dwell,lt,0.006)", "strand1= (local_median,gt,50)&(local_median,lt,150)&(local_range,gt,20)&(local_range,lt,44)&(local_median_sd,gt,0.9)&(local_median_sd,lt,5)&(event_count,gt,119)&(local_median_dwell,lt,0.1)", "strand2= (local_median,gt,50)&(local_median,lt,150)&(local_range,gt,10)&(local_range,lt,44)&(local_median_sd,gt,0.9)&(local_median_sd,lt,5)&(event_count,gt,119)&(local_median_dwell,lt,0.0075)", "unavailable= (local_median,gt,10)&(local_median,lt,250)&(local_median_sd,gt,0.6)", "zero= (local_median,gt,-25)&(local_median,lt,10)", "unknown_positive=(local_median,gt,0)&(local_median,lt,999)", "unknown_negative=(local_median,gt,-999)&(local_median,lt,0)" ] [analysis_configuration.event_detection] peak_height = 1.0 threshold = 4.13 window_size = 10 events_to_base_ratio = 1.8 break_on_mux_changes = true max_mux_change_back_shift = 5 [analysis_configuration.channel_states] import = "sequencing/sequencing_channel_states.toml" [custom_settings] run_time = 172800 # (seconds) 24hr=86400 run_time_between_mux_scans = 5400 # (seconds) 4hr=14400 start_bias_voltage = -180 simulation = '/home/tom/Projects/readfish-test/data/PLSP57501_20170308_FNFAF14035_MN16458_sequencing_run_NOTT_Hum_wh1rs2_60428.fast5' # mux scan voltage control minimum_voltage_adjustment = -5 # UI parameters translocation_speed_min = 300 translocation_speed_max = 425 q_score_min = 7 [custom_settings.temperature] target = 34.0 timeout = 300 tolerance = 0.1 min_stable_duration = 15 # Seconds [custom_settings.temperature.flongle] target = 35.0 [custom_settings.mux_scan] threshold = 2.5 # 2.5 seconds of time in well must be pore/strand/adapter to be eligible to be picked collection_time_per_well = 10 enabled = true percentile_cut_off = 25 filter_percentile = false [custom_settings.mux_scan_progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 15, 30 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager [custom_settings.group_manager] # If this is true, and a channel becomes disabled/locked then swap the channel for another well if possible swap_out_disabled_channels = true # How many muxes to include per channel, if possible. Only applies if swap_out_disabled_channels is False limit_mux_per_channel = 3 [custom_settings.global_mux_change] interval = 28800 # (seconds) enabled = false [custom_settings.global_flick] enabled = false interval = 3600 # Timing between flicks (in seconds) # voltage, pause, voltage, pause, voltage, pause voltages = [0, 120, 0] adjustment_pause = [1.0, 3.0, 1.0] [custom_settings.global_flick.flongle] enabled = true # Problem with unblock_voltage through adapter [custom_settings.progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 15, 30 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable', 'zero'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager [custom_settings.progressive_unblock.flongle] rest_duration = [ 3, 3, 15, 300 ] [custom_settings.drift_correction] enabled = true interval = 600 # Try to correct this often (seconds) setpoint = 32.0 # Try to keep (q90-q10) range close to this value (in pA) channels_threshold = 50 # This many channels need to have classification to count classification = "strand" # Use this as the source ### Small adjustment threshold = 0.8 # if average of observed medians is outside setpoint +/- threshold then adjust adjust_value = 5 # Adjust by this much ### Larger adjustment intense_threshold = 1.6 # If average of observed medians outside setpoint by +/- then adjust more intensely intense_adjust_value = 10 # Adjust by this much ewma_factor = 0.3 # exponentially weighted moving average weight factor. Closer to 1 == weight newest information more voltage_fallback = -250 # Once voltage goes outside this, use fallback static voltage_fallback_interval = 5400 # If not corrected in this long (seconds), or in fallback, adjust by adjust_value # Don't go out of these limits voltage_max = -170 voltage_min = -250 [custom_settings.drift_correction.flongle] channels_threshold = 5 # A lot less channels to work with [custom_settings.static_drift_correction] enabled = false interval = 5400 # Correct this often (seconds) adjust_value = 5 voltage_max = -170 voltage_min = -250 [custom_settings.channel_states_disable] states_to_disable = ['multiple', 'saturated'] enabled = true # Feeds into group_manager. If this is true and if a channel enters # a states_to_disable the group manger will try and replace it for another mux change_mux_on_disable = true ##################### # Channel Wind Down # ##################### [custom_settings.channel_wind_down] timeout = 60 enabled = true [custom_settings.channel_wind_down_channel_states_disable] states_to_disable = ['pore', 'saturated', 'multiple', 'unknown_negative', 'unknown_positive', 'zero'] enabled = true stop_feature_manage_enabled = true min_channel_threshold = 10 active_states = ['strand'] # Feeds into group_manager. If this is true and if a channel enters # a states_to_disable the group manger will try and replace it for another mux change_mux_on_disable = false [custom_settings.channel_wind_down_channel_states_disable.flongle] min_channel_threshold = 2 [custom_settings.channel_wind_down_progressive_unblock] enabled = true # A flick tier would go (flick for x seconds, rest for y seconds) * repeats flick_duration = [ 0.1, 2.0, 10.0, 30.0 ] rest_duration = [ 3, 3, 3, 3 ] repeats = [ 1, 1, 4, 4 ] states_to_flick = ['unavailable', 'zero'] # When see this, flick states_to_reset = ['strand', 'pore', 'adapter' , 'event', 'locked'] # If any of these appear 'reset' the channel so it starts again change_mux_after_last_tier = true # Feeds into group_manager. If this is true the channel is flagged to be replaced by group manager <file_sep>/toml/conf.toml [caller_settings] config_name = \"dna_r9.4.1_450bps_hac\" host = \"127.0.0.1\" port = 5555
e2fb8bf49cb5d01dc721eb4822d0536cca76944f
[ "TOML", "Shell" ]
5
Shell
TomHarrop/readfish-test
9373971584f4cfbd8c72c30d2f1d4474fefe54aa
1f61c3121513fe513abee9ebd1e79f7e8eef79c9
refs/heads/master
<file_sep>server.servlet.context-path=/tokenwebservices cxf.path=/ <file_sep>package com.ut.ws.soap; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.handler.WSHandlerConstants; import com.token.ws.soap.PaymentProcessorImplService; import com.token.ws.soap.PaymentProcessorRequest; import com.token.ws.soap.PaymentProcessorResponse; import com.token.ws.soap.PaymentProcessor_0020; public class WSClient { public static void main(String[] args) { // TODO Auto-generated method stub try { PaymentProcessorImplService service = new PaymentProcessorImplService( new URL("http://localhost:8080/tokenwebservices/paymentProcessor?wsdl")); PaymentProcessor_0020 port = service.getPaymentProcessorImplPort(); PaymentProcessorRequest paymentProcessorResponse = new PaymentProcessorRequest(); Client client = ClientProxy.getClient(port); Endpoint endpoint = client.getEndpoint(); Map<String, Object> map = new HashMap<>(); map.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); map.put(WSHandlerConstants.USER, "Ericka"); map.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT); map.put(WSHandlerConstants.PW_CALLBACK_CLASS,UTPasswordCallback.class.getName()); WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(map); endpoint.getOutInterceptors().add(wssOut); PaymentProcessorResponse response = port.processPayment(paymentProcessorResponse); System.out.println(response.isResult()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.token.ws.soap; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import com.token.ws.soap.dto.PaymentProcessorRequest; import com.token.ws.soap.dto.PaymentProcessorResponse; @WebService (name="PaymentProcessor ") public interface PaymentProcessor { @WebMethod public @WebResult(name="response") PaymentProcessorResponse processPayment( @WebParam(name="paymentProcessorResponse") PaymentProcessorRequest paymentProcessorRequest); }
51d08fdd155c31266a7eac90753b797068a9745d
[ "Java", "INI" ]
3
INI
erickamontero100292/tokenWebService
b839b03c8be277435f572954fa03c9ab0afed174
fe62c0e042316d631a17077e2d7fd1cbfb9c1963
refs/heads/master
<repo_name>eclatdev/testtbcb<file_sep>/my.js function sayHello() { alert("Welcome to Javascript World!"); } function inputData() { num1=parseInt(prompt("Enter First Number")); num2=parseInt(prompt("Enter Second Number")); } function add() { inputData(); sum=num1+num2; document.write("<br><h1>The sum is " + sum + "</h1>"); } function sub() { inputData(); sub=num1-num2; document.write("<br><h1>The Subtraction is " + sub + "</h1>"); }
98da995b68b4ec848bb34b0d38f163e5c8da4304
[ "JavaScript" ]
1
JavaScript
eclatdev/testtbcb
cff2c2070da0158e6ef0a762ac88bb4ae35aa7ed
ada298a90d37bb07678f218db7bcc6ebc0de65c9
refs/heads/master
<repo_name>AizarCabrera/backend_prework<file_sep>/day_4/ex21.rb def add(a,b) #passing two arguments puts "ADDING #{a} + #{b}" #printing our operation using interpolation return a + b #returning our result end def substract(a,b) #passing two arguments puts "SUBSTRACTING #{a} - #{b}" #printing our operation using interpolation return a - b #returning our result end def multiply(a,b) #passing two arguments puts "MULTIPLYING #{a} * #{b}" #printing our operation using interpolation return a * b #returning our result end def divide(a,b) #passing two arguments puts "DIVIDING #{a} / #{b}" #printing our operation using interpolation return a/b #returning our result end puts "Let's do some math with just methods!" age = add(30, 5) #storing the result of our method into a variable height = substract(78, 4) #storing the result of our method into a variable weight = multiply(90,4) #storing the result of our method into a variable iq = divide(100,2) #storing the result of our method into a variable puts "Age #{age}, Height:#{height}, Weight:#{weight},IQ:#{iq}" #first we passed the arguments to our methods, then stored the values into #variables and using those variables to do some math and then stores those results #into a new variable called 'what' what = add(age,substract(height, multiply(weight, divide(iq, 2)))) puts "Here is a puzzle." puts "That becomes: #{what}. Can you do it by hand?" <file_sep>/day_6/ex3.rb class Car def initialize(year, model, color) @year = year @model = model @color = color @speed = 0 end def speed_up(number) @speed += number puts "You hit the gas and accelerate #{number} mph." end def brake(number) @speed -= number puts "You hit the brake and decelerate #{number} mph." end def speed puts "You are now at #{@speed} mph." end def shut_down @speed = 0 puts "Let's stop!" end end ramvan = Car.new(1996,'<NAME>','white') ramvan.speed_up(30) ramvan.speed ramvan.speed_up(30) ramvan.speed ramvan.brake(30) ramvan.speed ramvan.brake(30) ramvan.speed ramvan.shut_down ramvan.speed <file_sep>/day_6/ex1.rb class Student end aizar = Student.new <file_sep>/day_1/ex4.rb cars = 100 #variable space_in_a_car = 4.0 #floating point, it's just a number with a decimal point drivers = 30 #variable passengers = 90 #variable cars_not_driven = cars - drivers #using variables cars and drivers to do some math cars_driven = drivers #using variable drivers to store it into to cars_driven variable carpool_capacity = cars_driven * space_in_a_car #using variables to do math average_passengers_per_car = passengers / cars_driven #using variables to do math puts "There are #{cars} cars available." puts "There are only #{drivers} drivers available." puts "There will be #{cars_not_driven} empty cars today" puts "We can transport #{carpool_capacity} people today" puts "We have #{passengers} to carpool today." puts "We need to put about #{average_passengers_per_car} in each car" <file_sep>/day_5/questions.md ## Day 5 Questions 1. What is a Hash, and how is it different from an Array in Ruby? It's a collection of data that has no order, the difference between a hash and an array, is mainly the order. 1. In the space below, create a Hash stored to a variable named `pet_store`. This hash should hold an inventory of items and the number of that item that you might find at a pet store. pet_store = {"toys"=>"5"} 1. given the following `states = {"CO" => "Colorado", "IA" => "Iowa", "OK" => "Oklahoma"}`, how would you access the value `"Iowa"`? states["IA"] 1. With the same hash above, how would we get all the keys? All the values? states.each.do |abbrev, state| puts "#{state} is abbreviated #{abbrev}" end 1. What is another example of when we might use a hash? In this case, why is a hash better than an array? When we want to add a value other than a number to one of the elements. 1. What questions do you still have about hashes? How to combine the use of variables with hashes and the syntax in general. <file_sep>/day_6/questions.md ## Day 5 Questions 1. In your own words, what is a Class? A class it's some sort of definition of what the object does and what the object has. 1. In relation to a Class, what is an attribute? The attribute are the features that an object has, like a name, a color, a shape, etc... 1. In relation to a Class, what is behavior? What the object does, like, searching, adding, changing something, etc... 1. In the space below, create a Dog class with at least 2 attributes and 2 behaviors class TheDog def initialize(name) @name = name end def get_name @name end def speak "#{@name} says arf!" end def play "#{@name} plays!" end end gyalbu = TheDog.new("Gyalbu") gyalbu.speak gyalbu.play gyalbu.get_name 1. How do you create an instance of a class? Aizar = Student.new We are calling the method on the class and storing it in a new variable. 1. What questions do you still have about classes in Ruby? Is it possible to combine classes...??? <file_sep>/day_6/exercises/person.rb # Create a person class with at least 2 attributes and 2 behaviors. Call all # person methods below the class so that they print their result to the # terminal. #YOUR CODE HERE class Person attr_reader :name def initialize(name = 'Aizar') @name = name end def introduction(target) p "Hi #{target}, my name is #{@name}!" end def favorite_person p "My favorite person is, YOU" end end aizar = Person.new aizar.introduction("Amigo") aizar.favorite_person <file_sep>/day_3/ex29.rb people = 20 cats = 30 dogs = 15 if people < cats #conditions the statment puts "Too many cats! The world is doomed!" #prints a result end if people > cats #conditions the statment puts "Not many cats!The world is saved!" #prints a result end if people < dogs #conditions the statment puts "The world is drooled on!" #prints a result end if people > dogs #conditions the statment puts "The world is dry!" #prints a result end dogs += 5 if people >= dogs #conditions the statment puts "People are greater than or equal to dogs." #prints a result end if people <= dogs #conditions the statment puts "People are less than or equal to dogs." #prints a result end if people == dogs #conditions the statment puts "People are dogs." #prints a result end <file_sep>/day_4/exsay.rb def say(words = "hello")#method passes a string stored into variable 'words' puts words + '.' #prints the variable words with a dot at the end end say() say("hi") #method passes a string stored into variable 'words' say("how are you") #method passes a string stored into variable 'words' say("I'm fine")#method passes a string stored into variable 'words' <file_sep>/day_2/array_methods.md arrays Sort. You can reorder the elements using the SORT method. In other words, you can rearrange and repeat the elements using these two methods. Each. You can iterate through each element using the EACH method. In other words, you can rearrange and repeat the elements using these two methods. <file_sep>/day_1/ex6.rb types_of_people = 10 #storing value of 10 into variable types_of_people x = "There are #{types_of_people} types of people." #uses variable here binary = "binary" #storing value of binary into variable binary do_not = "don't" #storing value of don't into variable do_not y = "Those who know #{binary} and those who #{do_not}." #usage of both variables puts x #prints x string with interpolated variables puts y #prints y string with interpolated variables puts " I said:#{x}" #interpolates x puts " I also said: '#{y}'." #interpolates y hilarious = false #stores false into hilarious variable joke_evaluation = "Isn't that joke so funny?! #{hilarious}" #interpolates "false" puts joke_evaluation w = "This is the left side of..." e = "a string with a right side." puts w + e #concatenation of two strings <file_sep>/day_6/exercises/dog.rb # In the dog class below, add a play method that, when called, will result in # the dog being hungry. Call that method below the class, and print the dog's # hunger status. class Dog attr_reader :name def initialize(name) @name = name end def play p "#{name} is hungry!" end end fido = Dog.new("Fido") fido.play <file_sep>/day_4/ex19.rb #we have a method passing two arguments def cheese_and_crackers(cheese_count, boxes_of_crackers) puts "You have #{cheese_count} chessees!" #prints the argument of chesse puts "You have #{boxes_of_crackers} boxes of crackers!"#prints the argument of chesse puts "Man that's enough for a party!" #prints a string puts "Get a blanket.\n "#prints another string end puts "We can just give the method numbers directly" cheese_and_crackers(20, 30) #we're calling the method and passing two arguments puts "OR, we can use variables from our script:" amount_of_cheese = 10 #we're storing the value of 10 into the chesses varible amount_of_crackers = 50 #we're storing the value of 50 into the crackers variable cheese_and_crackers(amount_of_cheese, amount_of_crackers) #calling the method again puts "We can even do math inside it too:" cheese_and_crackers(10 + 20, 5 + 6) #we're doing math inside the argument puts "And we can comnbine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) #we're using the variables and adding some extra values as we pass the arguments <file_sep>/day_3/questions.md ## Day 3 Questions 1. What is a conditional statement? Give three examples. Conditional statements evaluate to true or false. Some examples of conditional operators are ==(equal), > (greater than), >= (greater than or equal to), < (less than), and <= (less than or equal to). 1. Why might you want to use an if-statement? To test a condition and then evaluate depending on the result. 1. What is the Ruby syntax for an if statement? if else end 1. How do you add multiple conditions to an if statement? By adding more conditions, add more elsif blocks for each possible choice. 1. What is the Ruby syntax for an if/elsif/else statement? if elsif else end 1. Other than an if-statement, can you think of any other ways we might want to use a conditional statement? Ways to control execution <file_sep>/day_6/ex2.rb module Work class Student include Work end aizar = Student.new <file_sep>/day_4/ex18.rb # this one is like your scripts with ARGV def print_two(*args) #we're using splat operator arg1, arg2 = args puts "arg1: #{arg1}, arg2: #{arg2}" end # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2) #we got rid of splat and we're using two arguments puts "arg1: #{arg1}, arg2: #{arg2}" end # this just takes one argument def print_one(arg1) #we're passing just one argument puts "arg1: #{arg1}" end def print_none() #passing zero arguments puts "I got nothin'." end #we're callling the methods and passing the strings as arguments print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none <file_sep>/day_1/questions.md ## Day 1 Questions 1. How would you print the string `"Hello World!"` to the terminal? print "Hello World!" 1. What is the character you would use to indicate comments in a ruby file? #comments 1. Explain the difference between an integer and a float? A floating number has a decimal point. The integer number does not. 1. In the space below, create a variable `animal` that holds the string `"zebra"` animal="zebra" 1. How would you print the string `"zebra"` using the variable that you created above? animal="zebra" puts #{animal} 1. What is interpolation? Use interpolation to print a sentence using the variable `animal`. Basically whatever we have within the two brackets {} is evaluated first, then the result is injected into the outer string animal="zebra" puts"We can find a #{animal} in a zoo !" 1. How do we get input from a user? What is the method that we would use? gets.chomp, where chomp helps us to avoid having extra space after the input in our line. 1. Name and describe two common string methods. .lenght and .split <file_sep>/day_2/questions.md ## Day 2 Questions 1. Create an array containing the following strings: `"zebra", "giraffe", "elephant"`. x = ["Zebra", "Giraffe", "Elephant"] 1. Save the array you created above to a variable `animals`. animals = ["Zebra", "Giraffe", "Elephant"] 1. using the array `animals`, how would you access `"giraffe"`? animals=["zebra", "giraffe", "elephant"] animals=>[1] 1. How would you add `"lion"` to the `animals` array? animals=["zebra", "giraffe", "elephant"] animals << "lion" 1. Name and describe two additional array methods. You can reorder the elements using the SORT method. You can iterate through each element using the EACH method. in other words, you can rearrange and repeat the elements using these two methods. 1. What are the boolean values in Ruby? They are terms (characters and phrases) for determining if something is "true" or "false." 1. In Ruby, how would you evaluate if `2` is equal to `25`? What is the result of this evaluation? 2 == 25 =>false 1. In Ruby, how would you evaluate if `25` is greater than `2`? What is the result of this evaluation? 25 >= 2 =>true <file_sep>/playground.rb # puts 'What do you want to say?' # say = gets # puts "You said this : #{say}" # # # # p 'What is the first number?' # first = gets.to_i # p 'What is the second number?' # second = gets.to_i # result = (first + second) # p "The sum of these two numbers is #{result}" # # a = 'apple' # b = 'banana' # a == b # p a + b # a = b # p a + b # # # def truthy_or_falsey value # # We don't know what `value` is # # It could be true, false, or a non-boolean value like 1, "", etc. # # Ruby only cares about whether something is truthy or falsey, though. # # Let's go look! # # if value # # What does inspect do here? # # Remove it and see how the output changes. # puts "#{value.inspect} is truthy" # # # Instead of calling value.inspect, call value.to_s # # How does the output of that look? # else # puts "#{value.inspect} is falsey" # end # end # # [true, false, Object, 0, 1, nil, true, false, "", [1, 2, 3], {}].each do |value| # truthy_or_falsey(value) # end # # print "How many apples do you have? >" # apple_count = gets.to_i # puts "You have #{apple_count} apples." # # print "How many apples do you have? >" # apple_count = gets.to_i # # if apple_count > 5 # puts "Lots of apples!" # else # puts 'Not many apples...' # end # # require 'pry' # total = 0 # user_input = nil # while user_input != 'stop' # print 'Enter a number to add to the total.>' # user_input = gets.chomp # f_total = total + user_input.to_i # end # p "Your final total was #{f_total}!!!" # # binding.pry # # # # total = 99 # colors = ['red', 'blue', 'green'] # colors.each do |color| # puts "#{total} colors of paint on the wall..." # puts "Take #{color} down, pass it around..." # total = total - 1 # puts "#{total} colors of paint on the wall!" # end # # def calculate_circle_area(radius) # Math::PI * (radius ** 2) # end # # p "What is the radius of your circle?>" # radius = gets.to_i # # p "Your circle has an area of #{calculate_circle_area(radius)}" # # class Circle # def initialize(radius) # @radius = radius # end # # def area # Math::PI * (@radius ** 2) # end # # def perimeter # 2 * Math::PI * @radius # end # # print "What is the radius of your circle? >" # radius = gets.to_i # # a_circle = Circle.new(radius) # puts "Your circle has an area of #{a_circle.area}" # puts "Your circle has a perimeter of #{a_circle.perimeter}" # # end # # def roll # rand(6) + 1 # end # # p roll # # # def roll(sides) # rand(sides) + 1 # end # # p roll(6) # # def roll(sides, number = 1) # roll_array = [] # number.times do # roll_value = rand(sides) + 1 # roll_array = roll_value # end # total = 0 # roll_array.each do |roll| # new_total = total + roll # total = new_total # end # total # end # # # puts "we're rollin a six sided die!" # puts roll(6) # # puts "Now we're rolling two 20 sided die!" # puts roll(20, 2) <file_sep>/day_4/questions.md ## Day 4 Questions 1. In your own words, what is the purpose of a method? It's a section of a code that needs to be repeated several times in a program 1. In the space below, create a method named `hello` that will print `"<NAME>"`. def hello (name) puts name + "I am" end hello ("Sam") 1. Create a method name `hello_someone` that takes an argument of `name` and prints `"#{name} I am"`. def hello_someone (name) puts "#{name} I am" end hello_someone ("Aizar") 1. How would you call or execute the method that you created above? By calling the name of the method, hello_someone, plus a parenthesis 1. What questions do you still have about methods in Ruby? Still have questions about the way variables interact within the method itself <file_sep>/day_1/ex7.rb print "How old are you " #prompt to user age = gets.chomp #gets info print "How tall are you? "#prompt to user height = gets.chomp #gets info print "How much do you weigh? " #prompt to user weight = gets.chomp #gets info puts "So you're #{age} old, #{height} tall and #{weight} heavy." <file_sep>/day_5/exercises/hashes.rb # In the exercises below, write your own code where indicated # to achieve the desired result. You should be able to run this # file from your terminal with the command `ruby day_6/exercises/arrays.rb` # example: Write code below to print a hash that holds grocery store inventory foods = {apples: 23, grapes: 507, eggs: 48} p foods # Write code below that will print a hash of animals and their number # at the zoo. (an inventory of animals) zoo ={apes: 23, lions: 507, zebras: 48} #YOUR CODE HERE p zoo # Using the zoo that you created above, print all the keys in the hash. zoo ={apes: 13, lions: 5, zebras: 8} #YOUR CODE HERE zoo.each do |animal, number| p "There are x number of #{animal} at the zoo" end p zoo.keys # Using the zoo that you created above, print all the values in the hash. zoo ={apes: 13, lions: 5, zebras: 8} #YOUR CODE HERE zoo.each do |animal, number| p "There are #{number} of animals at the zoo" end p zoo.values # Using the zoo taht you created above, print the value of the first item in # the hash zoo ={"apes" => 13, "lions"=> 5, "zebras"=> 8} #YOUR CODE HERE p zoo["apes"] p zoo.values.first # Add an animal to the zoo hash and print the updated hash. zoo ={"apes" => 13, "lions"=> 5, "zebras"=> 8} # YOUR CODE HERE zoo["tigers"]=4 zoo.each do |animal, number| puts "There are #{number} of #{animal} at the zoo" end <file_sep>/day_3/ex30.rb people = 30 cars = 40 trucks = 15 if cars > people #conditions the statment puts "We should take the cars." #prints a result elsif cars < people #conditions the statment puts "We should not take the cars." #prints a result else #default decision puts "We can't decide." #prints a result end #ends the program if trucks > cars #conditions the statment puts "That's too many trucks" elsif trucks < cars #conditions the statment puts "Maybe we coould take the trucks." #prints a result else #default decision puts "We still can't decide." #prints a result end #ends the program if people > trucks #conditions the statment puts "Alright, let's just take the trucks." #prints a result else #default decision puts "Fine, let's stay home then." #prints a result end #ends the program <file_sep>/day_6/student.rb class Student attr_accessor :first_name, :last_name, :primary_phone_number def introduction(target) puts "Hi, #{target} my name is #{first_name}!" end def favorite_number 7 end end aizar = Student.new aizar.first_name = "Aizar" aizar.introduction("Aurelia") puts "My favorite number is #{aizar.favorite_number}." <file_sep>/day_2/exercises/arrays.rb # In the exercises below, write your own code where indicated # to achieve the desired result. You should be able to run this # file from your terminal with the command `ruby day_2/exercises/arrays.rb` # example: write code below that will print an array of animals. # Store the array in a variable. animals = ["Zebra", "Giraffe", "Elephant"] puts animals # Write code below that will print an array of states. Store the array in a variable. states = ['Minnesota', 'Iowa', 'Texas'] p states #YOUR CODE HERE # Write code below that will print an array of foods. Store the array in a variable. foods = ['Tacos', 'Beans','Banana'] p foods # YOUR CODE HERE # example: Write code below that will print the number of elements in array of animals = ["Zebra", "Giraffe", "Elephant"]# animals from above. p animals.count p animals.length # Write code below that will print the number of elements in the array of #foods from above. foods = ["Hamburger", "Tacos","Cheesse","Grapes"] p foods.count p foods.length # YOUR CODE HERE # # Write code below that will print "Zebra" from the animals array animals = ["Zebra", "Giraffe", "Elephant"] p animals[0] # YOUR CODE HERE # # Write code below that will print the last item from the foods array. foods = ["Hamburger", "Tacos","Cheesse","Grapes"] p foods.last # YOUR CODE HERE # # Write code below that uses a method to add "lion" to the animals array and # # print the result animals = ["Zebra", "Giraffe", "Elephant"] p animals animals << "Lion" p animals animals.push("Lion")# YOUR CODE HERE # # Write code below that removes the last item of food from the foods array and # # print the result p foods = ["Hamburger", "Tacos","Cheesse","Grapes"] foods.pop p foods foods << "Grapes" p foods foods.delete("Grapes") p foods # YOUR CODE HERE
8f959d9c8cb2f1ef31b878788f8a4fff85ec924f
[ "Markdown", "Ruby" ]
25
Ruby
AizarCabrera/backend_prework
7c019878977c8e14501a1fa9a7f1600299b13a8b
2108d6044daadcff9490297f6a5295d766934cf2
refs/heads/master
<file_sep>package com.elacqua.opticmap.data.local import androidx.lifecycle.LiveData import androidx.room.* @Dao interface PlacesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addPlace(place: Place): Long @Delete suspend fun deletePlace(place: Place) @Query("select * from place") suspend fun getAllPlaces(): List<Place> }<file_sep>package com.elacqua.opticmap.data.local import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Entity @Parcelize data class Place( @PrimaryKey(autoGenerate = true) val id: Int = 0, val name: String = "", val latitude: Double = 0.0, val longitude: Double = 0.0, val date: String = "", val imageDir: String = "", ): Parcelable { @Ignore var address: Address = Address() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Place if (id != other.id) return false return true } override fun hashCode(): Int { var result = id result = (31 * result + latitude).toInt() result = (31 * result + longitude).toInt() result = 31 * result + date.hashCode() result = 31 * result + imageDir.hashCode() return result } }<file_sep>package com.elacqua.opticmap.ui.places import android.annotation.SuppressLint import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.elacqua.opticmap.R import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.util.byteArrayToBitmap import com.elacqua.opticmap.util.getBitmapFromUri import com.elacqua.opticmap.util.getDateFromEpoch import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList class PlaceRecyclerView(private val placeClickListener: PlaceClickListener) : RecyclerView.Adapter<PlaceRecyclerView.ViewHolder>() { private val places = ArrayList<Place>() fun setPlaces(newPlaces: List<Place>) { places.clear() places.addAll(newPlaces) notifyDataSetChanged() } fun removePlace(position: Int) { places.removeAt(position) notifyItemRemoved(position) } fun getItemAt(position: Int) = places[position] override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater .from(parent.context) .inflate(R.layout.places_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.onBind(position) holder.onClick(position) } override fun getItemCount() = places.size inner class ViewHolder(private val view: View) : RecyclerView.ViewHolder(view) { private val txtPlaceName: TextView = view.findViewById(R.id.txt_place_name) private val txtPlaceLocation: TextView = view.findViewById(R.id.txt_place_location) private val txtPlaceDate: TextView = view.findViewById(R.id.txt_place_date) private val imgPlaceOcr: ImageView = view.findViewById(R.id.img_place_ocr) @SuppressLint("SetTextI18n") fun onBind(position: Int) { txtPlaceName.text = places[position].name txtPlaceLocation.text = "${places[position].address.city} / ${places[position].address.country}" txtPlaceDate.text = getDateFromEpoch(places[position].date) if (places[position].imageDir.isNotEmpty()) { val bitmap = getBitmapFromUri(Uri.parse(places[position].imageDir), view.context.contentResolver) imgPlaceOcr.setImageBitmap(bitmap) } } fun onClick(position: Int) { view.setOnClickListener { placeClickListener.onPlaceClick(places[position]) } } } }<file_sep>package com.elacqua.opticmap.ocr interface TranslateResultListener { fun onSuccess(text: String) fun onFailure(message: String) }<file_sep>package com.elacqua.opticmap.ocr import android.content.Context import android.graphics.* import android.net.Uri import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.text.Text import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.TextRecognizer import com.google.mlkit.vision.text.TextRecognizerOptions import timber.log.Timber import kotlin.math.abs class MLKitOCRHandler(private val translator: MLTranslator) { fun runTextRecognition(image: InputImage, ocrResultListener: OCRResultListener<Text>) { val recognizer: TextRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS) recognizer.process(image) .addOnSuccessListener { texts -> ocrResultListener.onSuccess(texts) } .addOnFailureListener { e -> ocrResultListener.onFailure(e.stackTraceToString()) } } fun translateText( image: Bitmap, texts: Text, recognitionOptions: RecognitionOptions, ocrResultListener: OCRResultListener<Bitmap> ) { if (texts.textBlocks.size > 0) { val bitmap = image.copy(Bitmap.Config.ARGB_8888, true) when (recognitionOptions) { RecognitionOptions.TRANSLATE_BLOCKS -> processImageBlocks(texts, bitmap, ocrResultListener) RecognitionOptions.TRANSLATE_LINES -> processImageLines(texts, bitmap, ocrResultListener) RecognitionOptions.TRANSLATE_WHOLE -> processImageWhole(texts, bitmap, ocrResultListener) } } } fun ocrToSpeech(texts: Text, callback: TranslateResultListener) { translator.translate(texts.text, callback) } fun getImageFromUri(uri: Uri, context: Context): InputImage = InputImage.fromFilePath(context, uri) private fun processImageBlocks( texts: Text, bitmap: Bitmap, callback: OCRResultListener<Bitmap> ) { val blocks = texts.textBlocks val canvas = Canvas(bitmap) var textCount = 0 for (i in blocks.indices) { val lines = blocks[i].lines for (j in lines.indices) { val elements = lines[j].elements for (k in elements.indices) { val element = elements[k] translator.translate( element.text, object : TranslateResultListener { override fun onSuccess(text: String) { if (element.boundingBox != null) { drawBoxes(canvas, element.boundingBox!!, text) } if (++textCount >= blocks.size * lines.size * elements.size) { callback.onSuccess(bitmap) } } override fun onFailure(message: String) { Timber.e("processImageBlocks: $message") callback.onFailure(message) } }) } } } return } private fun processImageLines( texts: Text, bitmap: Bitmap, callback: OCRResultListener<Bitmap> ) { val blocks = texts.textBlocks val canvas = Canvas(bitmap) var lineCount = 0 for (i in blocks.indices) { val lines = blocks[i].lines for (j in lines.indices) { translator.translate( lines[j].text, object : TranslateResultListener { override fun onSuccess(text: String) { if (lines[j].boundingBox != null) { drawBoxes(canvas, lines[j].boundingBox!!, text) } if (++lineCount >= blocks.size * lines.size) { callback.onSuccess(bitmap) } } override fun onFailure(message: String) { Timber.e("processImageLines: $message") callback.onFailure(message) } }) } } return } private fun processImageWhole( texts: Text, bitmap: Bitmap, callback: OCRResultListener<Bitmap> ) { val blocks = texts.textBlocks val canvas = Canvas(bitmap) var lineCount = 0 for (i in blocks.indices) { translator.translate( blocks[i].text, object : TranslateResultListener { override fun onSuccess(text: String) { if (blocks[i].boundingBox != null) { drawBoxes(canvas, blocks[i].boundingBox!!, text) } if (++lineCount >= blocks.size) { callback.onSuccess(bitmap) } } override fun onFailure(message: String) { Timber.e("processImageLines: $message") callback.onFailure(message) } }) } return } private fun drawBoxes(canvas: Canvas, rect: Rect, text: String) { drawWhiteBox(canvas, rect) drawTextAccordingToBox(canvas, rect, text) } private fun drawWhiteBox(canvas: Canvas, rect: Rect) { val backgroundPaint = Paint() backgroundPaint.color = Color.WHITE canvas.drawRect(rect, backgroundPaint) } private fun drawTextAccordingToBox(canvas: Canvas, rect: Rect, text: String) { val paint = Paint() val tempRect = Rect() paint.color = Color.BLACK paint.getTextBounds(text, 0, text.length, tempRect) if (tempRect.width() < rect.width() && tempRect.height() < rect.height()) { calculateMaxTextSize(text, paint, rect.width().toFloat(), rect.height().toFloat()) } else { val newWidth = paint.measureText(text, 0, text.length) paint.textSize = abs(rect.width()) / newWidth * paint.textSize } canvas.drawText(text, rect.left.toFloat(), rect.bottom.toFloat(), paint) } private fun calculateMaxTextSize( text: String, paint: Paint, maxWidth: Float, maxHeight: Float ): Float { val bound = Rect() var size = 1.0f val step = 1.0f while (true) { paint.getTextBounds(text, 0, text.length, bound) if (bound.width() < maxWidth && bound.height() < maxHeight) { size += step paint.textSize = size } else { return size - step } } } fun closeTranslator() { translator.close() } }<file_sep>package com.elacqua.opticmap.ui.activity import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.elacqua.opticmap.R import com.elacqua.opticmap.databinding.ActivityMainBinding import com.elacqua.opticmap.util.Constant import com.elacqua.opticmap.util.UIState import com.elacqua.opticmap.util.getBitmapFromUri import com.google.android.material.bottomnavigation.BottomNavigationView import com.yalantis.ucrop.UCrop import timber.log.Timber import java.io.File class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) navView.setupWithNavController(navController) observeUIState() } private fun observeUIState() { UIState.isLoadingState.observe(this, { isLoadingState -> if (isLoadingState) { binding.viewProgressMain.visibility = View.VISIBLE binding.progressBarMain.visibility = View.VISIBLE } else { binding.viewProgressMain.visibility = View.GONE binding.progressBarMain.visibility = View.GONE } }) } @Suppress("DEPRECATION") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode) { UCrop.REQUEST_CROP -> { if (data != null) { val resultUri = UCrop.getOutput(data) navigateToOcrFragment(resultUri!!) } } UCrop.RESULT_ERROR -> { if (data != null) { Timber.e("onActivityResult: Crop error: ${UCrop.getError(data)}") } } } } private fun navigateToOcrFragment(imageUri: Uri) { val args = bundleOf(Constant.OCR_IMAGE_KEY to imageUri) findNavController(R.id.nav_host_fragment).navigate( R.id.action_navigation_home_to_ocrFragment, args ) } }<file_sep>package com.elacqua.opticmap.data import android.content.Context import android.location.Geocoder import com.elacqua.opticmap.data.local.Address import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.data.local.PlacesDao import java.util.* class LocalRepository(private val placesDao: PlacesDao) { suspend fun getAllPlaces(): List<Place> = placesDao.getAllPlaces() suspend fun deletePlaces(place: Place) = placesDao.deletePlace(place) suspend fun addPlace(place: Place): Long = placesDao.addPlace(place) fun getAddress(context: Context, lat: Double, long: Double): Address? { val geoCoder = Geocoder(context, Locale.getDefault()) val addresses = geoCoder.getFromLocation(lat, long, 1) return if (addresses.size > 0) { val adr = addresses[0] Address( adr.subLocality ?: "", adr.locality ?: Locale.getDefault().country, adr.getAddressLine(2) ?: Locale.getDefault().country ) } else { null } } }<file_sep>package com.elacqua.opticmap.ui.fragments import android.Manifest import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.location.Location import android.location.LocationManager import android.net.Uri import android.os.Bundle import android.os.Looper import android.provider.MediaStore import android.speech.tts.TextToSpeech import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.RadioButton import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.elacqua.opticmap.R import com.elacqua.opticmap.data.LocalRepository import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.data.local.PlacesDatabase import com.elacqua.opticmap.databinding.DialogSaveOcrBinding import com.elacqua.opticmap.databinding.FragmentOcrBinding import com.elacqua.opticmap.ocr.* import com.elacqua.opticmap.util.* import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.mlkit.vision.text.Text import timber.log.Timber import java.io.File import java.util.* class OcrFragment : Fragment(), TextToSpeech.OnInitListener { private lateinit var placesDatabase: PlacesDatabase private lateinit var ocrViewModel: OcrViewModel private lateinit var sharedPref: SharedPref private lateinit var tts: TextToSpeech private lateinit var ocr: MLKitOCRHandler private var binding: FragmentOcrBinding? = null private var imageUri: Uri? = null private var langFrom: Languages = Constant.DEFAULT_LANGUAGE private var langTo: Languages = Constant.DEFAULT_LANGUAGE override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) placesDatabase = PlacesDatabase.getInstance(requireContext()) ocrViewModel = ViewModelProvider( this, OcrViewModelFactory(LocalRepository(placesDatabase.getPlacesDao())) ).get(OcrViewModel::class.java) getArgs() initOCR() } private fun initOCR() { UIState.isLoadingState.value = true tts = TextToSpeech(requireContext().applicationContext, this) val translator = MLTranslator(langFrom, langTo) ocr = MLKitOCRHandler(translator) translator.downloadModel { success -> if (success) { recognizeText() } UIState.isLoadingState.value = false } } private fun recognizeText() { UIState.isLoadingState.value = true val img = ocr.getImageFromUri(imageUri!!, requireContext()) ocrViewModel.recognizeText(img, ocr) ocrViewModel.textsOnImage.observe(viewLifecycleOwner, { texts -> if (texts != null) { textToSpeech(texts) handleRadioButtons(texts) } UIState.isLoadingState.value = false }) } private fun textToSpeech(texts: Text) { UIState.isLoadingState.value = true binding!!.btnOcrVoice.setOnClickListener { ocr.ocrToSpeech(texts, object : TranslateResultListener { override fun onSuccess(text: String) { UIState.isLoadingState.value = false tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null) } override fun onFailure(message: String) { UIState.isLoadingState.value = false } }) } } private fun handleRadioButtons(text: Text) { binding!!.radioBtnOcrBlock.setOnCheckedChangeListener { btn, isChecked -> if (isChecked) { setLastRadioButton(text, RecognitionOptions.TRANSLATE_BLOCKS) } setRadioBtnTextColor(btn as RadioButton) } binding!!.radioBtnOcrLine.setOnCheckedChangeListener { btn, isChecked -> if (isChecked) { setLastRadioButton(text, RecognitionOptions.TRANSLATE_LINES) } setRadioBtnTextColor(btn as RadioButton) } binding!!.radioBtnOcrWhole.setOnCheckedChangeListener { btn, isChecked -> if (isChecked) { setLastRadioButton(text, RecognitionOptions.TRANSLATE_WHOLE) } setRadioBtnTextColor(btn as RadioButton) } when (sharedPref.lastSelectedRadioButton) { RecognitionOptions.TRANSLATE_BLOCKS.name -> { binding!!.radioBtnOcrBlock.isChecked = true } RecognitionOptions.TRANSLATE_LINES.name -> { binding!!.radioBtnOcrLine.isChecked = true } RecognitionOptions.TRANSLATE_WHOLE.name -> { binding!!.radioBtnOcrWhole.isChecked = true } } } private fun setLastRadioButton(text: Text, option: RecognitionOptions) { sharedPref.lastSelectedRadioButton = option.name getTextFromImage(text, option) } private fun setRadioBtnTextColor(btn: RadioButton) { if (btn.isChecked) { btn.setTextColor(ContextCompat.getColor(requireContext(), R.color.white)) } else { btn.setTextColor(ContextCompat.getColor(requireContext(), R.color.primary_color)) } } private fun getTextFromImage(text: Text, option: RecognitionOptions) { if (imageUri == null) { return } UIState.isLoadingState.value = true val bitmap = getBitmapFromUri(imageUri!!, requireContext().contentResolver) if (imageUri != null) { ocr.translateText(bitmap, text, option, object : OCRResultListener<Bitmap> { override fun onSuccess(result: Bitmap?) { UIState.isLoadingState.value = false if (result == null) { binding?.imgOcrPicture?.setImageURI(imageUri) } else { binding?.imgOcrPicture?.setImageBitmap(result) saveButtonHandler(result) } } override fun onFailure(message: String) { UIState.isLoadingState.value = false Timber.e("OCR failed: $message") binding?.imgOcrPicture?.setImageURI(imageUri) } }) } } private fun saveButtonHandler(img: Bitmap) { binding!!.btnOcrSave.setOnClickListener { if (this.imageUri == null) { return@setOnClickListener } createSaveDialog(img) } } private fun createSaveDialog(img: Bitmap) { val dialog = Dialog(requireContext()) dialog.run { val dialogBinding = DialogSaveOcrBinding.inflate(LayoutInflater.from(requireContext())) setContentView(dialogBinding.root) dialogBinding.txtPhotoName.requestFocus() window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) dialogBinding.btnDialogSave.setOnClickListener { val photoName = dialogBinding.txtPhotoName.text.toString() requestLocation { location -> val savedUri = saveImageToGallery(img) val lat = location.latitude val long = location.longitude val place = Place(0, photoName, lat, long, getEpochTime(), savedUri.toString()) ocrViewModel.savePlace(place) Toast.makeText(requireContext(), R.string.ocr_image_saved, Toast.LENGTH_SHORT).show() } dismiss() } dialogBinding.btnDialogCancel.setOnClickListener { dismiss() } show() } } private fun requestLocation(callback: (location: Location) -> Unit) { if (ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { findLocation(callback) } else { requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), Constant.LOCATION_PERM_CODE) } } @SuppressLint("MissingPermission") private fun findLocation(callback: (location: Location) -> Unit) { val locationManager = requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ) { val fusedLocationFinder = LocationServices.getFusedLocationProviderClient(requireContext()) fusedLocationFinder.lastLocation.addOnSuccessListener { location: Location? -> if (location != null) { callback(location) } else { val locationRequest = LocationRequest() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(5000) .setFastestInterval(1000) .setNumUpdates(1) val locationCallback = object : LocationCallback() { override fun onLocationResult(result: LocationResult?) { val loc = result?.lastLocation loc?.let { callback(loc) } } } fusedLocationFinder.requestLocationUpdates( locationRequest, locationCallback, Looper.myLooper()!! ) } } } } @Suppress("DEPRECATION") private fun saveImageToGallery(bitmap: Bitmap): Uri { val filename = "${System.currentTimeMillis()}.png" val url = MediaStore.Images.Media.insertImage( requireContext().contentResolver, bitmap, filename, "OpticMap image" ) return Uri.parse(url) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == Constant.LOCATION_PERM_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED ) { initOCR() } } private fun getArgs() { imageUri = arguments?.get(Constant.OCR_IMAGE_KEY) as Uri if (imageUri != null) { sharedPref = SharedPref(requireContext()) langFrom = Languages.getLanguageFromShortName(sharedPref.langFrom) langTo = Languages.getLanguageFromShortName(sharedPref.langTo) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentOcrBinding.inflate(inflater, container, false) return binding!!.root } override fun onPause() { tts.stop() super.onPause() } override fun onDestroy() { UIState.isLoadingState.value = false ocr.closeTranslator() tts.shutdown() binding = null deleteFiles(requireContext().cacheDir.absolutePath, ".png") super.onDestroy() } private fun deleteFiles(dirPath: String, ext: String) { val dir = File(dirPath) if (!dir.exists()) return val fList: Array<File> = dir.listFiles()!! for (f in fList) { if (f.name.endsWith(ext)) { Timber.e("File deleted: ${f.name}") f.delete() } } } override fun onInit(p0: Int) { if (p0 == TextToSpeech.SUCCESS) { tts.language = Locale.US } } }<file_sep>package com.elacqua.opticmap.ui.home import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.view.* import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.elacqua.opticmap.R import com.elacqua.opticmap.databinding.FragmentHomeBinding import com.elacqua.opticmap.util.Constant import com.elacqua.opticmap.util.Language import com.elacqua.opticmap.util.Languages import com.elacqua.opticmap.util.SharedPref import com.google.android.material.snackbar.Snackbar import com.otaliastudios.cameraview.CameraListener import com.otaliastudios.cameraview.PictureResult import com.yalantis.ucrop.UCrop import timber.log.Timber import java.io.File import java.io.FileOutputStream class HomeFragment : Fragment() { private val homeViewModel: HomeViewModel by viewModels() private var binding: FragmentHomeBinding? = null private var langFrom = Constant.DEFAULT_LANGUAGE.shortName private var langTo = Constant.DEFAULT_LANGUAGE.shortName override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (!checkInternetStatus()) { showNoInternetSnackbar() } setLanguages() requestCameraPermission() binding?.run { btnLanguageFrom.setOnClickListener { createLanguageDialog(Language.FROM) } btnLanguageTo.setOnClickListener { createLanguageDialog(Language.TO) } btnHomeGallery.setOnClickListener { takeImageFromGallery() } } } private fun setCameraView() { binding?.run { camera.apply { setLifecycleOwner(viewLifecycleOwner) addCameraListener(object : CameraListener() { override fun onPictureTaken(result: PictureResult) { result.toBitmap { picture -> picture?.let { image -> if (isLanguageSelected()) { val imageUri = saveImgToCache(image) navigateToUCrop(imageUri) } } } } }) } btnTakePicture.setOnClickListener { camera.takePicture() } } } private fun saveImgToCache(image: Bitmap): Uri { val outputDir = requireContext().cacheDir val outputFile = File.createTempFile( System.currentTimeMillis().toString(), ".png", outputDir ) val stream = FileOutputStream(outputFile.absolutePath) image.compress(Bitmap.CompressFormat.PNG, 100, stream) stream.close() return Uri.fromFile(outputFile) } private fun navigateToUCrop(imageUri: Uri) { val outputDir = requireContext().cacheDir val outputFile = File.createTempFile( System.currentTimeMillis().toString(), ".png", outputDir ) val options = UCrop.Options().apply { setFreeStyleCropEnabled(true) setCompressionQuality(100) setToolbarColor(ContextCompat.getColor(requireContext(), R.color.edit_toolbar)) setStatusBarColor(ContextCompat.getColor(requireContext(), R.color.edit_status_bar)) setToolbarTitle(getString(R.string.edit_photo)) setActiveControlsWidgetColor(ContextCompat.getColor(requireContext(), R.color.primary_color)) setCropFrameStrokeWidth(0) } UCrop.of(imageUri, Uri.fromFile(outputFile)) .withOptions(options) .start(requireActivity()) } private fun takeImageFromGallery() { if (!isLanguageSelected()) { return } val photoPickIntent = Intent(Intent.ACTION_PICK) photoPickIntent.type = "image/*" startActivityForResult(photoPickIntent, Constant.IMAGE_PICK_INTENT_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode != AppCompatActivity.RESULT_OK) { return } when(requestCode) { Constant.IMAGE_PICK_INTENT_CODE -> { try { val imageUri: Uri? = data?.data if (imageUri != null) { navigateToUCrop(imageUri) } else { Timber.e("Gallery image uri is null") } } catch (e: Exception) { Timber.e(e) } } } } private fun isLanguageSelected(): Boolean { return if (binding?.btnLanguageFrom?.text == getString(R.string.home_button_from) || binding?.btnLanguageTo?.text == getString(R.string.home_button_to) ) { Toast.makeText(requireContext(), R.string.home_select_language, Toast.LENGTH_SHORT) .show() false } else { true } } private fun createLanguageDialog(type: Language) { val builder = AlertDialog.Builder(requireContext()) builder.run { setTitle(R.string.home_dialog_title) setSingleChoiceItems(Languages.availableLanguages(), -1) { dialog, selectedIndex -> val pref = SharedPref(requireContext()) if (type == Language.FROM) { langFrom = Languages.values()[selectedIndex].shortName pref.langFrom = langFrom binding?.btnLanguageFrom?.text = Languages.getLanguageFromShortName(langFrom).name } else { langTo = Languages.values()[selectedIndex].shortName pref.langTo = langTo binding?.btnLanguageTo?.text = Languages.getLanguageFromShortName(langTo).name } dialog.dismiss() } create() show() } } @Suppress("DEPRECATION") private fun checkInternetStatus(): Boolean { val connectivityManager = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val networkCapabilities = connectivityManager.activeNetwork ?: return false val actNw = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false return when { actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true actNw.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true else -> false } } else { val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo return activeNetwork?.isConnectedOrConnecting ?: false } } private fun showNoInternetSnackbar() { Snackbar.make( binding!!.relativeLayoutHome, R.string.home_no_internet, Snackbar.LENGTH_LONG ) .setAction(R.string.home_open_settings) { openSettings() } .show() } private fun openSettings() { val intent = Intent(Settings.ACTION_SETTINGS) startActivity(intent) } private fun setLanguages() { val pref = SharedPref(requireContext()) langFrom = pref.langFrom langTo = pref.langTo binding?.btnLanguageFrom?.text = Languages.getLanguageFromShortName(langFrom).name binding?.btnLanguageTo?.text = Languages.getLanguageFromShortName(langTo).name } private fun requestCameraPermission() { if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) { requestPermissions( arrayOf(Manifest.permission.CAMERA), Constant.CAMERA_REQUEST_CODE ) } else { setCameraView() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == Constant.CAMERA_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED ) { setCameraView() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { removeStatusBar() binding = FragmentHomeBinding.inflate(inflater, container, false) return binding!!.root } @Suppress("DEPRECATION") private fun removeStatusBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { requireActivity().window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { requireActivity().window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } } override fun onPause() { super.onPause() binding!!.camera.close() } override fun onResume() { super.onResume() binding!!.camera.open() } override fun onDestroyView() { super.onDestroyView() binding = null } }<file_sep>package com.elacqua.opticmap.util import android.content.ContentResolver import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.net.Uri import android.os.Build import android.provider.MediaStore import androidx.lifecycle.MutableLiveData import java.io.ByteArrayOutputStream import java.text.SimpleDateFormat import java.util.* object Constant { // Shared Preferences const val APP_SHARED_PREFS = "Shared Pref" const val PREF_FROM_LANGUAGE_KEY = "OCR_FROM_LANGUAGE_KEY" const val PREF_TO_LANGUAGE_KEY = "OCR_TO_LANGUAGE_KEY" const val PREF_OCR_RADIO_BUTTON = "PREF_OCR_RADIO_BUTTON" // Args const val OCR_IMAGE_KEY = "OCR_IMAGE_KEY" const val PLACE_ARG_KEY = "PLACE_ARG_KEY" const val IMAGE_PICK_INTENT_CODE = 10 const val CAMERA_REQUEST_CODE = 11 const val LOCATION_PERM_CODE = 13 val DEFAULT_LANGUAGE = Languages.English } object UIState { var isLoadingState = MutableLiveData(false) } fun getBitmapFromUri(uri: Uri, contentResolver: ContentResolver): Bitmap { return if (Build.VERSION.SDK_INT < 28) { MediaStore.Images.Media.getBitmap(contentResolver, uri) } else { val source = ImageDecoder.createSource(contentResolver, uri) ImageDecoder.decodeBitmap(source) } } // milliseconds since the epoch fun getEpochTime(): String { return System.currentTimeMillis().toString() } // milliseconds since the epoch fun getDateFromEpoch(epoch: String): String { val date = Date(epoch.toLong()) val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) return formatter.format(date) } fun bitmapToByteArray(bitmap: Bitmap): ByteArray { val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) return stream.toByteArray() } fun byteArrayToBitmap(bytes: ByteArray): Bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) <file_sep>package com.elacqua.opticmap.util enum class Languages(val shortName: String) { Catalan("ca"), Danish("da"), Dutch("nl"), English("en"), Finnish("fi"), French("fr"), German("de"), Hungarian("hu"), Italian("it"), Norwegian("no"), Polish("pl"), Portugese("pt"), Romanian("ro"), Spanish("es"), Swedish("sv"), Tagalog("tl"), Turkish("tr"); companion object { fun availableLanguages(): Array<String> { val langList = ArrayList<String>() for (lang in values()) { langList.add(lang.name) } return langList.toTypedArray() } fun getLanguageFromShortName(_shortName: String): Languages { var result = Constant.DEFAULT_LANGUAGE for (lang in values()) { if (lang.shortName == _shortName) { result = lang } } return result } } } enum class Language { FROM,TO }<file_sep>package com.elacqua.opticmap.ocr enum class RecognitionOptions { TRANSLATE_BLOCKS, TRANSLATE_LINES, TRANSLATE_WHOLE, } <file_sep>package com.elacqua.opticmap.data.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database( entities = [Place::class], version = 1, exportSchema = false ) abstract class PlacesDatabase: RoomDatabase() { abstract fun getPlacesDao(): PlacesDao companion object { private const val DATABASE_NAME = "PlacesDatabase" @Volatile private lateinit var instance: PlacesDatabase fun getInstance(context: Context): PlacesDatabase { synchronized(this) { if (!::instance.isInitialized) { instance = Room.databaseBuilder(context, PlacesDatabase::class.java, DATABASE_NAME) .fallbackToDestructiveMigration() .build() } return instance } } } }<file_sep>package com.elacqua.opticmap.ui.fragments import androidx.lifecycle.* import com.elacqua.opticmap.data.LocalRepository import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.ocr.MLKitOCRHandler import com.elacqua.opticmap.ocr.OCRResultListener import com.elacqua.opticmap.ui.places.PlacesViewModel import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.text.Text import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import timber.log.Timber class OcrViewModel(private val localRepository: LocalRepository) : ViewModel() { private val _textsOnImage = MutableLiveData<Text?>() val textsOnImage: LiveData<Text?> = _textsOnImage fun recognizeText( image: InputImage, ocr: MLKitOCRHandler ) { ocr.runTextRecognition(image, object: OCRResultListener<Text> { override fun onSuccess(result: Text?) { _textsOnImage.value = result } override fun onFailure(message: String) { _textsOnImage.value = null Timber.e(message) } }) } fun savePlace(place: Place) { viewModelScope.launch(Dispatchers.IO) { localRepository.addPlace(place) } } } @Suppress("UNCHECKED_CAST") class OcrViewModelFactory(private val localRepository: LocalRepository): ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return OcrViewModel(localRepository) as T } }<file_sep>package com.elacqua.opticmap.ui.fragments import android.annotation.SuppressLint import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.databinding.FragmentPlaceBinding import com.elacqua.opticmap.util.Constant import com.elacqua.opticmap.util.byteArrayToBitmap import com.elacqua.opticmap.util.getBitmapFromUri import com.elacqua.opticmap.util.getDateFromEpoch class PlaceFragment : Fragment() { private var binding: FragmentPlaceBinding? = null private var place: Place? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) getArgs() setViews() } private fun getArgs() { place = arguments?.get(Constant.PLACE_ARG_KEY) as Place } @SuppressLint("SetTextI18n") private fun setViews() { if (place == null) { return } binding!!.txtPlaceFragmentName.text = place!!.name binding!!.txtPlaceFragmentAddress.text = "${place!!.address.address} ${place!!.address.city} / ${place!!.address.country}" val date = getDateFromEpoch(place!!.date) binding!!.txtPlaceFragmentDate.text = date if (place!!.imageDir.isNotEmpty()) { val bitmap = getBitmapFromUri(Uri.parse(place!!.imageDir), requireContext().contentResolver) binding!!.imgPlaceFragment.setImageBitmap(bitmap) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentPlaceBinding.inflate(layoutInflater, container, false) return binding!!.root } }<file_sep>package com.elacqua.opticmap.ui.places import android.content.Context import androidx.lifecycle.* import com.elacqua.opticmap.data.LocalRepository import com.elacqua.opticmap.data.local.Place import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class PlacesViewModel(private val localRepository: LocalRepository) : ViewModel() { private val _places = MutableLiveData<List<Place>>() val places: LiveData<List<Place>> = _places fun getPlaces(context: Context) { viewModelScope.launch(Dispatchers.IO) { val result = localRepository.getAllPlaces() for (place in result) { val adr = localRepository.getAddress(context, place.latitude, place.longitude) if (adr != null) { place.address = adr } } _places.postValue(result) } } fun deletePlace(place: Place) { viewModelScope.launch(Dispatchers.IO) { localRepository.deletePlaces(place) } } } @Suppress("UNCHECKED_CAST") class PlacesViewModelFactory(private val localRepository: LocalRepository): ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return PlacesViewModel(localRepository) as T } }<file_sep>package com.elacqua.opticmap.ui.home import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { }<file_sep>package com.elacqua.opticmap.ocr import com.elacqua.opticmap.util.Languages import com.google.mlkit.common.model.DownloadConditions import com.google.mlkit.nl.translate.Translation import com.google.mlkit.nl.translate.Translator import com.google.mlkit.nl.translate.TranslatorOptions import timber.log.Timber class MLTranslator(langFrom: Languages, langTo: Languages) { private var translator: Translator init { val options: TranslatorOptions = TranslatorOptions.Builder() .setSourceLanguage(langFrom.shortName) .setTargetLanguage(langTo.shortName) .build() translator = Translation.getClient(options) } fun downloadModel(downloadOnFinish: (Boolean) -> Unit) { val conditions = DownloadConditions.Builder().build() translator.downloadModelIfNeeded(conditions) .addOnSuccessListener { downloadOnFinish(true) } .addOnFailureListener { exception -> Timber.e("downloadModel: ${exception.message}") downloadOnFinish(false) } } fun translate(text: String, callback: TranslateResultListener) { translator.translate(text) .addOnSuccessListener { result -> callback.onSuccess(result) } .addOnFailureListener { exception -> callback.onFailure(exception.stackTraceToString()) } } fun close() { translator.close() } }<file_sep>package com.elacqua.opticmap.ui.places import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.elacqua.opticmap.R import com.elacqua.opticmap.data.LocalRepository import com.elacqua.opticmap.data.local.Place import com.elacqua.opticmap.data.local.PlacesDatabase import com.elacqua.opticmap.databinding.FragmentPlacesBinding import com.elacqua.opticmap.util.Constant class PlacesFragment : Fragment() { private var binding: FragmentPlacesBinding? = null private lateinit var placesDatabase: PlacesDatabase private lateinit var placeRecyclerView: PlaceRecyclerView private lateinit var placesViewModel: PlacesViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) placesDatabase = PlacesDatabase.getInstance(requireContext()) placesViewModel = ViewModelProvider( this, PlacesViewModelFactory(LocalRepository(placesDatabase.getPlacesDao())) ).get(PlacesViewModel::class.java) initRecyclerView() observePlacesData() placesViewModel.getPlaces(requireContext()) } private fun observePlacesData() { placesViewModel.places.observe(viewLifecycleOwner, { placeRecyclerView.setPlaces(it) }) } private fun initRecyclerView() { placeRecyclerView = PlaceRecyclerView(object : PlaceClickListener { override fun onPlaceClick(place: Place) { val args = bundleOf(Constant.PLACE_ARG_KEY to place) findNavController().navigate( R.id.action_navigation_places_to_placeFragment, args ) } }) binding!!.rvPlaces.run { adapter = placeRecyclerView layoutManager = GridLayoutManager(requireContext(), 2) setHasFixedSize(true) addItemDecoration(GridSpacingItemDecoration(2, 50, true)) } val swipe = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { placesViewModel.deletePlace(placeRecyclerView.getItemAt(viewHolder.adapterPosition)) placeRecyclerView.removePlace(viewHolder.adapterPosition) } } ItemTouchHelper(swipe).attachToRecyclerView(binding!!.rvPlaces) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentPlacesBinding.inflate(layoutInflater, container, false) return binding!!.root } override fun onDestroy() { binding = null super.onDestroy() } }<file_sep>package com.elacqua.opticmap.ui.places import com.elacqua.opticmap.data.local.Place interface PlaceClickListener { fun onPlaceClick(place: Place) }<file_sep>package com.elacqua.opticmap.ocr interface OCRResultListener<T> { fun onSuccess(result: T?) fun onFailure(message: String) }<file_sep>package com.elacqua.opticmap.data.local import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Address(val address: String = "", val city: String = "", val country: String = ""): Parcelable<file_sep># OpticMap OpticMap is a on-device optical character recognition Android application. Internet connection only needed for downloading models when a language selected first time. It can can recognize text in any Latin-based character set and can translate recognized texts. It supports Catalan, Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Polish, Portugese, Romanian, Spanish, Swedish, Tagalog, Turkish; - Recognize text on images and translate recognized texts. - Text to speech - Images can be coming from gallery or camera - Save image with recognized text on it - Saved images carries additional informations such as location, name of the place, address, date - List all saved images ### Tech * MVVM architecture * Single activity multiple fragments * MlKit Translate for translation * TextToSpeech * MlKit Text Recognition for OCR * Coroutine for async tasks * LiveData * Timber for logging * uCrop for cropping images * CameraView (otaliastudios) for camera preview and taking picturs * Room for local database * ViewModel * SharedPreference ### Screenshots: <p align="center"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-123903_OpticMap.jpg?raw=true" width="200"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-123939_OpticMap.jpg?raw=true" width="200"> <img src="https://raw.githubusercontent.com/etasdemir/OpticMap/master/screens/Screenshot_20210619-124004_OpticMap.jpg?raw=true" width="200"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-133450_OpticMap.jpg?raw=true" width="200"> </p> <br> <p align="center"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-125538_OpticMap.jpg?raw=true" width="200"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-125944_OpticMap.jpg?raw=true" width="200"> <img src="https://github.com/etasdemir/OpticMap/blob/master/screens/Screenshot_20210619-125951_OpticMap.jpg?raw=true" width="200"> </p> License ---- OpticMap is licensed under the Apache License, Version 2.0. See LICENSE for the full license text. <file_sep>package com.elacqua.opticmap.util import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import com.elacqua.opticmap.ocr.RecognitionOptions @SuppressLint("CommitPrefEdits") class SharedPref(context: Context) { private val _sharedPrefs: SharedPreferences = context.getSharedPreferences(Constant.APP_SHARED_PREFS, Context.MODE_PRIVATE) private val _prefsEditor: SharedPreferences.Editor = _sharedPrefs.edit() var langFrom: String get() = _sharedPrefs.getString(Constant.PREF_FROM_LANGUAGE_KEY, Constant.DEFAULT_LANGUAGE.shortName)!! set(value) = _prefsEditor.putString(Constant.PREF_FROM_LANGUAGE_KEY, value).apply() var langTo: String get() = _sharedPrefs.getString(Constant.PREF_TO_LANGUAGE_KEY, Constant.DEFAULT_LANGUAGE.shortName)!! set(value) = _prefsEditor.putString(Constant.PREF_TO_LANGUAGE_KEY, value).apply() var lastSelectedRadioButton: String get() = _sharedPrefs.getString(Constant.PREF_OCR_RADIO_BUTTON, RecognitionOptions.TRANSLATE_BLOCKS.name)!! set(value) = _prefsEditor.putString(Constant.PREF_OCR_RADIO_BUTTON, value).apply() }
cdcf547dc459bdaffebc84da3b21659502691a5e
[ "Markdown", "Kotlin" ]
24
Kotlin
etasdemir/OpticMap
72bfb9c95a3d3af7e0eb38d5814aa1760a84783d
67fa10ac6cda0e7a5d5d13dcdcf959677f71f3c6
refs/heads/master
<repo_name>Godis91/A-simple-Todo-App<file_sep>/src/components/About.js import React from 'react' const About = () => { return ( <div className="container"> <h3 className="center">About</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur totam ratione accusantium cum a dolore voluptates autem laboriosam numquam, quod repellat iusto fugiat suscipit quidem incidunt sequi aliquam soluta accusamus.</p> </div> ) } export default About <file_sep>/src/reducers/rootReducer.js const initState = { posts: [ { id: '1', title: 'My first day in school', body: 'Lorem ipsum dolor enetur ad at! Mollitia fugit elit. Perferendis, nisi temporibus. Aliquam, minus ullamsit amet consectetur adipisicing elit. Facere, magni. Voluptates quibusdam impedit dolores!'}, { id: '2', title: 'The journey begins', body: 'exercitationem illo voluptate tenetur ad at! Mollitia fugit elit. Perferendis, neque architecto facilis veniam nemo eligendi reiciendis ratione solutanisi temporibus. Aliquam, minus ullam.'}, { id: '3', title: 'The lord of the rings', body: 'Fugit, neque architecto facilis veniam nemo Mollitia fugit elit. Perferendis,eligendi reiciendis ratione soluta itaque in maiores molestias vero nostrum'} ] } const rootReducer = (state = initState, action) => { if(action.type === 'DELETE_POST'){ let newPosts = state.posts.filter(post => { return action.id !== post.id }); return { ...state, posts:newPosts } } return state; } export default rootReducer;<file_sep>/src/components/Contact.js import React from 'react' const Contact = (props) => { console.log(props) return ( <div className="container"> <h3 className="center">Contact</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur totam ratione accusantium cum a dolore voluptates autem laboriosam numquam, quod repellat iusto fugiat suscipit quidem incidunt sequi aliquam soluta accusamus.</p> </div> ) } export default Contact
e8e4e6abe7fa80e30c6783177de7dd1cb552e68a
[ "JavaScript" ]
3
JavaScript
Godis91/A-simple-Todo-App
3c07c33dfc3e0df2841bf28d9aa39a71389e4641
0655b1c42a37034c902fcd4cd7461bea7931db7e
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <title>PaginaPrincipal</title> <link rel="stylesheet" type="text/css" href="estilo/layout.css"/> <link href="https://fonts.googleapis.com/css?family=News+Cycle|Patua+One&display=swap" rel="stylesheet"> </head> <body> <?php include("todos/header.php"); ?> <article class="col-12 col-m-12 col-x-12"> <p>PESQUISA, EXTENSSÃO, DESENVOLVIMENTO...</p> <h1>Explore o Conhecimento!</h1> </article> <main class="col-12 col-m-12 col-x-12 magem"> <a href=""><aside class="col-3 col-m-3 col-x-3 materia"><h1>Português</h1></aside></a> <a href=""><aside class="col-3 col-m-3 col-x-3 materia"><h1>História</h1></aside></a> <a href=""><aside class="col-3 col-m-3 col-x-3 materia"><h1>Informática</h1></aside></a> <h1 id="h1estilo" class="col-11 col-m-11 col-x-11">----------- TOP 3 MAIS VISTOS ----------</h1> <a href=""><aside class="col-3 col-m-3 col-x-3"> <p class="box">1º</p> <h1>Feminismo nas escolas</h1> <p class="pAside">Elabora meios de ensinar o significado de empoderamento para meninas.</p> <p class="p2"><NAME> e <NAME></p> </aside></a> <a href=""><aside class="col-3 col-m-3 col-x-3"> <p class="box">2º</p> <h1>Racismo no século XX</h1> <p class="pAside">O artigo aborda o racismo nos EUA no século XX.</p> <p class="p2"><NAME> e <NAME></p> </aside></a> <a href=""><aside class="col-3 col-m-3 col-x-3"> <p class="box">3º</p> <h1>Letras de Rap e Funk</h1> <p class="pAside">Identifica quais as principais caracteristicas das letras de rap e funk.</p> <p class="p2"><NAME> e <NAME></p> </aside></a> </main> </aside> <?php include("todos/footer.php"); ?> </body> </html><file_sep># amostraif Projeto para a matéria de Construções de páginas web que visa acessibilizar ao artigos acadêmicos dos institutos federais
33e171bc6c94c577304125107f5f749f6a164b15
[ "Markdown", "PHP" ]
2
PHP
nataliaflores/amostraif
53c3003454b79a778ff2a0df2dce02ec064551b6
ad5484150119d42862f39450738dad77120743d4
refs/heads/master
<file_sep><?php class Zo_Customization_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View { public function tessst() { return "zerzerzerzer"; } }
8ed1d8b3a735167f2687d080e4f40117c0932ccd
[ "PHP" ]
1
PHP
neilyc/zo
84c2bd3a867a33bdd478bf29c4a978860bdf03c2
cd988458b01025aeed0400beadd9a40a55a2fb4e
refs/heads/master
<file_sep>#include "plugin.h" #include "CFont.h" #include "CTimer.h" #include "CCamera.h" #include "extensions/ScriptCommands.h" #include "CTxdStore.h" #include "CMessages.h" #include "CCoronas.h" #include "CSprite.h" #include "CModelInfo.h" #include "CFileMgr.h" #include "map" using namespace plugin; // GV1 CVector2D mousePos = CVector2D(0.0f, 0.0f); //std::fstream lg; std::list< std::list<const char*>> ListPatterns; //std::list<char*> screenLogMessages; static CSprite2d mouseSprite; bool bMouseDown = false; bool menu_showGUI = false; int menu_editingModelIndex = 0; int menu_onScreen = 0; int menu_editingCorona = 0; int menu_subPage = 0; // Functions 1 void InitPatterns() { std::list<const char*> pattern; pattern.push_back("1,1,0,160"); pattern.push_back("0,0,0,50"); pattern.push_back("0,0,1,160"); pattern.push_back("0,0,0,50"); ListPatterns.push_back(pattern); pattern.clear(); pattern.push_back("1,1,1,60"); pattern.push_back("0,0,0,60"); pattern.push_back("1,1,1,60"); pattern.push_back("0,0,0,300"); ListPatterns.push_back(pattern); pattern.clear(); pattern.push_back("1,1,0,60"); pattern.push_back("0,0,0,60"); pattern.push_back("1,1,0,60"); pattern.push_back("0,0,0,300"); pattern.push_back("0,1,1,60"); pattern.push_back("0,0,0,60"); pattern.push_back("0,1,1,60"); pattern.push_back("0,0,0,300"); ListPatterns.push_back(pattern); pattern.clear(); pattern.push_back("1,1,0,80"); pattern.push_back("0,0,0,60"); pattern.push_back("1,1,0,80"); pattern.push_back("0,0,0,60"); pattern.push_back("1,1,0,80"); pattern.push_back("0,0,0,300"); pattern.push_back("0,1,1,80"); pattern.push_back("0,0,0,60"); pattern.push_back("0,1,1,80"); pattern.push_back("0,0,0,60"); pattern.push_back("0,1,1,80"); pattern.push_back("0,0,0,300"); ListPatterns.push_back(pattern); pattern.clear(); } int GetNumberOfSteps(int patternId) { int i = 0; std::list< std::list<const char*>>::iterator it; for (it = ListPatterns.begin(); it != ListPatterns.end(); ++it) { if (i == patternId) { return (*it).size(); } i++; } return 0; } void GetPatternStep(int patternId, int step, bool& left, bool& middle, bool& right, int& delay) { int i[2] = { 0, 0 }; std::list< std::list<const char*>>::iterator it; for (it = ListPatterns.begin(); it != ListPatterns.end(); ++it) { if (i[0] == patternId) { break; } i[0]++; } std::list<const char*>::iterator it_; for (it_ = (*it).begin(); it_ != (*it).end(); ++it_) { if (i[1] == step) { break; } i[1]++; } int str_i = 0; size_t pos = 0; std::string token; std::string str = (*it_); while ((pos = str.find(",")) != std::string::npos) { token = str.substr(0, pos); int val = atoi(token.c_str()); if (str_i == 0) { left = val; } if (str_i == 1) { middle = val; } if (str_i == 2) { right = val; } str.erase(0, pos + 1); str_i++; } delay = atoi(str.c_str()); } float ScreenPosX(float x) { return (x * (SCREEN_COORD_CENTER_X * 2)) / 800.0f; } float ScreenPosY(float y) { return (y * (SCREEN_COORD_CENTER_Y * 2)) / 600.0f; } float clampf(float n, float lower, float upper) { return (std::max)(lower, (std::min)(n, upper)); } float GetAngleBetweenVectors(CVector v1, CVector v2, CVector v3) { float v12 = sqrt(pow(v1.x - v2.x, 2) + pow(v1.y - v2.y, 2)); float v13 = sqrt(pow(v1.x - v3.x, 2) + pow(v1.y - v3.y, 2)); float v23 = sqrt(pow(v2.x - v3.x, 2) + pow(v2.y - v3.y, 2)); return acos((pow(v12, 2) + pow(v13, 2) - pow(v23, 2)) / (2 * v12 * v13)); } // Classes class Input { public: int type = 0; float x = 0.0f; float y = 0.0f; float w = 0.0f; float h = 0.0f; bool show = false; bool mouseOver, mouseOverL, mouseOverR = false; char stringText[256]; char floatTitle[256]; float floatValue = 0.0; float floatMin = 0.0; float floatMax = 0.0; int selection_current = 1; int selection_min = 1; int selection_max = 2; bool holdToAdd = false; CRGBA bgColor = CRGBA(122, 122, 122, 255); CRGBA bgColorHover = CRGBA(73, 73, 73, 255); CRGBA bgColorDisabled = CRGBA(20, 20, 20, 255); bool useIcon = false; CRGBA iconMainColor; CRGBA iconSecondaryColor; bool iconUseSecondary = false; Input(int type, float x, float y, float w, float h) { this->type = type; this->x = x; this->y = y; this->w = w; this->h = h; } void SetCoronaIcon(CRGBA mainColor, bool useSecondary, CRGBA secodarycolor) { useIcon = true; iconMainColor = mainColor; iconSecondaryColor = secodarycolor; iconUseSecondary = useSecondary; } void SetAsHoldToAdd() { holdToAdd = true; } void SetBackgroundColor(CRGBA color) { bgColor = color; } void SetBackgroundColorHover(CRGBA color) { bgColorHover = color; } void SetText(char* text) { sprintf(stringText, "%s", text); } void SetFloatEditorSettings(char* text, float min, float max) { sprintf(floatTitle, "%s", text); floatMin = min; floatMax = max; } void SetSelection(int value, int min, int max) { selection_current = value; selection_min = min; selection_max = max; } void Draw() { float sx = ScreenPosX(x); float sy = ScreenPosY(y); float sw = ScreenPosX(w); float sh = ScreenPosY(h); CFont::SetOrientation(ALIGN_CENTER); CFont::SetDropShadowPosition(1); CFont::SetBackground(false, false); CFont::SetScale(ScreenPosX(0.3), ScreenPosY(0.9)); CFont::SetFontStyle(FONT_SUBTITLES); CFont::SetProportional(true); CFont::SetColor(CRGBA(255, 255, 255, 255)); if (type == 0 || type == 2) { mouseOver = (mousePos.x >= sx && mousePos.x < (sx + sw) && mousePos.y >= sy && mousePos.y < (sy + sh)); CSprite2d::DrawRect(CRect(sx, sy, sx + sw, sy + sh), mouseOver ? bgColorHover : bgColor); if (type == 2) { sprintf(stringText, "%.2f", floatValue); } CFont::PrintString(sx + sw / 2, sy + ScreenPosY(1.0f), stringText); if (useIcon) { CRect rectMain = CRect(sx + 3, sy + 3, sx + sh - 3, sy + sh - 3); CSprite2d::DrawRect(rectMain, CRGBA(0, 0, 0, 255)); CSprite2d::DrawRect(CRect(rectMain.left+2, rectMain.top+2, rectMain.right-2, rectMain.bottom-2), iconMainColor); if (iconUseSecondary) { CRect rectSecondary = CRect(rectMain.right + 6, rectMain.top, rectMain.right + sh, rectMain.bottom); CSprite2d::DrawRect(rectSecondary, CRGBA(0, 0, 0, 255)); CSprite2d::DrawRect(CRect(rectSecondary.left + 2, rectSecondary.top + 2, rectSecondary.right - 2, rectSecondary.bottom - 2), iconSecondaryColor); } } } if (type == 1) { CRect buttonLess = CRect(sx, sy, sx+sh, sy+sh); CRect inputVal = CRect(buttonLess.right + 5, sy, buttonLess.right + 5 + sw, sy+sh); CRect buttonMore = CRect(inputVal.right + 5, sy, inputVal.right + 5 + sh, sy + sh); mouseOverL = (mousePos.x >= buttonLess.left && mousePos.x < buttonLess.right && mousePos.y >= buttonLess.top && mousePos.y < buttonLess.bottom); mouseOverR = (mousePos.x >= buttonMore.left && mousePos.x < buttonMore.right && mousePos.y >= buttonMore.top && mousePos.y < buttonMore.bottom); CSprite2d::DrawRect(buttonLess, (selection_min == selection_current) ? bgColorDisabled : (mouseOverL ? bgColorHover : bgColor)); CSprite2d::DrawRect(inputVal, CRGBA(68, 68, 68, 255)); CSprite2d::DrawRect(buttonMore, (selection_max == selection_current) ? bgColorDisabled : (mouseOverR ? bgColorHover : bgColor)); CFont::PrintString(inputVal.left + sw / 2, sy + ScreenPosY(1.0f), stringText); } if (type == 2) { //CSprite2d::DrawCircleAtNearClip(CVector2D(sx, sy), 12.0f, CRGBA(255, 255, 255, 255), 180); //CSprite2d::DrawCircleAtNearClip(CVector2D(sx, sy), 10.0f, CRGBA(20, 20, 20, 255), 180); } } }; class CoronaData { public: int type = 0; eCoronaFlareType flareType = eCoronaFlareType::FLARETYPE_NONE; int direction = 1; int numberOfSubCoronas = 2; unsigned char red = 255; unsigned char green = 0; unsigned char blue = 0; unsigned char alpha = 255; unsigned char sec_red = 0; unsigned char sec_green = 0; unsigned char sec_blue = 255; unsigned char sec_alpha = 255; unsigned char bigFlash_alpha = 20; int initialPattern = 0; float radius = 0.2f; float x = 0.0f; float y = 0.0f; float z = 1.0f; float nearClip = 0.8f; float farClip = 200.0f; float bigFlashRadius = 6.0f; bool useSecondaryColor = false; bool useBigFlash = false; float distanceBetweenCoronas = 0.3f; }; class ModelConfig { public: unsigned short modelIndex; int numberOfCoronas = 0; std::list<CoronaData*>Coronas; ModelConfig(unsigned short modelIndex) { this->modelIndex = modelIndex; } void CreateCorona() { CoronaData* coronaData = new CoronaData(); Coronas.push_back(coronaData); numberOfCoronas++; } void RemoveCorona(CoronaData* corona) { std::list<CoronaData*>::iterator it; for (it = Coronas.begin(); it != Coronas.end(); ++it) { if ((*it) == corona) { Coronas.erase(it); numberOfCoronas--; return; } } } CoronaData* GetCorona(int id) { int i = 0; std::list<CoronaData*>::iterator it; for (it = Coronas.begin(); it != Coronas.end(); ++it) { if (id == i) { return (*it); } i++; } } }; class VehicleController { public: CVehicle* vehicle; std::map<int, int>cData_pattern; std::map<int, int>cData_step; std::map<int, int>cData_lastStepChange; std::map<int, int>cData_lastPatternChange; bool active = false; bool setupPattern = true; void SetupPatterns(ModelConfig* modelCfg) { if (setupPattern) { setupPattern = false; for (int corona_i = 0; corona_i < modelCfg->numberOfCoronas; corona_i++) { CoronaData* corona = modelCfg->GetCorona(corona_i); cData_pattern[corona_i] = corona->initialPattern; cData_step[corona_i] = 0; cData_lastPatternChange[corona_i] = CTimer::m_snTimeInMilliseconds; cData_lastStepChange[corona_i] = CTimer::m_snTimeInMilliseconds; } } } VehicleController(CVehicle* vehicle) { this->vehicle = vehicle; } }; // GV2 std::list<VehicleController*> vehicleControllers; std::list<Input*> coronaButtons; std::list<std::pair<unsigned short, ModelConfig*>>modelsConfig; std::list<Input*> ListInputs; std::list<Input*> ListInputs_coronaSlots; Input* nextPage; Input* prevPage; //1 Input* cfgPage_numCoronas; Input* cfgPage_removeCorona; Input* cfgPage_dir; Input* cfgPage_distCoronas; Input* cfgPage_radius; Input* cfgPage_type; Input* cfgPage_initialPattern; //2 Input* cfgPage_posX; Input* cfgPage_posY; Input* cfgPage_posZ; Input* cfgPage_nearClip; //3 Input* cfgPage_colorM_red; Input* cfgPage_colorM_green; Input* cfgPage_colorM_blue; Input* cfgPage_colorM_alpha; //4 Input* cfgPage_useSecColor; Input* cfgPage_colorSec_red; Input* cfgPage_colorSec_green; Input* cfgPage_colorSec_blue; Input* cfgPage_colorSec_alpha; //5 Input* cfgPage_useBigFlash; Input* cfgPage_bigFlashRadius; Input* cfgPage_bigFlashAlpha; Input* editField_editingInput; CoronaData* menu_editingCoronaClass; bool floatEditor_enabled = false; bool floatEditor_movingView = false; Input* floatEditor_editingInput; // Functions 2 static void SaveConfigData() { std::fstream cfgFile; char path[256]; sprintf(path, "%sNSiren.SA.data", paths::GetPluginDirPathA()); cfgFile.open(path, std::fstream::out | std::fstream::trunc); std::list< std::pair<unsigned short, ModelConfig*> >::iterator it; for (it = modelsConfig.begin(); it != modelsConfig.end(); ++it) { ModelConfig* modelCfg = (*it).second; for (int i = 0; i < modelCfg->numberOfCoronas; i++) { CoronaData* corona = modelCfg->GetCorona(i); cfgFile << modelCfg->modelIndex << ":" << i << ":" << 0 << ":" << corona->numberOfSubCoronas << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 1 << ":" << corona->direction << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 2 << ":" << corona->distanceBetweenCoronas << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 3 << ":" << corona->radius << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 4 << ":" << corona->type << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 5 << ":" << corona->x << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 6 << ":" << corona->y << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 7 << ":" << corona->z << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 8 << ":" << corona->nearClip << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 9 << ":" << (int)corona->red << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 10 << ":" << (int)corona->green << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 11 << ":" << (int)corona->blue << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 12 << ":" << (int)corona->alpha << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 13 << ":" << corona->useSecondaryColor << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 14 << ":" << (int)corona->sec_red << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 15 << ":" << (int)corona->sec_green << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 16 << ":" << (int)corona->sec_blue << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 17 << ":" << (int)corona->sec_alpha << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 18 << ":" << corona->useBigFlash << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 19 << ":" << corona->bigFlashRadius << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 20 << ":" << (int)corona->bigFlash_alpha << "\n"; cfgFile << modelCfg->modelIndex << ":" << i << ":" << 21 << ":" << corona->initialPattern << "\n"; } } cfgFile.close(); } static void SetCoronaSettings() { CoronaData* corona = menu_editingCoronaClass; cfgPage_numCoronas->SetSelection(corona->numberOfSubCoronas, 0, 5); cfgPage_dir->SetSelection(corona->direction, 0, 1); cfgPage_distCoronas->floatValue = corona->distanceBetweenCoronas; cfgPage_radius->floatValue = corona->radius; cfgPage_type->SetSelection(corona->type, 0, 1); cfgPage_initialPattern->SetSelection(corona->initialPattern, 0, 3); cfgPage_posX->floatValue = corona->x; cfgPage_posY->floatValue = corona->y; cfgPage_posZ->floatValue = corona->z; cfgPage_nearClip->floatValue = corona->nearClip; cfgPage_colorM_red->SetSelection(corona->red, 0, 255); cfgPage_colorM_green->SetSelection(corona->green, 0, 255); cfgPage_colorM_blue->SetSelection(corona->blue, 0, 255); cfgPage_colorM_alpha->SetSelection(corona->alpha, 0, 255); cfgPage_useSecColor->SetSelection(corona->useSecondaryColor, 0, 1); cfgPage_colorSec_red->SetSelection(corona->sec_red, 0, 255); cfgPage_colorSec_green->SetSelection(corona->sec_green, 0, 255); cfgPage_colorSec_blue->SetSelection(corona->sec_blue, 0, 255); cfgPage_colorSec_alpha->SetSelection(corona->sec_alpha, 0, 255); cfgPage_useBigFlash->SetSelection(corona->useBigFlash, 0, 1); cfgPage_bigFlashRadius->floatValue = corona->bigFlashRadius; cfgPage_bigFlashAlpha->SetSelection(corona->bigFlash_alpha, 0, 40); } static void ApplyCoronaSettings() { CoronaData* corona = menu_editingCoronaClass; corona->numberOfSubCoronas = cfgPage_numCoronas->selection_current; corona->direction = cfgPage_dir->selection_current; corona->distanceBetweenCoronas = cfgPage_distCoronas->floatValue; corona->radius = cfgPage_radius->floatValue; corona->type = cfgPage_type->selection_current; corona->initialPattern = cfgPage_initialPattern->selection_current; corona->x = cfgPage_posX->floatValue; corona->y = cfgPage_posY->floatValue; corona->z = cfgPage_posZ->floatValue; corona->nearClip = cfgPage_nearClip->floatValue; corona->red = cfgPage_colorM_red->selection_current; corona->green = cfgPage_colorM_green->selection_current; corona->blue = cfgPage_colorM_blue->selection_current; corona->alpha = cfgPage_colorM_alpha->selection_current; corona->useSecondaryColor = cfgPage_useSecColor->selection_current; corona->sec_red = cfgPage_colorSec_red->selection_current; corona->sec_green = cfgPage_colorSec_green->selection_current; corona->sec_blue = cfgPage_colorSec_blue->selection_current; corona->sec_alpha = cfgPage_colorSec_alpha->selection_current; corona->useBigFlash = cfgPage_useBigFlash->selection_current; corona->bigFlashRadius = cfgPage_bigFlashRadius->floatValue; corona->bigFlash_alpha = cfgPage_bigFlashAlpha->selection_current; //cfgPage_bigFlashAlpha } static void SetCoronaSlotsInputVisible(bool visible) { std::list<Input*>::iterator input_itt; for (input_itt = ListInputs_coronaSlots.begin(); input_itt != ListInputs_coronaSlots.end(); ++input_itt) { Input* input = (*input_itt); input->show = visible; } } static void DrawInputs() { std::list<Input*>::iterator input_itt; for (input_itt = ListInputs.begin(); input_itt != ListInputs.end(); ++input_itt) { Input* input = (*input_itt); if (input->show) { input->Draw(); } } } static Input* CreateInput(int type, float x, float y, float w, float h) { Input* input = new Input(type, x, y, w, h); ListInputs.push_back(input); return input; } static bool GetModelConfig(unsigned short modelIndex, ModelConfig* &modelCfg) { std::list< std::pair<unsigned short, ModelConfig*> >::iterator it; for (it = modelsConfig.begin(); it != modelsConfig.end(); ++it) { if ((*it).first == modelIndex) { modelCfg = (*it).second; return true; } } return false; } static ModelConfig* CreateModelConfig(unsigned short modelIndex) { ModelConfig* modelCfg = new ModelConfig(modelIndex); modelsConfig.push_back(std::make_pair(modelIndex, modelCfg)); return modelCfg; } static bool GetVehicleController(CVehicle* vehicle, VehicleController* &vController) { std::list<VehicleController*>::iterator it; for (it = vehicleControllers.begin(); it != vehicleControllers.end(); ++it) { if ((*it)->vehicle == vehicle) { vController = (*it); return true; } } return false; } static VehicleController* CreateVehicleController(CVehicle* vehicle) { VehicleController* vController = new VehicleController(vehicle); vehicleControllers.push_back(vController); return vController; } static void RemoveVehicleController(VehicleController* vController) { std::list<VehicleController*>::iterator it; for (it = vehicleControllers.begin(); it != vehicleControllers.end(); ++it) { if (*it == vController) { break; } } vehicleControllers.erase(it); } static void EditCorona(int coronaSlot, ModelConfig* modelCfg) { menu_onScreen = 1; menu_editingCorona = coronaSlot; SetCoronaSlotsInputVisible(false); nextPage->show = true; prevPage->show = true; menu_editingCoronaClass = modelCfg->GetCorona(coronaSlot); //all inputs SetCoronaSettings(); } static void DisableLights() { //https://gtaforums.com/topic/757430-block-siren-lights-memory-address-for-it/ //0A8C: write_memory 0x70026C size 4 value 0x90909090 virtual_protect 0 plugin::patch::SetUInt(0x70026C, 0x90909090); //0A8C : write_memory 0x700270 size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x700270, 0x90); //0A8C : write_memory 0x700271 size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x700271, 0x90); //0A8C : write_memory 0x700261 size 4 value 0x90909090 virtual_protect 0 plugin::patch::SetUInt(0x700261, 0x90909090); //0A8C : write_memory 0x700265 size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x700265, 0x90); //0A8C : write_memory 0x700266 size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x700266, 0x90); //0A8C : write_memory 0x700257 size 4 value 0x90909090 virtual_protect 0 plugin::patch::SetUInt(0x700257, 0x90909090); //0A8C : write_memory 0x70025B size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x70025B, 0x90); //0A8C : write_memory 0x70025C size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x70025C, 0x90); //-- //0@ = 0xC3F12C //CPointLight => RGB int pointLight = 0xC3F12C; //0A8C: write_memory 0@ size 4 value 0.0 virtual_protect 0 // R plugin::patch::SetUInt(pointLight, 0); //0@ += 4 pointLight += 4; //0A8C: write_memory 0@ size 4 value 0.0 virtual_protect 0 // G plugin::patch::SetUInt(pointLight, 0); //0@ += 4 pointLight += 4; //0A8C: write_memory 2@ size 4 value 0.0 virtual_protect 0 plugin::patch::SetUInt(pointLight, 0); //-- //NOPs the function that draws the coronnas //0A8C: write_memory 0x6ABA60 size 4 value 0x90909090 virtual_protect 0 plugin::patch::SetUInt(0x6ABA60, 0x90909090); //0A8C: write_memory 0x6ABA64 size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x6ABA64, 0x90); //-- //NOPs the function that checks wether the siren was activated or not //0A8C: write_memory 0x6FFDFC size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x6FFDFC, 0x90); //0A8C: write_memory 0x6FFDFD size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x6FFDFD, 0x90); //0A8C: write_memory 0x6FFDFE size 1 value 0x90 virtual_protect 0 plugin::patch::SetUChar(0x6FFDFE, 0x90); //-- //NOPs the function that activates the shadow drawing under the vehicle //0A8C: write_memory 0x70802D size 4 value 0x90909090 virtual_protect 0 //plugin::patch::SetUInt(0x70802D, 0x90909090); } static void ProccessHoldToAddInputs() { if (menu_showGUI) { std::list<Input*>::iterator input_itt; for (input_itt = ListInputs.begin(); input_itt != ListInputs.end(); ++input_itt) { Input* input = (*input_itt); if (input->show) { if (input->type == 1) { if (input->holdToAdd) { if (input->mouseOverL) { input->selection_current--; } if (input->mouseOverR) { input->selection_current++; } if (input->selection_current > input->selection_max) { input->selection_current = input->selection_max; } if (input->selection_current < input->selection_min) { input->selection_current = input->selection_min; } ApplyCoronaSettings(); } } } } } } void LoadConfigData() { char path[256]; sprintf(path, "%sNSiren.SA.data", paths::GetPluginDirPathA()); int file = CFileMgr::OpenFile(path, "r"); if (file > 0) { char buf[256]; while (CFileMgr::ReadLine(file, buf, 256)) { std::string str(reinterpret_cast<char*>(buf)); int modelid; int siren; int cmd; std::string value; int n = 0; size_t pos = 0; std::string token; while ((pos = str.find(":")) != std::string::npos) { token = str.substr(0, pos); if (n == 0) { modelid = std::stoi(token); } if (n == 1) { siren = std::stoi(token); } if (n == 2) { cmd = std::stoi(token); } str.erase(0, pos + 1); n++; } value = str; //lg << modelid << ":" << siren << ":" << cmd << ":" << value << "\n"; ModelConfig* modelCfg; if (!GetModelConfig(modelid, modelCfg)) { CreateModelConfig(modelid); GetModelConfig(modelid, modelCfg); } if (modelCfg->numberOfCoronas <= siren) { modelCfg->CreateCorona(); } CoronaData* corona = modelCfg->GetCorona(siren); if (cmd == 0) { corona->numberOfSubCoronas = std::stoi(value); } if (cmd == 1) { corona->direction = std::stoi(value); } if (cmd == 2) { corona->distanceBetweenCoronas = std::stof(value); } if (cmd == 3) { corona->radius = std::stof(value); } if (cmd == 4) { corona->type = std::stoi(value); } if (cmd == 5) { corona->x = std::stof(value); } if (cmd == 6) { corona->y = std::stof(value); } if (cmd == 7) { corona->z = std::stof(value); } if (cmd == 8) { corona->nearClip = std::stof(value); } if (cmd == 9) { corona->red = (unsigned char)std::stoi(value); } if (cmd == 10) { corona->green = (unsigned char)std::stoi(value); } if (cmd == 11) { corona->blue = (unsigned char)std::stoi(value); } if (cmd == 12) { corona->alpha = (unsigned char)std::stoi(value); } if (cmd == 13) { corona->useSecondaryColor = std::stoi(value); } if (cmd == 14) { corona->sec_red = (unsigned char)std::stoi(value); } if (cmd == 15) { corona->sec_green = (unsigned char)std::stoi(value); } if (cmd == 16) { corona->sec_blue = (unsigned char)std::stoi(value); } if (cmd == 17) { corona->sec_alpha = (unsigned char)std::stoi(value); } if (cmd == 18) { corona->useBigFlash = std::stoi(value); } if (cmd == 19) { corona->bigFlashRadius = std::stoi(value); } if (cmd == 20) { corona->bigFlash_alpha = (unsigned char)std::stoi(value); } if (cmd == 21) { corona->initialPattern = std::stoi(value); } } } } static void OnMouseDown() { if (menu_showGUI) { ModelConfig* modelCfg; if (GetModelConfig(menu_editingModelIndex, modelCfg)) { if (floatEditor_enabled) { floatEditor_enabled = false; mousePos.x = SCREEN_COORD_CENTER_X; mousePos.y = SCREEN_COORD_CENTER_Y; return; } std::list<Input*>::iterator input_itt; for (input_itt = ListInputs.begin(); input_itt != ListInputs.end(); ++input_itt) { Input* input = (*input_itt); if (input->show) { if (input->type == 2 && !floatEditor_enabled && input->mouseOver) { floatEditor_enabled = true; floatEditor_editingInput = input; } if (input->type == 1) { if (!input->holdToAdd) { if (input->mouseOverL) { input->selection_current--; } if (input->mouseOverR) { input->selection_current++; } } if (input->selection_current > input->selection_max) { input->selection_current = input->selection_max; } if (input->selection_current < input->selection_min) { input->selection_current = input->selection_min; } ApplyCoronaSettings(); std::list<VehicleController*>::iterator it; for (it = vehicleControllers.begin(); it != vehicleControllers.end(); ++it) { (*it)->setupPattern = true; } } } } if (menu_onScreen == 0) { int coronaSlot = 0; for (std::list<Input*>::iterator input_cfg_itt = ListInputs_coronaSlots.begin(); input_cfg_itt != ListInputs_coronaSlots.end(); ++input_cfg_itt) { Input* input = (*input_cfg_itt); if (input->mouseOver) { if (modelCfg->numberOfCoronas > coronaSlot) { EditCorona(coronaSlot, modelCfg); } else if (modelCfg->numberOfCoronas == coronaSlot) { modelCfg->CreateCorona(); EditCorona(coronaSlot, modelCfg); } } coronaSlot++; } } if (menu_onScreen == 1) { if (prevPage->mouseOver) { menu_subPage--; } if (nextPage->mouseOver) { menu_subPage++; } if (menu_subPage < 0) { menu_subPage = 0; } if (menu_subPage > 4) { menu_subPage = 4; } if (menu_subPage == 0) { if (cfgPage_removeCorona->mouseOver && cfgPage_removeCorona->show) { modelCfg->RemoveCorona(menu_editingCoronaClass); menu_onScreen = 0; menu_subPage = 0; SetCoronaSlotsInputVisible(true); nextPage->show = false; prevPage->show = false; } } } } } } // NSiren class NSiren { public: NSiren() { char logPath[256]; sprintf(logPath, "%sNSiren.SA.log", paths::GetPluginDirPathA()); //lg.open(logPath, std::fstream::out | std::fstream::trunc); DisableLights(); InitPatterns(); for (int i = 0; i < 8; i++) { ListInputs_coronaSlots.push_back(CreateInput(0, i < 4 ? 35.0f : 225.0f, 240.0f + (i % 4) * 30, 180.0f, 20.0f)); } prevPage = CreateInput(0, 25.0f, 395.0f, 120.0f, 20.0f); prevPage->SetText("Pagina anterior"); nextPage = CreateInput(0, 195.0f, 395.0f, 120.0f, 20.0f); nextPage->SetText("Proxima pagina"); //1 cfgPage_numCoronas = CreateInput(1, 150.0f, 235.0f, 80.0f, 20.0f); cfgPage_numCoronas->bgColor = CRGBA(158, 158, 158, 255); cfgPage_numCoronas->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_numCoronas->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_removeCorona = CreateInput(0, 300.0f, 235.0f, 100.0f, 20.0f); cfgPage_removeCorona->SetText("Deletar corona"); cfgPage_dir = CreateInput(1, 150.0f, 260.0f, 120.0f, 20.0f); cfgPage_dir->bgColor = CRGBA(158, 158, 158, 255); cfgPage_dir->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_dir->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_radius = CreateInput(2, 150.0f, 285.0f, 120.0f, 20.0f); cfgPage_radius->SetFloatEditorSettings("Tamanho", 0.0f, 1.0f); cfgPage_type = CreateInput(1, 150.0f, 310.0f, 120.0f, 20.0f); cfgPage_type->bgColor = CRGBA(158, 158, 158, 255); cfgPage_type->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_type->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_initialPattern = CreateInput(1, 150.0f, 335.0f, 120.0f, 20.0f); cfgPage_initialPattern->bgColor = CRGBA(158, 158, 158, 255); cfgPage_initialPattern->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_initialPattern->bgColorDisabled = CRGBA(40, 40, 40, 255); //2 cfgPage_posX = CreateInput(2, 150.0f, 235.0f, 120.0f, 20.0f); cfgPage_posX->SetFloatEditorSettings("Posicao X (Lados)", -3.0f, 3.0f); cfgPage_distCoronas = CreateInput(2, 150.0f, 260.0f, 120.0f, 20.0f); cfgPage_distCoronas->SetFloatEditorSettings("Distancia entre coronas", 0.0f, 3.0f); cfgPage_posY = CreateInput(2, 150.0f, 285.0f, 120.0f, 20.0f); cfgPage_posY->SetFloatEditorSettings("Posicao Y (Frente/Tras)", -8.0f, 8.0f); cfgPage_posZ = CreateInput(2, 150.0f, 310.0f, 120.0f, 20.0f); cfgPage_posZ->SetFloatEditorSettings("Posicao Z (Altura)", -5.0f, 5.0f); cfgPage_nearClip = CreateInput(2, 150.0f, 335.0f, 120.0f, 20.0f); cfgPage_nearClip->SetFloatEditorSettings("Near Clip", 0.1f, 2.0f); //3 cfgPage_colorM_red = CreateInput(1, 150.0f, 260.0f, 120.0f, 20.0f); cfgPage_colorM_red->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorM_red->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorM_red->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorM_red->SetAsHoldToAdd(); cfgPage_colorM_green = CreateInput(1, 150.0f, 285.0f, 120.0f, 20.0f); cfgPage_colorM_green->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorM_green->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorM_green->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorM_green->SetAsHoldToAdd(); cfgPage_colorM_blue = CreateInput(1, 150.0f, 310.0f, 120.0f, 20.0f); cfgPage_colorM_blue->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorM_blue->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorM_blue->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorM_blue->SetAsHoldToAdd(); cfgPage_colorM_alpha = CreateInput(1, 150.0f, 335.0f, 120.0f, 20.0f); cfgPage_colorM_alpha->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorM_alpha->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorM_alpha->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorM_alpha->SetAsHoldToAdd(); //4 cfgPage_useSecColor = CreateInput(1, 150.0f, 235.0f, 150.0f, 20.0f); cfgPage_useSecColor->bgColor = CRGBA(158, 158, 158, 255); cfgPage_useSecColor->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_useSecColor->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorSec_red = CreateInput(1, 150.0f, 260.0f, 120.0f, 20.0f); cfgPage_colorSec_red->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorSec_red->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorSec_red->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorSec_red->SetAsHoldToAdd(); cfgPage_colorSec_green = CreateInput(1, 150.0f, 285.0f, 120.0f, 20.0f); cfgPage_colorSec_green->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorSec_green->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorSec_green->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorSec_green->SetAsHoldToAdd(); cfgPage_colorSec_blue = CreateInput(1, 150.0f, 310.0f, 120.0f, 20.0f); cfgPage_colorSec_blue->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorSec_blue->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorSec_blue->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorSec_blue->SetAsHoldToAdd(); cfgPage_colorSec_alpha = CreateInput(1, 150.0f, 335.0f, 120.0f, 20.0f); cfgPage_colorSec_alpha->bgColor = CRGBA(158, 158, 158, 255); cfgPage_colorSec_alpha->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_colorSec_alpha->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_colorSec_alpha->SetAsHoldToAdd(); //5 cfgPage_useBigFlash = CreateInput(1, 150.0f, 235.0f, 150.0f, 20.0f); cfgPage_useBigFlash->bgColor = CRGBA(158, 158, 158, 255); cfgPage_useBigFlash->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_useBigFlash->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_bigFlashRadius = CreateInput(2, 150.0f, 260.0f, 120.0f, 20.0f); cfgPage_bigFlashRadius->SetFloatEditorSettings("Tamanho", 0.5f, 8.0f); cfgPage_bigFlashAlpha = CreateInput(1, 150.0f, 285.0f, 120.0f, 20.0f); cfgPage_bigFlashAlpha->bgColor = CRGBA(158, 158, 158, 255); cfgPage_bigFlashAlpha->bgColorHover = CRGBA(120, 120, 120, 255); cfgPage_bigFlashAlpha->bgColorDisabled = CRGBA(40, 40, 40, 255); cfgPage_bigFlashAlpha->SetAsHoldToAdd(); static int key_lastToggleMenu = 0; Events::initRwEvent += [] { int txd = CTxdStore::AddTxdSlot("mytxd"); CTxdStore::LoadTxd(txd, "MODELS\\FRONTEN_PC.TXD"); TxdDef* txdDef = CTxdStore::AddRef(txd); CTxdStore::PushCurrentTxd(); CTxdStore::SetCurrentTxd(txd); mouseSprite.SetTexture("mouse", "mouseA"); CTxdStore::PopCurrentTxd(); }; Events::initGameEvent += [] { ///lg << "Reading config\n"; LoadConfigData(); //lg << "Config OK\n"; }; Events::processScriptsEvent.before += [] { CPed* playa = FindPlayerPed(); if (menu_showGUI) { if (KeyPressed(32)) { if (!floatEditor_movingView) { floatEditor_movingView = true; Command<0x01B4, int, bool>(0, true); } } else { if (floatEditor_movingView) { floatEditor_movingView = false; Command<0x01B4, int, bool>(0, false); mousePos.x = SCREEN_COORD_CENTER_X; mousePos.y = SCREEN_COORD_CENTER_Y; } } } if (!floatEditor_movingView) { if (KeyPressed(1)) { ProccessHoldToAddInputs(); if (!bMouseDown) { bMouseDown = true; OnMouseDown(); } } else { if (bMouseDown) { bMouseDown = false; } } } if (KeyPressed(90) && KeyPressed(17) && CTimer::m_snTimeInMilliseconds - key_lastToggleMenu > 500) { key_lastToggleMenu = CTimer::m_snTimeInMilliseconds; CVehicle* vehicle = FindPlayerVehicle(0, false); if (vehicle > 0) { if (!menu_showGUI) { ModelConfig* modelCfg; unsigned short modelIndex = vehicle->m_nModelIndex; if (!GetModelConfig(modelIndex, modelCfg)) { CreateModelConfig(modelIndex); } //ok menu_showGUI = true; Command<0x01B4, int, bool>(0, false); menu_onScreen = 0; menu_subPage = 0; menu_editingModelIndex = modelIndex; SetCoronaSlotsInputVisible(true); nextPage->show = false; prevPage->show = false; } else { if (!floatEditor_enabled) { menu_showGUI = false; Command<0x01B4, int, bool>(0, true); SaveConfigData(); } } } else { CMessages::AddMessageJumpQ("Voce precisa estar em um veiculo!", 1000, 0, false); } } if (menu_showGUI) { POINT position; if (GetCursorPos(&position)) { if (floatEditor_enabled) { if (!floatEditor_movingView) { floatEditor_editingInput->floatValue -= (SCREEN_COORD_CENTER_X - position.x) / 500; floatEditor_editingInput->floatValue = clampf(floatEditor_editingInput->floatValue, floatEditor_editingInput->floatMin, floatEditor_editingInput->floatMax); ApplyCoronaSettings(); } } mousePos.x -= SCREEN_COORD_CENTER_X - position.x; mousePos.y -= SCREEN_COORD_CENTER_Y - position.y; mousePos.x = clampf(mousePos.x, 0, SCREEN_COORD_CENTER_X * 2); mousePos.y = clampf(mousePos.y, 0, SCREEN_COORD_CENTER_Y * 2); } } for (CVehicle* vehicle : CPools::ms_pVehiclePool) { VehicleController* vController; if (!GetVehicleController(vehicle, vController)) { vController = CreateVehicleController(vehicle); //lg << reinterpret_cast<int>(vController->vehicle) << " created\n"; } else { vController->active = vehicle->m_nVehicleFlags.bSirenOrAlarm; } } for (VehicleController* vController : vehicleControllers) { bool found = false; for (CVehicle* v : CPools::ms_pVehiclePool) { if (v == vController->vehicle) { found = true; break; } } if (!found) { //lg << reinterpret_cast<int>(vController->vehicle) << " not fonud. Removed\n"; RemoveVehicleController(vController); } } }; Events::vehicleRenderEvent.before += [](CVehicle* vehicle) { VehicleController* vController; if (GetVehicleController(vehicle, vController)) { ModelConfig* modelCfg; if (GetModelConfig(vehicle->m_nModelIndex, modelCfg)) { if (modelCfg->numberOfCoronas == 0) { return; } vController->SetupPatterns(modelCfg); unsigned int light_id = reinterpret_cast<unsigned int>(vehicle); for (int corona_i = 0; corona_i < modelCfg->numberOfCoronas; corona_i++) { bool left, middle, right; int delay = 100; GetPatternStep(vController->cData_pattern[corona_i], vController->cData_step[corona_i], left, middle, right, delay); if (CTimer::m_snTimeInMilliseconds - vController->cData_lastStepChange[corona_i] >= delay) { vController->cData_lastStepChange[corona_i] = CTimer::m_snTimeInMilliseconds; vController->cData_step[corona_i]++; if (vController->cData_step[corona_i] >= GetNumberOfSteps(vController->cData_pattern[corona_i])) { vController->cData_step[corona_i] = 0; if (CTimer::m_snTimeInMilliseconds - vController->cData_lastPatternChange[corona_i] > 8000) { vController->cData_lastPatternChange[corona_i] = CTimer::m_snTimeInMilliseconds; vController->cData_pattern[corona_i]++; if (vController->cData_pattern[corona_i] >= ListPatterns.size()) { vController->cData_pattern[corona_i] = 0; } } } } CoronaData* corona = modelCfg->GetCorona(corona_i); for (int subCorona_i = 0; subCorona_i < corona->numberOfSubCoronas; subCorona_i++) { float radius = corona->radius; float posx = corona->x - (corona->numberOfSubCoronas - 1) * corona->distanceBetweenCoronas / 2 + (subCorona_i)*corona->distanceBetweenCoronas; CVector offset = CVector(posx, corona->y, corona->z); bool isLeftSide = (subCorona_i < floor(corona->numberOfSubCoronas / 2)); bool isMiddle = corona->numberOfSubCoronas == 1; bool isRightSide = (subCorona_i >= floor(corona->numberOfSubCoronas / 2) + (corona->numberOfSubCoronas % 2 == 0 ? 0 : 1)); bool showCorona = false; bool registerCorona = true; if (left == 1 && isLeftSide) { showCorona = true; } if (right == 1 && isRightSide) { showCorona = true; } if (middle == 1 && isMiddle) { showCorona = true; } if (!vController->active) { showCorona = false; } if (menu_showGUI) { showCorona = true; registerCorona = true; } float bigFlashRadius = corona->bigFlashRadius; //dir CVector pos = CModelInfo::ms_modelInfoPtrs[vehicle->m_nModelIndex]->m_pColModel->m_boundBox.m_vecMin; CVector vehiclePos = vehicle->TransformFromObjectSpace(CVector(0.0f, 0.0f, 0.0f)); CVector coronaPos = vehicle->TransformFromObjectSpace(offset); float dir = (float)GetAngleBetweenVectors(vehiclePos, coronaPos, TheCamera.GetPosition()); if (isnan(dir)) { dir = 0.01f; } const float start_fadeout = 1.00; const float end_fadeout = 1.60; if ((corona->y >= 0.1f || corona->y <= -0.1f) && corona->direction != 1) { if (dir >= start_fadeout && dir <= end_fadeout) { float r = (dir - start_fadeout) / (end_fadeout - start_fadeout); radius *= (1.0f - r); bigFlashRadius *= (1.0f - r); } if (dir >= end_fadeout && corona->direction == 1) { registerCorona = false; } if (corona->direction == 0 && dir >= end_fadeout) { registerCorona = false; } } //-- if (!showCorona) { radius = 0.0f; bigFlashRadius = 0.0f; } eCoronaType type = (corona->type == 0 ? eCoronaType::CORONATYPE_SHINYSTAR : eCoronaType::CORONATYPE_HEADLIGHTLINE); bool useSecundaryColor = (corona->useSecondaryColor && isRightSide); if (registerCorona) { CCoronas::RegisterCorona(light_id, vehicle, (useSecundaryColor ? corona->sec_red : corona->red), (useSecundaryColor ? corona->sec_green : corona->green), (useSecundaryColor ? corona->sec_blue : corona->blue), (useSecundaryColor ? corona->sec_alpha : corona->alpha), offset, radius, corona->farClip, type, corona->flareType, false, false, 0, 0.0f, false, corona->nearClip, 0, 15.0f, false, false); } light_id++; if (corona->useBigFlash && registerCorona) { CCoronas::RegisterCorona(light_id, vehicle, (useSecundaryColor ? corona->sec_red : corona->red), (useSecundaryColor ? corona->sec_green : corona->green), (useSecundaryColor ? corona->sec_blue : corona->blue), corona->bigFlash_alpha, offset, bigFlashRadius, corona->farClip, type, eCoronaFlareType::FLARETYPE_NONE, false, false, 0, 0.0f, false, 1.5f, 0, 15.0f, false, false); } light_id++; } } } } }; Events::drawHudEvent.before += [] { if (menu_showGUI) { ModelConfig* modelCfg; if (GetModelConfig(menu_editingModelIndex, modelCfg)) { CFont::SetOrientation(ALIGN_LEFT); CFont::SetDropShadowPosition(1); CFont::SetBackground(false, false); CFont::SetScale(ScreenPosX(0.3), ScreenPosY(0.9)); CFont::SetFontStyle(FONT_SUBTITLES); CFont::SetProportional(true); CFont::SetColor(CRGBA(255, 255, 255, 255)); if (floatEditor_enabled) { CSprite2d::DrawRect(CRect(ScreenPosX(0.0f), ScreenPosY(0.0f), ScreenPosX(800.0f), ScreenPosY(600.0f)), CRGBA(0, 0, 0, 60)); if (!floatEditor_movingView) { CSprite2d::DrawRect(CRect(ScreenPosX(10.0f), ScreenPosY(230.0f), ScreenPosX(260.0f), ScreenPosY(340.0f)), CRGBA(0, 0, 0, 140)); //floatEditor_editingInput->floatValue char text[256]; CFont::SetOrientation(ALIGN_CENTER); CFont::PrintString(ScreenPosX(135.0f), ScreenPosY(245), floatEditor_editingInput->floatTitle); CFont::SetScale(ScreenPosX(0.6), ScreenPosY(1.2)); sprintf(text, "%.2f", floatEditor_editingInput->floatValue); CFont::PrintString(ScreenPosX(135.0f), ScreenPosY(265.0f), text); CFont::SetColor(CRGBA(255, 160, 0, 255)); CFont::SetScale(ScreenPosX(0.4), ScreenPosY(0.85)); CFont::PrintString(ScreenPosX(135.0f), ScreenPosY(290.0f), "ESPACO: Move a camera livremente"); CFont::PrintString(ScreenPosX(135.0f), ScreenPosY(305.0f), "MOUSE1: Finaliza edicao"); } return; } if (floatEditor_movingView) { return; } CSprite2d::DrawRect(CRect(ScreenPosX(20.0f), ScreenPosY(200.0f), ScreenPosX(20.0f + 400.0f), ScreenPosY(200.0f + 220.0f)), CRGBA(0, 0, 0, 255)); CSprite2d::DrawRect(CRect(ScreenPosX(20.0f), ScreenPosY(200.0f), ScreenPosX(20.0f + 400.0f), ScreenPosY(200.0f + 30.0f)), CRGBA(22, 22, 22, 255)); char text[256]; if (menu_onScreen == 1) { sprintf(text, "NSiren - Editando [%i]", menu_editingCorona); sprintf(text, "NSiren - Editando [%i]", menu_editingCorona); } else { sprintf(text, "NSiren - (%i)", modelCfg->modelIndex); CFont::PrintString(ScreenPosX(23.0f), ScreenPosY(400.0f), "Feito por DaniloM1301"); } CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(206.0f), text); cfgPage_numCoronas->show = false; cfgPage_removeCorona->show = false; cfgPage_dir->show = false; cfgPage_radius->show = false; cfgPage_type->show = false; cfgPage_initialPattern->show = false; cfgPage_posX->show = false; cfgPage_distCoronas->show = false; cfgPage_posY->show = false; cfgPage_posZ->show = false; cfgPage_nearClip->show = false; cfgPage_colorM_red->show = false; cfgPage_colorM_green->show = false; cfgPage_colorM_blue->show = false; cfgPage_colorM_alpha->show = false; cfgPage_useSecColor->show = false; cfgPage_colorSec_red->show = false; cfgPage_colorSec_green->show = false; cfgPage_colorSec_blue->show = false; cfgPage_colorSec_alpha->show = false; cfgPage_bigFlashRadius->show = false; cfgPage_useBigFlash->show = false; cfgPage_bigFlashAlpha->show = false; if (menu_onScreen == 1) { //170 //395 CFont::SetOrientation(ALIGN_CENTER); sprintf(text, "%i / %i", menu_subPage + 1, 5); CFont::PrintString(ScreenPosX(170.0f), ScreenPosY(396.0f), text); CFont::SetOrientation(ALIGN_LEFT); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(360.0f), " ( Segure ESPACO para mover a camera )"); if (menu_subPage == 0) { //+25 CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(235.0f), "Numero de coronas"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(260.0f), "Direcao"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(285.0f), "Tamanho"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(310.0f), "Tipo"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(335.0f), "Padrao das luzes"); cfgPage_numCoronas->show = true; sprintf(cfgPage_numCoronas->stringText, "%i", cfgPage_numCoronas->selection_current); cfgPage_removeCorona->show = true; cfgPage_dir->show = true; sprintf(cfgPage_dir->stringText, "%s", (cfgPage_dir->selection_current == 0 ? ("Frente ou tras") : ("Todas as direcoes"))); cfgPage_radius->show = true; cfgPage_type->show = true; sprintf(cfgPage_type->stringText, "%s", (cfgPage_type->selection_current == 0 ? ("Tipo 1") : ("Tipo 2"))); cfgPage_initialPattern->show = true; sprintf(cfgPage_initialPattern->stringText, "Padrao %i", cfgPage_initialPattern->selection_current + 1); } if (menu_subPage == 1) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(235.0f), "Posicao X (Lados)"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(260.0f), "Distancia entre coronas"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(285.0f), "Posicao Y (Frente/Tras)"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(310.0f), "Posicao Z (Altura)"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(335.0f), "Near Clip *"); cfgPage_posX->show = true; cfgPage_distCoronas->show = true; cfgPage_posY->show = true; cfgPage_posZ->show = true; cfgPage_nearClip->show = true; } if (menu_subPage == 2) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(235.0f), "[ Cor ]"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(260.0f), "R - Vermelho"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(285.0f), "G - Verde"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(310.0f), "B - Azul"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(335.0f), "A - Transparencia"); cfgPage_colorM_red->show = true; sprintf(cfgPage_colorM_red->stringText, "%i", cfgPage_colorM_red->selection_current); cfgPage_colorM_green->show = true; sprintf(cfgPage_colorM_green->stringText, "%i", cfgPage_colorM_green->selection_current); cfgPage_colorM_blue->show = true; sprintf(cfgPage_colorM_blue->stringText, "%i", cfgPage_colorM_blue->selection_current); cfgPage_colorM_alpha->show = true; sprintf(cfgPage_colorM_alpha->stringText, "%i", cfgPage_colorM_alpha->selection_current); CSprite2d::DrawRect(CRect(ScreenPosX(354.0), ScreenPosY(286.0), ScreenPosX(403.0f), ScreenPosY(335.0f)), CRGBA(255, 255, 255, 255)); CSprite2d::DrawRect(CRect(ScreenPosX(356.0), ScreenPosY(288.0), ScreenPosX(401.0f), ScreenPosY(333.0f)), CRGBA(cfgPage_colorM_red->selection_current, cfgPage_colorM_green->selection_current, cfgPage_colorM_blue->selection_current, cfgPage_colorM_alpha->selection_current)); } if (menu_subPage == 3) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(235.0f), "[ Cor Secundaria ]"); cfgPage_useSecColor->show = true; sprintf(cfgPage_useSecColor->stringText, "%s", cfgPage_useSecColor->selection_current == 1 ? "Usar cor secundaria" : "Nao usar cor secundaria"); if (cfgPage_useSecColor->selection_current == 1) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(260.0f), "R - Vermelho"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(285.0f), "G - Verde"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(310.0f), "B - Azul"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(335.0f), "A - Transparencia"); cfgPage_colorSec_red->show = true; sprintf(cfgPage_colorSec_red->stringText, "%i", cfgPage_colorSec_red->selection_current); cfgPage_colorSec_green->show = true; sprintf(cfgPage_colorSec_green->stringText, "%i", cfgPage_colorSec_green->selection_current); cfgPage_colorSec_blue->show = true; sprintf(cfgPage_colorSec_blue->stringText, "%i", cfgPage_colorSec_blue->selection_current); cfgPage_colorSec_alpha->show = true; sprintf(cfgPage_colorSec_alpha->stringText, "%i", cfgPage_colorSec_alpha->selection_current); CSprite2d::DrawRect(CRect(ScreenPosX(354.0), ScreenPosY(286.0), ScreenPosX(403.0f), ScreenPosY(335.0f)), CRGBA(255, 255, 255, 255)); CSprite2d::DrawRect(CRect(ScreenPosX(356.0), ScreenPosY(288.0), ScreenPosX(401.0f), ScreenPosY(333.0f)), CRGBA(cfgPage_colorSec_red->selection_current, cfgPage_colorSec_green->selection_current, cfgPage_colorSec_blue->selection_current, cfgPage_colorSec_alpha->selection_current)); } } if (menu_subPage == 4) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(235.0f), "Usar flash maior"); cfgPage_useBigFlash->show = true; sprintf(cfgPage_useBigFlash->stringText, "%s", cfgPage_useBigFlash->selection_current == 1 ? "Ativado" : "Desativado"); if (cfgPage_useBigFlash->selection_current == 1) { CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(260.0f), "Tamanho"); CFont::PrintString(ScreenPosX(25.0f), ScreenPosY(285.0f), "Intensidade"); cfgPage_bigFlashRadius->show = true; cfgPage_bigFlashAlpha->show = true; sprintf(cfgPage_bigFlashAlpha->stringText, "%i", cfgPage_bigFlashAlpha->selection_current); } } } if (menu_onScreen == 0) { std::list<Input*>::iterator input_itt; int input_i = 0; for (input_itt = ListInputs_coronaSlots.begin(); input_itt != ListInputs_coronaSlots.end(); ++input_itt) { Input* input = (*input_itt); CoronaData* corona = modelCfg->GetCorona(input_i); input->useIcon = false; if (input_i < modelCfg->numberOfCoronas) { char inputText[256]; sprintf(inputText, "Editar [%i]", input_i); input->SetBackgroundColor(CRGBA(122, 122, 122, 255)); input->SetBackgroundColorHover(CRGBA(73, 73, 73, 255)); input->SetText(inputText); input->SetCoronaIcon(CRGBA(corona->red, corona->green, corona->blue, corona->alpha), corona->useSecondaryColor, CRGBA(corona->sec_red, corona->sec_green, corona->sec_blue, corona->sec_alpha)); } else if (input_i == modelCfg->numberOfCoronas) { input->SetBackgroundColor(CRGBA(226, 226, 226, 255)); input->SetBackgroundColorHover(CRGBA(153, 153, 153, 255)); input->SetText("Criar corona"); } else { input->SetBackgroundColor(CRGBA(30, 30, 30, 255)); input->SetBackgroundColorHover(CRGBA(30, 30, 30, 255)); input->SetText("Slot vazio"); } input_i++; } } DrawInputs(); } } }; Events::drawHudEvent.after += [] { if (menu_showGUI && !floatEditor_enabled && !floatEditor_movingView) { mouseSprite.Draw(mousePos.x, mousePos.y, 30.0f, 30.0f, CRGBA(255, 255, 255, 255)); } }; } } nSiren;
d3b5ba93180a7d4fe23a811dfb9342a96690cff2
[ "C++" ]
1
C++
Danilo1301/NSiren
22c794da808a5fa30d0cc32514ba9757e5bc534c
b7ac8902abdfc9be1eea1de907e4fb93cdfd7699
refs/heads/main
<repo_name>magzumAlmat/ReactI18SPA<file_sep>/simple-react-responsive-navbar/src/components/about.jsx import React from "react"; class about extends React.Component { render() { const { match, t, i18n } = this.props; return ( <div> <h2>Topics</h2> </div> ); } } export default about;<file_sep>/simple-react-responsive-navbar/build/precache-manifest.82796ab3c56c7efb46fe87fe9fd959d6.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "65405c059ade63e068e3345fd12b035b", "url": "/index.html" }, { "revision": "58317aac24f315e64bfa", "url": "/static/css/main.5653514d.chunk.css" }, { "revision": "e7e9cf8a3d961ee5c2d9", "url": "/static/js/2.b6d907e1.chunk.js" }, { "revision": "58317aac24f315e64bfa", "url": "/static/js/main.cf5c3e04.chunk.js" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" }, { "revision": "2f80b29375c2390dd2f5766dd177a177", "url": "/static/media/001.2f80b293.jpg" }, { "revision": "f41d926c92c7ed0e541b3b5678b47737", "url": "/static/media/002.f41d926c.jpg" }, { "revision": "777ea43f5271e900de8d4f2a3048fd20", "url": "/static/media/003.777ea43f.jpg" }, { "revision": "3611f4a4a64d431d73e73cd6e12f8f43", "url": "/static/media/004.3611f4a4.jpg" }, { "revision": "03df42c15d6e9a9b1bb7a87c28e9c1e2", "url": "/static/media/005.03df42c1.jpg" }, { "revision": "edceca3e349303dc5ac7820eb69dd0e4", "url": "/static/media/006.edceca3e.jpg" }, { "revision": "679d5d28d0139b4388393b532f4a0f98", "url": "/static/media/1.679d5d28.png" }, { "revision": "01a079bff222b8554f2971a0f82f5a2d", "url": "/static/media/10.01a079bf.png" }, { "revision": "e31e86b8de8a236abce0b9a8fb0fd84e", "url": "/static/media/2.e31e86b8.png" }, { "revision": "2707b07e8a5d8cb62d2d140f1eaa6737", "url": "/static/media/3.2707b07e.png" }, { "revision": "c70965b348537f0717143e7087736759", "url": "/static/media/4.c70965b3.png" }, { "revision": "d8f4e8400cdb85e51a09da5d09aa3b57", "url": "/static/media/5.d8f4e840.png" }, { "revision": "acdae15<KEY>", "url": "/static/media/6.acdae156.png" }, { "revision": "457f139a04e765aaaac990b2f7adbec8", "url": "/static/media/7.457f139a.png" }, { "revision": "c37f78759a48c5fe4232b6e9cac1b60c", "url": "/static/media/8.c37f7875.png" }, { "revision": "ab4747e95713ba7d3695caf53a0affcf", "url": "/static/media/9.ab4747e9.png" }, { "revision": "9c791b6b0e084c387555f36ae172147b", "url": "/static/media/burger.9c791b6b.png" }, { "revision": "0beff8fdd763fc620530e8a011514b5f", "url": "/static/media/certsn.0beff8fd.jpg" }, { "revision": "1f7a6a7867914f27f9c5621982720733", "url": "/static/media/logo.1f7a6a78.png" } ]);<file_sep>/simple-react-responsive-navbar/src/components/corusel.js import "./slick.css"; import "./slick-theme.css"; import React from "react"; import Slider from "react-slick"; import img1 from './002.jpg'; import img2 from './001.jpg'; import img3 from './003.jpg'; import img4 from './004.jpg'; import img5 from './005.jpg'; import img6 from './006.jpg'; import './im.css'; class SimpleSlider extends React.Component { render() { var settings = { dots: true, infinite: true, speed: 20, slidesToShow: 1, slidesToScroll: 1 }; return ( <Slider {...settings} > <div > <img src={img1} className='imageResize'/> </div> <div> <img src={img2}className='imageResize' /> </div> <div> <img src={img3} className='imageResize'/> </div> <div> <img src={img4} className='imageResize'/> </div> <div> <img src={img5} className='imageResize'/> </div> <div> <img src={img6} className='imageResize'/> </div> </Slider> ); } } export default SimpleSlider
1ff4dd8e9bb22ad463bfb32137da936dcc932190
[ "JavaScript" ]
3
JavaScript
magzumAlmat/ReactI18SPA
574666d089edea5ed8eaa471fff5f5e1f92a2709
cd5033f807998197661a48f1fa88dbf8246dd346
refs/heads/master
<repo_name>niblazevic/AutoSkola<file_sep>/app/src/main/java/com/example/autoskola_v1/PitanjaIOdgovori.java package com.example.autoskola_v1; public class PitanjaIOdgovori { private String Pitanje; private String Odgovor1; private String Odgovor2; private String Odgovor3; private long TocanOdgovor; private String Slika; private String OznakaOdgovor1; private String OznakaOdgovor2; private String OznakaOdgovor3; private int BrojBodova; private int RedniBroj; public PitanjaIOdgovori(){} public PitanjaIOdgovori(String pitanje, String odgovor1, String odgovor2, String odgovor3, long tocanOdgovor, String slika, String oznakaOdgovor1, String oznakaOdgovor2, String oznakaOdgovor3, int brojBodova, int redniBroj) { Pitanje = pitanje; Odgovor1 = odgovor1; Odgovor2 = odgovor2; Odgovor3 = odgovor3; TocanOdgovor = tocanOdgovor; Slika = slika; OznakaOdgovor1 = oznakaOdgovor1; OznakaOdgovor2 = oznakaOdgovor2; OznakaOdgovor3 = oznakaOdgovor3; BrojBodova = brojBodova; RedniBroj = redniBroj; } public int getRedniBroj() { return RedniBroj; } public void setRedniBroj(int redniBroj) { RedniBroj = redniBroj; } public String getPitanje() { return Pitanje; } public void setPitanje(String pitanje) { Pitanje = pitanje; } public String getOdgovor1() { return Odgovor1; } public void setOdgovor1(String odgovor1) { Odgovor1 = odgovor1; } public String getOdgovor2() { return Odgovor2; } public void setOdgovor2(String odgovor2) { Odgovor2 = odgovor2; } public String getOdgovor3() { return Odgovor3; } public void setOdgovor3(String odgovor3) { Odgovor3 = odgovor3; } public long getTocanOdgovor() { return TocanOdgovor; } public void setTocanOdgovor(long tocanOdgovor) { TocanOdgovor = tocanOdgovor; } public String getSlika() { return Slika; } public void setSlika(String slika) { Slika = slika; } public String getOznakaOdgovor1() { return OznakaOdgovor1; } public void setOznakaOdgovor1(String oznakaOdgovor1) { OznakaOdgovor1 = oznakaOdgovor1; } public String getOznakaOdgovor2() { return OznakaOdgovor2; } public void setOznakaOdgovor2(String oznakaOdgovor2) { OznakaOdgovor2 = oznakaOdgovor2; } public String getOznakaOdgovor3() { return OznakaOdgovor3; } public void setOznakaOdgovor3(String oznakaOdgovor3) { OznakaOdgovor3 = oznakaOdgovor3; } public int getBrojBodova() { return BrojBodova; } public void setBrojBodova(int brojBodova) { BrojBodova = brojBodova; } } <file_sep>/app/src/main/java/com/example/autoskola_v1/VjezbePitanja.java package com.example.autoskola_v1; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.ActivityOptions; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.util.Pair; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.DecelerateInterpolator; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; public class VjezbePitanja extends AppCompatActivity { LinearLayout linearLayout4; TextView txtBrojPitanja, txtTekstPitanja, txtBrojac, txtInfo; ImageView imgInfo, imgPitanja; Button btnOdgovor1, btnOdgovor2, btnOdgovor3, btnOdgovori; List<Pitanje> ListaPitanja; CountDownTimer countDownTimer; int redniBrojPitanja, rezultatExtra; int velinicnaSeta; int odgovor = 0; int provjeraTimera = 0; String OznakaOdgovor1 = "0", OznakaOdgovor2 = "0", OznakaOdgovor3 = "0"; String userID; FirebaseAuth fAuth; FirebaseFirestore fStore; Ucitavanje ucitavanje = new Ucitavanje(VjezbePitanja.this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_vjezbe_pitanja); ucitavanje.pokreniUcitavanje(); fStore = FirebaseFirestore.getInstance(); fAuth = FirebaseAuth.getInstance(); txtBrojPitanja = findViewById(R.id.txtBrojPitanja); txtTekstPitanja = findViewById(R.id.txtTekstPitanja); txtInfo = findViewById(R.id.txtInfo); txtBrojac = findViewById(R.id.txtBrojac); imgInfo = findViewById(R.id.imgInfo); imgPitanja = findViewById(R.id.imgPitanja); btnOdgovor1 = findViewById(R.id.btnOdgovor1); btnOdgovor2 = findViewById(R.id.btnOdgovor2); btnOdgovor3 = findViewById(R.id.btnOdgovor3); btnOdgovori = findViewById(R.id.btnOdgovori); linearLayout4 = findViewById(R.id.linearLayout4); linearLayout4.setTransitionName(getIntent().getStringExtra("LOGO")); txtInfo.setText(getIntent().getStringExtra("KATEGORIJA")); if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Opća pitanja")){ imgInfo.setImageResource(R.drawable.opca_pitanja_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Prometni znakovi")){ imgInfo.setImageResource(R.drawable.prometni_znakovi_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Propuštanje vozila i prednost prolaska")){ imgInfo.setImageResource(R.drawable.propustanje_vozila_itd_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Opasne situacije")){ imgInfo.setImageResource(R.drawable.opasne_situacije_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "1 - 22")){ imgInfo.setImageResource(R.drawable.first_aid_kit_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "23 - 44")){ imgInfo.setImageResource(R.drawable.bandage_icon); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "45 - 66")){ imgInfo.setImageResource(R.drawable.revive_icon); } btnOdgovor1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { oznacavanjeOdgovora("1", v); } }); btnOdgovor2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { oznacavanjeOdgovora("2", v); } }); btnOdgovor3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { oznacavanjeOdgovora("3", v); } }); btnOdgovori.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { countDownTimer.cancel(); if(odgovor == 0){ btnOdgovori.setText("Sljedeće Pitanje"); provjeraOdogovora(OznakaOdgovor1, OznakaOdgovor2, OznakaOdgovor3); odgovor = 1; }else{ btnOdgovori.setText("Odgovori"); oznacavanjeOdgovora("0", v); promjeniPitanje(); odgovor = 0; } } }); getListaPitanja(); rezultatExtra = 0; } private void getListaPitanja(){ ListaPitanja = new ArrayList<>(); if(String.valueOf(getIntent().getStringExtra("IDDETALJNO")).equals("0")){ DocumentReference documentReference = fStore.collection("Pitanja") .document(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))) .collection("BrojPitanja") .document(String.valueOf(getIntent().getStringExtra("IDSETA"))); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ velinicnaSeta = Objects.requireNonNull(Objects.requireNonNull(task.getResult()).getLong("BrojPitanja")).intValue(); if(velinicnaSeta < 20){ txtBrojPitanja.setText("Pitanje 1/" + velinicnaSeta); if(velinicnaSeta == 0){ countDownTimer.cancel(); Intent intent = new Intent(VjezbePitanja.this, VjezbeRezultati.class); intent.putExtra("REZULTAT", "Baza podataka je prazna!"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left); }else { for (int i = 1; i <= velinicnaSeta; i++) { DocumentReference documentReference1 = fStore.collection("Pitanja") .document(String.valueOf(getIntent() .getStringExtra("IDKATEGORIJE"))) .collection(String.valueOf(getIntent().getStringExtra("IDSETA"))) .document("Pitanje" + i); documentReference1.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); assert snapshot != null; Pitanje pitanje = new Pitanje(snapshot.getString("Pitanje"), snapshot.getString("Odgovor1"), snapshot.getString("Odgovor2"), snapshot.getString("Odgovor3"), Objects.requireNonNull(snapshot.getLong("TocanOdgovor")), snapshot.getString("Slika")); ListaPitanja.add(pitanje); setPitanje(); } } }); } } }else{ txtBrojPitanja.setText("Pitanje 1/20"); List<Integer> ListaBrojeva = new ArrayList<>(); Random random = new Random(); int temp; for(int i = 0; i < 20; i++){ temp = random.nextInt(velinicnaSeta) +1; if(ListaBrojeva.contains(temp)){ i--; }else{ ListaBrojeva.add(temp); DocumentReference documentReference1 = fStore.collection("Pitanja") .document(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))) .collection(String.valueOf(getIntent().getStringExtra("IDSETA"))) .document("Pitanje" + ListaBrojeva.get(i)); documentReference1.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ DocumentSnapshot snapshot = task.getResult(); assert snapshot != null; Pitanje pitanje = new Pitanje(snapshot.getString("Pitanje"), snapshot.getString("Odgovor1"), snapshot.getString("Odgovor2"), snapshot.getString("Odgovor3"), Objects.requireNonNull(snapshot.getLong("TocanOdgovor")), snapshot.getString("Slika")); ListaPitanja.add(pitanje); setPitanje(); } } }); } } } } } }); }else { DocumentReference documentReference = fStore.collection("Pitanja").document(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))).collection("BrojPitanja").document(String.valueOf(getIntent().getStringExtra("IDSETA"))).collection("Pitanja").document(String.valueOf(getIntent().getStringExtra("IDDETALJNO"))); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ velinicnaSeta = Objects.requireNonNull(Objects.requireNonNull(task.getResult()).getLong("BrojPitanja")).intValue(); if(velinicnaSeta < 20){ txtBrojPitanja.setText("Pitanje 1/" + velinicnaSeta); if(velinicnaSeta == 0){ countDownTimer.cancel(); Intent intent = new Intent(VjezbePitanja.this, VjezbeRezultati.class); intent.putExtra("REZULTAT", "Baza podataka je prazna!"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left); }else { for (int i = 1; i <= velinicnaSeta; i++) { DocumentReference documentReference1 = fStore.collection("Pitanja").document(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))).collection(String.valueOf(getIntent().getStringExtra("IDSETA"))).document(String.valueOf(getIntent().getStringExtra("IDDETALJNO"))).collection("Pitanja").document("Pitanje" + i); documentReference1.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); assert snapshot != null; Pitanje pitanje = new Pitanje(snapshot.getString("Pitanje"), snapshot.getString("Odgovor1"), snapshot.getString("Odgovor2"), snapshot.getString("Odgovor3"), Objects.requireNonNull(snapshot.getLong("TocanOdgovor")), snapshot.getString("Slika")); ListaPitanja.add(pitanje); setPitanje(); } } }); } } }else{ txtBrojPitanja.setText("Pitanje 1/20"); List<Integer> ListaBrojeva = new ArrayList<>(); Random random = new Random(); int temp; for(int i = 0; i < 20; i++){ temp = random.nextInt(velinicnaSeta) +1; if(ListaBrojeva.contains(temp)){ i--; }else{ ListaBrojeva.add(temp); DocumentReference documentReference1 = fStore.collection("Pitanja").document(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))).collection(String.valueOf(getIntent().getStringExtra("IDSETA"))).document(String.valueOf(getIntent().getStringExtra("IDDETALJNO"))).collection("Pitanja").document("Pitanje" + ListaBrojeva.get(i)); documentReference1.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ DocumentSnapshot snapshot = task.getResult(); assert snapshot != null; Pitanje pitanje = new Pitanje(snapshot.getString("Pitanje"), snapshot.getString("Odgovor1"), snapshot.getString("Odgovor2"), snapshot.getString("Odgovor3"), Objects.requireNonNull(snapshot.getLong("TocanOdgovor")), snapshot.getString("Slika")); ListaPitanja.add(pitanje); setPitanje(); } } }); } } } } } }); } } private void setPitanje() { txtBrojac.setText(String.valueOf(45)); txtTekstPitanja.setText(ListaPitanja.get(0).getPitanje()); btnOdgovor1.setText(ListaPitanja.get(0).getOdgovor1()); btnOdgovor2.setText(ListaPitanja.get(0).getOdgovor2()); if(ListaPitanja.get(redniBrojPitanja).getOdgovor3().equals("0")){ btnOdgovor3.setVisibility(View.GONE); }else{ btnOdgovor3.setVisibility(View.VISIBLE); btnOdgovor3.setText(ListaPitanja.get(0).getOdgovor3()); } redniBrojPitanja = 0; if(!ListaPitanja.get(0).getSlika().equals("")){ Picasso.get().load(ListaPitanja.get(0).getSlika()).into(imgPitanja, new com.squareup.picasso.Callback() { @Override public void onSuccess() { ucitavanje.makniUcitavanje(); startTimer(); } @Override public void onError(Exception e) { } }); }else{ imgPitanja.setVisibility(View.GONE); if(provjeraTimera == 0){ ucitavanje.makniUcitavanje(); startTimer(); } provjeraTimera++; } } private void startTimer() { countDownTimer = new CountDownTimer(46000, 1000) { @Override public void onTick(long millisUntilFinished) { if(millisUntilFinished < 45000){ txtBrojac.setText(String.valueOf(millisUntilFinished / 1000)); } } @Override public void onFinish() { oznacavanjeOdgovora("0", btnOdgovori.getRootView()); promjeniPitanje(); } }; countDownTimer.start(); } private void provjeraOdogovora(String OznakaOdgovor1, String OznakaOdgovor2, String OznakaOdgovor3){ btnOdgovor1.setEnabled(false); btnOdgovor2.setEnabled(false); btnOdgovor3.setEnabled(false); int OznaceniOdgovor = 0; if(OznakaOdgovor1.equals("1")){ OznaceniOdgovor = 1; } if(OznakaOdgovor2.equals("1")){ if(OznaceniOdgovor == 1){ OznaceniOdgovor = 12; } else{ OznaceniOdgovor = 2; } } if(OznakaOdgovor3.equals("1")){ if(OznaceniOdgovor == 1){ OznaceniOdgovor = 13; } if(OznaceniOdgovor == 12){ OznaceniOdgovor = 123; } if(OznaceniOdgovor == 2){ OznaceniOdgovor = 23; } if(OznaceniOdgovor == 0){ OznaceniOdgovor = 3; } } if(OznaceniOdgovor == ListaPitanja.get(redniBrojPitanja).getTocanOdgovor()) { switch (OznaceniOdgovor){ case 1: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 2: btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 3: btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 12: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 13: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 23: btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 123: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; } rezultatExtra++; } else { btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); switch ((int) ListaPitanja.get(redniBrojPitanja).getTocanOdgovor()) { case 1: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 2: btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 3: btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 12: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 13: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 23: btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; case 123: btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); break; } } } private void promjeniPitanje(){ ucitavanje.pokreniUcitavanje(); if (redniBrojPitanja < ListaPitanja.size() - 1){ btnOdgovor1.setEnabled(true); btnOdgovor2.setEnabled(true); btnOdgovor3.setEnabled(true); redniBrojPitanja++; playAnim(txtTekstPitanja, 0, 0); playAnim(btnOdgovor1, 0, 1); playAnim(btnOdgovor2, 0, 2); if(ListaPitanja.get(redniBrojPitanja).getOdgovor3().equals("0")){ btnOdgovor3.setVisibility(View.GONE); }else{ btnOdgovor3.setVisibility(View.VISIBLE); playAnim(btnOdgovor3, 0, 3); } txtBrojPitanja.setText("Pitanje: " + (redniBrojPitanja+1) + "/" + ListaPitanja.size()); txtBrojac.setText(String.valueOf(45)); if(!ListaPitanja.get(redniBrojPitanja).getSlika().equals("")){ Picasso.get().load(ListaPitanja.get(redniBrojPitanja).getSlika()).into(imgPitanja, new com.squareup.picasso.Callback() { @Override public void onSuccess() { ucitavanje.makniUcitavanje(); startTimer(); } @Override public void onError(Exception e) { } }); }else{ imgPitanja.setVisibility(View.GONE); ucitavanje.makniUcitavanje(); startTimer(); } int img = R.drawable.neoznaceno_icon; btnOdgovor1.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); btnOdgovor2.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); btnOdgovor3.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } else{ userID = Objects.requireNonNull(fAuth.getCurrentUser()).getUid(); DocumentReference documentReference = fStore.collection("users").document(userID).collection(String.valueOf(getIntent().getStringExtra("IDKATEGORIJE"))).document(); Map<String, Object> rezultat = new HashMap<>(); rezultat.put("BrojTocnihOdgovora", rezultatExtra); rezultat.put("BrojPitanja", ListaPitanja.size()); documentReference.set(rezultat); Intent intent = new Intent(VjezbePitanja.this, VjezbeRezultati.class); intent.putExtra("REZULTAT", String.valueOf(rezultatExtra) + "/" + String.valueOf(ListaPitanja.size())); intent.putExtra("KATEGORIJA", getIntent().getStringExtra("KATEGORIJA")); intent.putExtra("LOGO", getIntent().getStringExtra("LOGO")); Pair[] pairs = new Pair[1]; pairs[0] = new Pair<View, String>(linearLayout4, getIntent().getStringExtra("LOGO")); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(VjezbePitanja.this, pairs); startActivity(intent, options.toBundle()); } } private void playAnim(final View view, final int value, final int viewBroj) { view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(150) .setStartDelay(100) .setInterpolator(new DecelerateInterpolator()).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if(value == 0){ switch (viewBroj){ case 0: ((TextView)view).setText(ListaPitanja.get(redniBrojPitanja).getPitanje()); break; case 1: ((Button)view).setText(ListaPitanja.get(redniBrojPitanja).getOdgovor1()); break; case 2: ((Button)view).setText(ListaPitanja.get(redniBrojPitanja).getOdgovor2()); break; case 3: ((Button)view).setText(ListaPitanja.get(redniBrojPitanja).getOdgovor3()); break; } if(viewBroj != 0){ ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); } playAnim(view, 1, viewBroj); } } }); } private void oznacavanjeOdgovora(String oznaceniOdgovor, View view){ if(oznaceniOdgovor.equals("1")){ if(OznakaOdgovor1.equals("0")){ OznakaOdgovor1 = "1"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#ffcc00"))); int img = R.drawable.oznaceno_icon; btnOdgovor1.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } else{ OznakaOdgovor1 = "0"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); int img = R.drawable.neoznaceno_icon; btnOdgovor1.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } } if(oznaceniOdgovor.equals("2")){ if(OznakaOdgovor2.equals("0")){ OznakaOdgovor2 = "1"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#ffcc00"))); int img = R.drawable.oznaceno_icon; btnOdgovor2.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } else{ OznakaOdgovor2 = "0"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); int img = R.drawable.neoznaceno_icon; btnOdgovor2.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } } if(oznaceniOdgovor.equals("3")){ if(OznakaOdgovor3.equals("0")){ OznakaOdgovor3 = "1"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#ffcc00"))); int img = R.drawable.oznaceno_icon; btnOdgovor3.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } else{ OznakaOdgovor3 = "0"; ((Button)view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); int img = R.drawable.neoznaceno_icon; btnOdgovor3.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0); } } if(oznaceniOdgovor.equals("0")){ OznakaOdgovor1 = "0"; OznakaOdgovor2 = "0"; OznakaOdgovor3 = "0"; btnOdgovor1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); btnOdgovor2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); btnOdgovor3.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#132131"))); } } @Override public void onBackPressed(){ DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: countDownTimer.cancel(); VjezbePitanja.super.onBackPressed(); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Jeste li sigurni da želite napustiti ovu vježbu?").setPositiveButton("Da", dialogClickListener) .setNegativeButton("Ne", dialogClickListener).show(); } } <file_sep>/app/src/main/java/com/example/autoskola_v1/DetaljnoRezultati.java package com.example.autoskola_v1; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.text.DecimalFormat; import java.util.Objects; public class DetaljnoRezultati extends AppCompatActivity { LinearLayout linearLayout26, txtBrojZavrsenihLayout, txtPostotakTocnihOdgovoraUVjezbamaLayout, txtNajboljeRjesenaVjezbaLayout, txtBrojPolozenihIspitaLayout; ImageView imgSlikaDetaljnoRezultati; TextView txtKategorijaDetaljnoRezultati, txtBrojZavrsenih, txtPostotakTocnihOdgovoraUVjezbama, txtNajboljeRjesenaVjezba, txtBrojPolozenihIspita, txtBrojZavrsenihNesto; Button btnIspitDetaljnoRezultati; int prolaznost = 0; FirebaseAuth fAuth; FirebaseFirestore fStore; String userID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_detaljno_rezultati); linearLayout26 = findViewById(R.id.linearLayout26); txtBrojZavrsenihLayout = findViewById(R.id.txtBrojZavrsenihLayout); txtPostotakTocnihOdgovoraUVjezbamaLayout = findViewById(R.id.txtPostotakTocnihOdgovoraUVjezbamaLayout); txtNajboljeRjesenaVjezbaLayout = findViewById(R.id.txtNajboljeRjesenaVjezbaLayout); txtBrojPolozenihIspitaLayout = findViewById(R.id.txtBrojPolozenihIspitaLayout); imgSlikaDetaljnoRezultati = findViewById(R.id.imgSlikaDetaljnoRezultati); txtKategorijaDetaljnoRezultati = findViewById(R.id.txtKategorijaDetaljnoRezultati); txtBrojZavrsenih = findViewById(R.id.txtBrojZavrsenih); txtPostotakTocnihOdgovoraUVjezbama = findViewById(R.id.txtPostotakTocnihOdgovoraUVjezbama); txtNajboljeRjesenaVjezba = findViewById(R.id.txtNajboljeRjesenaVjezba); txtBrojPolozenihIspita = findViewById(R.id.txtBrojPolozenihIspita); txtBrojZavrsenihNesto = findViewById(R.id.txtBrojZavrsenihNesto); btnIspitDetaljnoRezultati = findViewById(R.id.btnIspitDetaljnoRezultati); fAuth = FirebaseAuth.getInstance(); fStore = FirebaseFirestore.getInstance(); userID = Objects.requireNonNull(fAuth.getCurrentUser()).getUid(); linearLayout26.setTransitionName(getIntent().getStringExtra("LOGO")); txtKategorijaDetaljnoRezultati.setText(getIntent().getStringExtra("KATEGORIJA")); btnIspitDetaljnoRezultati.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(DetaljnoRezultati.this, ListaIspita.class); startActivity(intent); } }); if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Propisi")){ imgSlikaDetaljnoRezultati.setImageResource(R.drawable.vjezba_propisi_icon); getPropisiRezultati(); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Prva pomoć")){ imgSlikaDetaljnoRezultati.setImageResource(R.drawable.vjezba_prva_pomoc_icon); getPrvaPomocRezultati(); } if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Ispiti")){ imgSlikaDetaljnoRezultati.setImageResource(R.drawable.ispit_propisi_icon); getIspitiRezultati(); } } private void getPropisiRezultati() { txtBrojPolozenihIspitaLayout.setVisibility(View.GONE); btnIspitDetaljnoRezultati.setVisibility(View.GONE); CollectionReference collectionReference = fStore.collection("users").document(userID).collection("Kat1"); collectionReference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ int brojacZavrsenihVjezbi = 0; double tocniOdgovori = 0; double brojPitanja = 0; double postotak; double najboljeRjesen = 0; for(QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())){ tocniOdgovori = tocniOdgovori + snapshot.getDouble("BrojTocnihOdgovora"); brojPitanja = brojPitanja + snapshot.getDouble("BrojPitanja"); if(snapshot.getDouble("BrojTocnihOdgovora") / snapshot.getDouble("BrojPitanja") > najboljeRjesen){ najboljeRjesen = snapshot.getDouble("BrojTocnihOdgovora") / snapshot.getDouble("BrojPitanja"); } brojacZavrsenihVjezbi++; } if(brojacZavrsenihVjezbi == 0){ txtBrojZavrsenih.setText(String.valueOf(brojacZavrsenihVjezbi)); txtPostotakTocnihOdgovoraUVjezbama.setText(String.valueOf(0)); txtNajboljeRjesenaVjezba.setText(String.valueOf(0)); }else{ DecimalFormat df = new DecimalFormat("##.##%"); postotak = (tocniOdgovori / brojPitanja); String formattedPercent = df.format(postotak); String formattedPercent1 = df.format(najboljeRjesen); txtBrojZavrsenih.setText(String.valueOf(brojacZavrsenihVjezbi)); txtPostotakTocnihOdgovoraUVjezbama.setText(formattedPercent); txtNajboljeRjesenaVjezba.setText(formattedPercent1); } } } }); } private void getPrvaPomocRezultati() { txtBrojPolozenihIspitaLayout.setVisibility(View.GONE); btnIspitDetaljnoRezultati.setVisibility(View.GONE); CollectionReference collectionReference1 = fStore.collection("users").document(userID).collection("Kat2"); collectionReference1.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ int brojacZavrsenihVjezbi = 0; double tocniOdgovori = 0; double brojPitanja = 0; double postotak; double najboljeRjesen = 0; for(QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())){ tocniOdgovori = tocniOdgovori + snapshot.getDouble("BrojTocnihOdgovora"); brojPitanja = brojPitanja + snapshot.getDouble("BrojPitanja"); if(snapshot.getDouble("BrojTocnihOdgovora") / snapshot.getDouble("BrojPitanja") > najboljeRjesen){ najboljeRjesen = snapshot.getDouble("BrojTocnihOdgovora") / snapshot.getDouble("BrojPitanja"); } brojacZavrsenihVjezbi++; } if(brojacZavrsenihVjezbi == 0){ txtBrojZavrsenih.setText(String.valueOf(brojacZavrsenihVjezbi)); txtPostotakTocnihOdgovoraUVjezbama.setText(String.valueOf(0)); txtNajboljeRjesenaVjezba.setText(String.valueOf(0)); }else{ DecimalFormat df = new DecimalFormat("##.##%"); postotak = (tocniOdgovori / brojPitanja); String formattedPercent = df.format(postotak); String formattedPercent1 = df.format(najboljeRjesen); txtBrojZavrsenih.setText(String.valueOf(brojacZavrsenihVjezbi)); txtPostotakTocnihOdgovoraUVjezbama.setText(formattedPercent); txtNajboljeRjesenaVjezba.setText(formattedPercent1); } } } }); } private void getIspitiRezultati() { txtPostotakTocnihOdgovoraUVjezbamaLayout.setVisibility(View.GONE); txtNajboljeRjesenaVjezbaLayout.setVisibility(View.GONE); DocumentReference documentReference = fStore.collection("users").document(userID).collection("BrojRjesenihIspita").document("Broj"); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ DocumentSnapshot snapshot = task.getResult(); assert snapshot != null; if(snapshot.getLong("Broj") == null){ txtBrojZavrsenih.setText("0"); btnIspitDetaljnoRezultati.setVisibility(View.GONE); }else{ txtBrojZavrsenih.setText(String.valueOf(snapshot.getLong("Broj"))); } txtBrojZavrsenihNesto.setText("Broj završenih ispita:"); if(snapshot.getLong("Broj") != null) { CollectionReference collectionReference = fStore.collection("users").document(userID).collection("RjeseniIspiti"); collectionReference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) { if(Objects.equals(document.getData().get("Prolaznost"), "Ispit je položen!")){ prolaznost++; } } txtBrojPolozenihIspita.setText(String.valueOf(prolaznost)); } } }); } } } }); } }<file_sep>/app/src/main/java/com/example/autoskola_v1/Login.java package com.example.autoskola_v1; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.ActivityOptions; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Pair; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import java.util.Objects; public class Login extends AppCompatActivity { ImageView imgLogoLogin; TextInputEditText txtEmail, txtSifra; TextInputLayout Email, Sifra; TextView txtNaslov, txtPodnaslov; Button btnUlogirajSe, btnZaboravljenaSifra, btnRegistracija; FirebaseAuth fAuth; Ucitavanje ucitavanje = new Ucitavanje(Login.this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_login); txtEmail = findViewById(R.id.txtEmail); txtSifra = findViewById(R.id.txtSifra); fAuth = FirebaseAuth.getInstance(); btnUlogirajSe = findViewById(R.id.btnUlogirajSe); btnRegistracija = findViewById(R.id.btnRegistracija); btnZaboravljenaSifra = findViewById(R.id.btnZaboravljenaSifra); Email = findViewById(R.id.Email); Sifra = findViewById(R.id.Sifra); imgLogoLogin = findViewById(R.id.imgLogoLogin); txtNaslov = findViewById(R.id.txtNaslov); txtPodnaslov = findViewById(R.id.txtPodnaslov); btnUlogirajSe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String email = Objects.requireNonNull(txtEmail.getText()).toString(); String sifra = Objects.requireNonNull(txtSifra.getText()).toString(); if(TextUtils.isEmpty(email)){ txtEmail.setError("Email nije unesen!"); return; } if(TextUtils.isEmpty(sifra)){ txtSifra.setError("Sifra nije unesena!"); return; } if(sifra.length() < 6){ txtSifra.setError("Sifra mora imati barem 6 znakova!"); return; } ucitavanje.pokreniUcitavanje(); fAuth.signInWithEmailAndPassword(email,sifra).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { Toast.makeText(Login.this,"Ulogiravanje uspijesno!", Toast.LENGTH_LONG).show(); Intent intent = new Intent(Login.this, GlavniIzbornik.class); Pair[] pairs = new Pair[3]; pairs[0] = new Pair<View, String>(imgLogoLogin, "logo_image"); pairs[1] = new Pair<View, String>(txtNaslov, "logo_text"); pairs[2] = new Pair<View, String>(txtPodnaslov, "logo_desc"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(Login.this, pairs); ucitavanje.makniUcitavanje(); startActivity(intent, options.toBundle()); Login.this.finishAfterTransition(); }else{ Toast.makeText(Login.this, "Neuspjesno ulogiravanje!" + task.getException().getMessage(), Toast.LENGTH_LONG).show(); ucitavanje.makniUcitavanje(); } } }); } }); btnRegistracija.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Register.class); Pair[] pairs = new Pair[8]; pairs[0] = new Pair<View, String>(imgLogoLogin, "logo_image"); pairs[1] = new Pair<View, String>(txtNaslov, "logo_text"); pairs[2] = new Pair<View, String>(txtPodnaslov, "logo_desc"); pairs[3] = new Pair<View, String>(Email, "email_trans"); pairs[4] = new Pair<View, String>(Sifra, "pass_trans"); pairs[5] = new Pair<View, String>(btnZaboravljenaSifra, "forget_trans"); pairs[6] = new Pair<View, String>(btnUlogirajSe, "prijava_trans"); pairs[7] = new Pair<View, String>(btnRegistracija, "register_login_trans"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(Login.this, pairs); startActivity(intent, options.toBundle()); } }); btnZaboravljenaSifra.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final EditText resetEmail = new EditText(v.getContext()); AlertDialog.Builder dijalogZaPromjenuSifre = new AlertDialog.Builder(v.getContext()); dijalogZaPromjenuSifre.setTitle("Promjena šifre?"); dijalogZaPromjenuSifre.setMessage("Upiši svoj email kako bi primio link za promjenu šifre!"); dijalogZaPromjenuSifre.setView(resetEmail); dijalogZaPromjenuSifre.setPositiveButton("Da", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String emailPromjena = resetEmail.getText().toString(); if(emailPromjena.length() < 1){ Toast.makeText(Login.this,"Niste unijeli e-mail!", Toast.LENGTH_SHORT).show(); } else{ fAuth.sendPasswordResetEmail(emailPromjena).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(Login.this,"Link za promjenu lozinke vam je poslan na email!", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(Login.this, "Link za promjenu šifre nije poslan!" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } }); dijalogZaPromjenuSifre.setNegativeButton("Ne", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dijalogZaPromjenuSifre.create().show(); } }); } } <file_sep>/app/src/main/java/com/example/autoskola_v1/AdminIzbornik.java package com.example.autoskola_v1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import java.util.Objects; public class AdminIzbornik extends AppCompatActivity { Button btnDodaj, btnIzmjeni, btnIzbrisi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_admin_izbornik); btnDodaj = findViewById(R.id.btnDodaj); btnIzmjeni = findViewById(R.id.btnIzmjeni); btnIzbrisi = findViewById(R.id.btnIzbrisi); btnDodaj.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Kat1")){ Intent intent = new Intent(AdminIzbornik.this, TeorijaPropisi.class); intent.putExtra("ADMIN", "Dodavanje"); startActivity(intent); }else{ Intent intent = new Intent(AdminIzbornik.this, TeorijaPrvaPomoc.class); intent.putExtra("ADMIN", "Dodavanje"); startActivity(intent); } } }); btnIzmjeni.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Kat1")){ Intent intent = new Intent(AdminIzbornik.this, TeorijaPropisi.class); intent.putExtra("ADMIN", "Izmjene"); startActivity(intent); }else{ Intent intent = new Intent(AdminIzbornik.this, TeorijaPrvaPomoc.class); intent.putExtra("ADMIN", "Izmjene"); startActivity(intent); } } }); btnIzbrisi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Objects.equals(getIntent().getStringExtra("KATEGORIJA"), "Kat1")){ Intent intent = new Intent(AdminIzbornik.this, TeorijaPropisi.class); intent.putExtra("ADMIN", "Brisanje"); startActivity(intent); }else{ Intent intent = new Intent(AdminIzbornik.this, TeorijaPrvaPomoc.class); intent.putExtra("ADMIN", "Brisanje"); startActivity(intent); } } }); } }<file_sep>/app/src/main/java/com/example/autoskola_v1/Pitanje.java package com.example.autoskola_v1; public class Pitanje { private String Pitanje; private String Odgovor1; private String Odgovor2; private String Odgovor3; private long TocanOdgovor; private String Slika; private String name; public Pitanje(){} public Pitanje(String Pitanje, String Odgovor1, String Odgovor2, String Odgovor3, long TocanOdgovor, String Slika) { this.Pitanje = Pitanje; this.Odgovor1 = Odgovor1; this.Odgovor2 = Odgovor2; this.Odgovor3 = Odgovor3; this.TocanOdgovor = TocanOdgovor; this.Slika = Slika; } public Pitanje(String Pitanje, String Odgovor1, String Odgovor2, String Odgovor3, long TocanOdgovor, String Slika, String name) { this.Pitanje = Pitanje; this.Odgovor1 = Odgovor1; this.Odgovor2 = Odgovor2; this.Odgovor3 = Odgovor3; this.TocanOdgovor = TocanOdgovor; this.Slika = Slika; this.name = name; } public void setPitanje(String pitanje) { Pitanje = pitanje; } public void setOdgovor1(String odgovor1) { Odgovor1 = odgovor1; } public void setOdgovor2(String odgovor2) { Odgovor2 = odgovor2; } public void setOdgovor3(String odgovor3) { Odgovor3 = odgovor3; } public void setTocanOdgovor(long tocanOdgovor) { TocanOdgovor = tocanOdgovor; } public void setSlika(String slika) { Slika = slika; } public String getPitanje() { return Pitanje; } public String getOdgovor1() { return Odgovor1; } public String getOdgovor2() { return Odgovor2; } public String getOdgovor3() { return Odgovor3; } public long getTocanOdgovor() { return TocanOdgovor; } public String getSlika() { return Slika; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/app/src/main/java/com/example/autoskola_v1/ListaIspita.java package com.example.autoskola_v1; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.ActivityOptions; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.android.material.button.MaterialButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.squareup.picasso.Picasso; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; public class ListaIspita extends AppCompatActivity { private RecyclerView FireStoreListaIspita; private FirebaseFirestore fStore; private FirebaseAuth fAuth; private FirestoreRecyclerAdapter adapter; Query query; String userID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_lista_ispita); fStore = FirebaseFirestore.getInstance(); fAuth = FirebaseAuth.getInstance(); FireStoreListaIspita = findViewById(R.id.FireStoreListaIspita); userID = Objects.requireNonNull(fAuth.getCurrentUser()).getUid(); query = fStore.collection("users").document(userID).collection("RjeseniIspiti").orderBy("RedniBroj"); FirestoreRecyclerOptions<Ispiti> options = new FirestoreRecyclerOptions.Builder<Ispiti>() .setQuery(query, Ispiti.class) .build(); adapter = new FirestoreRecyclerAdapter<Ispiti, IspitiViewHolder>(options) { @NonNull @Override public IspitiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_svih_ispita, parent, false); return new IspitiViewHolder(view); } @Override protected void onBindViewHolder(@NonNull IspitiViewHolder holder, int position, @NonNull Ispiti model) { holder.Naziv.setText(model.getNaziv()); holder.Naziv.setTransitionName(model.getBrojIspita()); holder.NazivDatoteke = model.getBrojIspita(); } }; FireStoreListaIspita.setLayoutManager(new LinearLayoutManager(this)); FireStoreListaIspita.setAdapter(adapter); } private class IspitiViewHolder extends RecyclerView.ViewHolder{ private Button Naziv; private String NazivDatoteke; public IspitiViewHolder(@NonNull View itemView) { super(itemView); Naziv = itemView.findViewById(R.id.Naziv); Naziv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListaIspita.this, IspitRezultati.class); intent.putExtra("ISPIT", NazivDatoteke); Pair[] pairs = new Pair[1]; pairs[0] = new Pair<View, String>(Naziv, NazivDatoteke); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(ListaIspita.this, pairs); startActivity(intent, options.toBundle()); } }); } } @Override protected void onStop() { super.onStop(); adapter.stopListening(); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } }<file_sep>/app/src/main/java/com/example/autoskola_v1/SplashScreen.java package com.example.autoskola_v1; import androidx.appcompat.app.AppCompatActivity; import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Pair; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; public class SplashScreen extends AppCompatActivity { Animation topAnim, bottomAnim; ImageView imgLogoSplashScreen; TextView txtVelikiSplashScreen, txtMaliSplashScreen; FirebaseAuth fAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_splash_screen); fAuth = FirebaseAuth.getInstance(); topAnim = AnimationUtils.loadAnimation(this, R.anim.top_animation); bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_animation); imgLogoSplashScreen = findViewById(R.id.imgLogoSplashScreen); txtVelikiSplashScreen = findViewById(R.id.txtVelikiSplashScreen); txtMaliSplashScreen = findViewById(R.id.txtMaliSplashScreen); imgLogoSplashScreen.setAnimation(topAnim); txtVelikiSplashScreen.setAnimation(bottomAnim); txtMaliSplashScreen.setAnimation(bottomAnim); new Handler().postDelayed(new Runnable() { @Override public void run() { if(fAuth.getCurrentUser() != null){ Intent intent = new Intent(SplashScreen.this, GlavniIzbornik.class); Pair[] pairs = new Pair[3]; pairs[0] = new Pair<View, String>(imgLogoSplashScreen, "logo_image"); pairs[1] = new Pair<View, String>(txtVelikiSplashScreen, "logo_text"); pairs[2] = new Pair<View, String>(txtVelikiSplashScreen, "logo_desc"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SplashScreen.this, pairs); startActivity(intent, options.toBundle()); }else{ Intent intent = new Intent(SplashScreen.this, Login.class); Pair[] pairs = new Pair[3]; pairs[0] = new Pair<View, String>(imgLogoSplashScreen, "logo_image"); pairs[1] = new Pair<View, String>(txtVelikiSplashScreen, "logo_text"); pairs[2] = new Pair<View, String>(txtVelikiSplashScreen, "logo_desc"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SplashScreen.this, pairs); startActivity(intent, options.toBundle()); } } }, 3000); } }<file_sep>/app/src/main/java/com/example/autoskola_v1/Register.java package com.example.autoskola_v1; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.ActivityOptions; import android.content.Intent; import android.nfc.Tag; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; public class Register extends AppCompatActivity { TextInputEditText txtImePrezime, txtEmail, txtSifra, txtPotvrdaSifre; TextInputLayout txtEmailRegistracija, txtSifraRegistracija; ImageView imgLogoRegister; Button btnRegistrirajSe, btnLogin; TextView txtNaslovRegistracija, txtPodnaslovRegistracija; FirebaseAuth fAuth; FirebaseFirestore fStore; String userID; Ucitavanje ucitavanje = new Ucitavanje(Register.this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_register); txtImePrezime = findViewById(R.id.txtImePrezime); txtEmail = findViewById(R.id.txtEmail); txtSifra = findViewById(R.id.txtSifra); txtPotvrdaSifre = findViewById(R.id.txtPotvrdaSifre); btnRegistrirajSe = findViewById(R.id.btnUlogirajSe); btnLogin = findViewById(R.id.btnLogin); imgLogoRegister = findViewById(R.id.imgLogoRegister); txtNaslovRegistracija = findViewById(R.id.txtNaslovRegistracija); txtPodnaslovRegistracija = findViewById(R.id.txtPodnaslovRegistracija); txtEmailRegistracija = findViewById(R.id.txtEmailRegistracija); txtSifraRegistracija = findViewById(R.id.txtSifraRegistracija); fAuth = FirebaseAuth.getInstance(); fStore = FirebaseFirestore.getInstance(); btnRegistrirajSe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String email = txtEmail.getText().toString().trim(); String sifra = txtSifra.getText().toString().trim(); String potvrdaSifre = txtPotvrdaSifre.getText().toString().trim(); final String ImePrezime = txtImePrezime.getText().toString(); if(TextUtils.isEmpty(email)){ txtEmail.setError("Email nije unesen!"); return; } else if(TextUtils.isEmpty(sifra)){ txtSifra.setError("Sifra nije unesena!"); return; } else if(TextUtils.isEmpty(potvrdaSifre)){ txtPotvrdaSifre.setError("Potvrda sifre nije unesena!"); return; } else if(sifra.length() < 6){ txtSifra.setError("Sifra mora imati barem 6 znakova!"); return; } else if(!potvrdaSifre.equals(sifra)){ txtPotvrdaSifre.setError("Sifre se ne podudaraju!"); return; } ucitavanje.pokreniUcitavanje(); fAuth.createUserWithEmailAndPassword(email,sifra).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Toast.makeText(Register.this,"Racun napravljen!", Toast.LENGTH_LONG).show(); userID = fAuth.getCurrentUser().getUid(); DocumentReference documentReference = fStore.collection("users").document(userID); Map<String, Object> user = new HashMap<>(); user.put("ImePrezime", ImePrezime); user.put("Email", email); documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(Register.this, "Korisnički profil je napravljen!", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(Register.this, "Greška: " + e.toString(), Toast.LENGTH_SHORT).show(); } }); Intent intent = new Intent(getApplicationContext(),GlavniIzbornik.class); Pair[] pairs = new Pair[3]; pairs[0] = new Pair<View, String>(imgLogoRegister, "logo_image"); pairs[1] = new Pair<View, String>(txtNaslovRegistracija, "logo_text"); pairs[2] = new Pair<View, String>(txtPodnaslovRegistracija, "logo_desc"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(Register.this, pairs); ucitavanje.makniUcitavanje(); startActivity(intent, options.toBundle()); }else{ Toast.makeText(Register.this, "Neuspjela registracija! " + task.getException().getMessage(), Toast.LENGTH_LONG).show(); ucitavanje.makniUcitavanje(); } } }); } }); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Register.this, Login.class); Pair[] pairs = new Pair[7]; pairs[0] = new Pair<View, String>(imgLogoRegister, "logo_image"); pairs[1] = new Pair<View, String>(txtNaslovRegistracija, "logo_text"); pairs[2] = new Pair<View, String>(txtPodnaslovRegistracija, "logo_desc"); pairs[3] = new Pair<View, String>(txtEmailRegistracija, "email_trans"); pairs[4] = new Pair<View, String>(txtSifraRegistracija, "pass_trans"); pairs[5] = new Pair<View, String>(btnRegistrirajSe, "prijava_trans"); pairs[6] = new Pair<View, String>(btnLogin, "register_login_trans"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(Register.this, pairs); startActivity(intent, options.toBundle()); } }); } } <file_sep>/app/src/main/java/com/example/autoskola_v1/TeorijaPrvaPomoc.java package com.example.autoskola_v1; import androidx.appcompat.app.AppCompatActivity; import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.util.Pair; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import java.util.Objects; public class TeorijaPrvaPomoc extends AppCompatActivity { Button btn1_22Teorija, btn23_44Teorija, btn45_66Teorija; TextView txtOpis; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_teorija_prva_pomoc); btn1_22Teorija = findViewById(R.id.btn1_22Teorija); btn23_44Teorija = findViewById(R.id.btn23_44Teorija); btn45_66Teorija = findViewById(R.id.btn45_66Teorija); txtOpis = findViewById(R.id.txtOpis); if(getIntent().getStringExtra("ADMIN")!=null) { txtOpis.setText("Odaberi set za " + getIntent().getStringExtra("ADMIN") + ":"); } btn1_22Teorija.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(getIntent().getStringExtra("ADMIN")!=null){ if(Objects.equals(getIntent().getStringExtra("ADMIN"), "Dodavanje")){ Intent intent = new Intent(TeorijaPrvaPomoc.this,AdminPitanje.class); intent.putExtra("KATEGORIJA", "1. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","1_22"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,EditiranjePitanja.class); intent.putExtra("KATEGORIJA", "1. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","1_22"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); } }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,TeorijaPitanja.class); intent.putExtra("KATEGORIJA", "1. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","1_22"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("LOGO","logo_image_set_1"); Pair[] pairs = new Pair[1]; pairs[0] = new Pair<View, String>(btn1_22Teorija, "logo_image_set_1"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(TeorijaPrvaPomoc.this, pairs); startActivity(intent, options.toBundle()); } } }); btn23_44Teorija.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(getIntent().getStringExtra("ADMIN")!=null){ if(Objects.equals(getIntent().getStringExtra("ADMIN"), "Dodavanje")){ Intent intent = new Intent(TeorijaPrvaPomoc.this,AdminPitanje.class); intent.putExtra("KATEGORIJA", "2. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","23_44"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,EditiranjePitanja.class); intent.putExtra("KATEGORIJA", "2. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","23_44"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); } }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,TeorijaPitanja.class); intent.putExtra("KATEGORIJA", "2. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","23_44"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("LOGO","logo_image_set_2"); Pair[] pairs = new Pair[1]; pairs[0] = new Pair<View, String>(btn23_44Teorija, "logo_image_set_2"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(TeorijaPrvaPomoc.this, pairs); startActivity(intent, options.toBundle()); } } }); btn45_66Teorija.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(getIntent().getStringExtra("ADMIN")!=null){ if(Objects.equals(getIntent().getStringExtra("ADMIN"), "Dodavanje")){ Intent intent = new Intent(TeorijaPrvaPomoc.this,AdminPitanje.class); intent.putExtra("KATEGORIJA", "3. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","45_66"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,EditiranjePitanja.class); intent.putExtra("KATEGORIJA", "3. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","45_66"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("ADMIN", getIntent().getStringExtra("ADMIN")); startActivity(intent); } }else{ Intent intent = new Intent(TeorijaPrvaPomoc.this,TeorijaPitanja.class); intent.putExtra("KATEGORIJA", "3. set pitanja"); intent.putExtra("IDKATEGORIJE", "Kat2"); intent.putExtra("IDSETA","45_66"); intent.putExtra("IDDETALJNO","0"); intent.putExtra("LOGO","logo_image_set_3"); Pair[] pairs = new Pair[1]; pairs[0] = new Pair<View, String>(btn45_66Teorija, "logo_image_set_3"); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(TeorijaPrvaPomoc.this, pairs); startActivity(intent, options.toBundle()); } } }); } } <file_sep>/settings.gradle include ':app' rootProject.name='AutoSkola_V1'
7dc7f1b6df66217d41090518d73671bc5b11501b
[ "Java", "Gradle" ]
11
Java
niblazevic/AutoSkola
420555759be6769093a1878ff660bbd1107955b2
148be1c623ab78f72fa0e9db65e1d3911a250db1
refs/heads/master
<repo_name>dannguyencoder/short_story<file_sep>/app/src/main/java/com/example/os_vinhnq/shortstoryapp/ShortStoryDatabaseHelper.java package com.example.os_vinhnq.shortstoryapp; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; public class ShortStoryDatabaseHelper extends SQLiteOpenHelper { //Database info private static final String DATABASE_NAME = "shortStoryDatabase"; private static final int DATABASE_VERSION = 3; //Table names private static final String TABLE_SHORT_STORY = "short_story"; //Short Story table columns private static final String KEY_ID = "id"; private static final String KEY_STORY_NAME = "story_name"; private static final String KEY_STORY_DESCRIPTION = "story_description"; private static final String KEY_STORY_CONTENT = "story_content"; private static final String KEY_STORY_THUMBNAIL_LINK = "story_thumbnail_link"; private static ShortStoryDatabaseHelper sInstance; public static synchronized ShortStoryDatabaseHelper getInstance(Context context) { //Use the application context, which will ensure that you don't accidentally leak Activity's context. if (sInstance == null) { sInstance = new ShortStoryDatabaseHelper(context.getApplicationContext()); } return sInstance; } private ShortStoryDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } //Called when the database is created for the first time //If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String CREATE_SHORT_STORY_TABLE = "CREATE TABLE " + TABLE_SHORT_STORY + "(" + KEY_ID + " INTEGER PRIMARY KEY," + //Define a primary key KEY_STORY_NAME + " TEXT," + KEY_STORY_DESCRIPTION + " TEXT," + KEY_STORY_CONTENT + " TEXT," + KEY_STORY_THUMBNAIL_LINK + " TEXT" + ")"; sqLiteDatabase.execSQL(CREATE_SHORT_STORY_TABLE); } //Called when the database needs to upgraded //This method will only be called if a database already exists on disk with the dame DATABASE_NAME //but the DATABASE_VERSION is different than the version of the database that exists on disk @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { //Simplest implementation is to drop all old tables and recreate them sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_SHORT_STORY); onCreate(sqLiteDatabase); } //CRUD Operations //Insert a story into the database public void addStory(ShortStory shortStory) { //Create and/or open the database for writing SQLiteDatabase db = getWritableDatabase(); //It's good idea to wrap our insert in a transaction. This helps with performance and ensures //consistency of database db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put(KEY_STORY_NAME, shortStory.getStoryName()); values.put(KEY_STORY_DESCRIPTION, shortStory.getStoryDescription()); values.put(KEY_STORY_CONTENT, shortStory.getStoryDescription()); values.put(KEY_STORY_THUMBNAIL_LINK, shortStory.getStoryThumbnailLink()); //Notice how we haven't specified the primary key. SQLite auto increment the primary column db.insertOrThrow(TABLE_SHORT_STORY, null, values); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); Log.d("Short_story_app", "Error when trying to add story to the database"); } finally { db.endTransaction(); } } public List<ShortStory> getAllStory() { List<ShortStory> shortStories = new ArrayList<>(); //SELECT * FROM short_story String STORY_SELECT_QUERY = String.format("SELECT * FROM %s", TABLE_SHORT_STORY); //getReadableDatabase() and getWritableDatabase() return the same object (except under low disk space scenarios) SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(STORY_SELECT_QUERY, null); try { if (cursor.moveToFirst()) { do { ShortStory shortStory = new ShortStory(); shortStory.setStoryName(cursor.getString(cursor.getColumnIndex(KEY_STORY_NAME))); shortStory.setStoryDescription(cursor.getString(cursor.getColumnIndex(KEY_STORY_DESCRIPTION))); shortStory.setStoryContent(cursor.getString(cursor.getColumnIndex(KEY_STORY_CONTENT))); shortStory.setStoryThumbnailLink(cursor.getString(cursor.getColumnIndex(KEY_STORY_THUMBNAIL_LINK))); shortStories.add(shortStory); } while (cursor.moveToNext()); } } catch (Exception e) { Log.d("Short_story_app", "Error when trying to get story from database"); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return shortStories; } }
0cb684e519d4867a21e38370ab576c7ed46ca025
[ "Java" ]
1
Java
dannguyencoder/short_story
9db3c9c1e98b06db6c2556d629e09fc371172428
82e13b7b5178d24622544383f7bf412ae6ed6fb6
refs/heads/master
<file_sep>import { Game, AUTO } from 'phaser'; import TestScene from './test-scene.js' const config = { type: AUTO, width: 800, height: 800, physics: { default: 'matter', matter: { gravity: { y: .5 }, debug: false } }, scene: [ TestScene ] }; export class MainGame extends Game { constructor() { super(config) } } export default MainGame; <file_sep>'use strict'; const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'index.bundle.js' }, devServer: { contentBase: path.join(__dirname, 'dist'), host: '0.0.0.0', port: 3000 }, module: { rules: [ { test: /\.(png|jpg|gif|svg)$/, use: [ { loader: 'file-loader', options: {} } ] }, { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] } //, //{ // test: [ /\.vert$/, /\.frag$/ ], // use: 'raw-loader' //} ] }, plugins: [ new HtmlWebpackPlugin({ title: "gameoff 2018", hash: true, showErrors: true }), new webpack.DefinePlugin({ 'CANVAS_RENDERER': JSON.stringify(true), 'WEBGL_RENDERER': JSON.stringify(true) }) ] }; <file_sep> import { Scene, GameObjects, Matter } from 'phaser'; import sumo from '../assets/dude.png'; import sumo2 from '../assets/dude2.png'; import dudes from '../assets/Dudes.png'; import ball from '../assets/balls.png'; import background from '../assets/backG.png'; import boden from '../assets/boden.png'; import bamboo from '../assets/bamboo.png'; import house from '../assets/house.png'; import w1 from '../assets/w1.png'; import w2 from '../assets/w2.png'; import w3 from '../assets/w3.png'; import w4 from '../assets/w4.png'; import gameover from '../assets/game-over.png'; import presents from '../assets/BS_presents.png'; import title from '../assets/sumo_raice.png'; import info from '../assets/INFO.png'; import style from '../style/default.css'; const viewHeight = 800; const speed = 8; let gameHeight = 1000; let gameRunning = false; var score = 0; var scoreString = "Score: "; var scoreText, gameoverText; var highestTouchPlayer = 1 class TestScene extends Scene { constructor() { super({ key: "TestScene" }) } startGame() { this.presents.setVisible(false) this.title.setVisible(false) this.ballSprite.setIgnoreGravity(false) this.gameStarted = true; this.ballSprite.applyForce({x: -0.01, y: -0.03}) } gameOver () { if (gameRunning) { if (this.character == this.ballSprite.lastTouchedBy) { highestTouchPlayer = 1; } else { highestTouchPlayer = 2; } scoreText = this.add.text(32, 24, scoreString + score, { fontSize: 32, stroke: 'black', strokeThickness: 5 }); gameoverText = this.add.image(32, 24, 'gameover'); gameoverText.visible = false; console.log("gameover") gameRunning = false; scoreText.visible = true; gameoverText.visible = true; scoreText.setText("Player: " + highestTouchPlayer + " score: " + Math.round(score, 0)); } } createWalls(fromHeight, toHeight) { const bambooHeight = 2000; for (let i = -fromHeight; i > -toHeight; i -= bambooHeight) { const left = this.matter.add.image(0, i, 'bamboo') left.setCollisionCategory(this.catWalls); left.setStatic(true) const right = this.matter.add.image(800, i, 'bamboo') right.setCollisionCategory(this.catWalls); right.setStatic(true) //walls.push(right) } } createClouds(fromHeight, toHeight) { for (let i = -fromHeight - (Math.random() * 1000); i > -toHeight; i -= (Math.random() * 1000)) { const cloud = this.matter.add.image((Math.random() * 1600) - 800, i, 'w' + Math.ceil((Math.random() * 3))) cloud.setScale(Math.random() * 2) cloud.setIgnoreGravity(true) cloud.setCollidesWith([]) this.clouds.push({ cloud: cloud, direction: (Math.ceil(i) % 3) - 1 }) } } preload () { this.load.spritesheet('sumoSheet', dudes, { frameWidth: 100, frameHeight: 100}) this.load.image('sumo', sumo) this.load.image('sumo2', sumo2) this.load.image('ball', ball) this.load.image('background', background) this.load.image('boden', boden) this.load.image('bamboo', bamboo) this.load.image('house', house) this.load.image('w1', w1) this.load.image('w2', w2) this.load.image('w3', w3) this.load.image('w4', w4) this.load.image('gameover', gameover) this.load.image('presents', presents) this.load.image('title', title) this.load.image('info', info) //this.player.body. //this.load.image('circle', circle); } create () { gameHeight = 1000; this.gameStarted = false; gameRunning = true; score = 0; var catChars = this.matter.world.nextCategory(); var catWalls = this.matter.world.nextCategory(); this.catWalls = catWalls; var catFloor = this.matter.world.nextCategory(); var catBalls = this.matter.world.nextCategory(); var catBackground = this.matter.world.nextCategory(); this.cursors = this.input.keyboard.createCursorKeys() this.cursors2 = this.input.keyboard.addKeys( {up:Phaser.Input.Keyboard.KeyCodes.W, down:Phaser.Input.Keyboard.KeyCodes.S, left:Phaser.Input.Keyboard.KeyCodes.A, right:Phaser.Input.Keyboard.KeyCodes.D}); //console.log(this.matter) const y = -100 this.matter.world.setBounds(0, 0, 800, 600) // set background this.background = this.matter.scene.add.image(0, gameHeight, 'background') this.background.setScale(1.2) // clouds this.clouds = [] this.createClouds(0, gameHeight) //for (let i = y - (Math.random() * 1000); i > 1000; i -= (Math.random() * 1000)) { // const cloud = this.matter.add.image((Math.random() * 1600) - 800, i, 'w' + Math.ceil((Math.random() * 3))) // cloud.setScale(Math.random() * 2) // cloud.setIgnoreGravity(true) // cloud.setCollidesWith([]) // this.clouds.push({ // cloud: cloud, // direction: (Math.ceil(i) % 3) - 1 // }) //} //this.background.setCollisionCategory(catBackground) const bounceFactor = .8 //creating player 1 and player 2: this.character = this.matter.add.sprite(200, y, 'sumoSheet', 2) this.character.setCircle(50) this.character.canJump = true; this.character.lastHit = true; this.character.setFrictionAir(0) this.character.setMass(20) this.character.setBounce(bounceFactor,bounceFactor) this.character.setCollisionCategory(catChars); this.character.setCollidesWith([ catWalls, catFloor, catChars, catBalls]); const char1 = this.character; this.character2 = this.matter.add.sprite(600, y, 'sumoSheet', 2) this.character2.setCircle(50) this.character2.canJump = true; this.character2.lastHit = false; this.character2.setFrictionAir(0) this.character2.setMass(20) this.character2.setBounce(bounceFactor,bounceFactor) this.character2.setCollisionCategory(catChars); this.character2.setCollidesWith([ catWalls, catFloor, catChars, catBalls]); const char2 = this.character2; this.matter.scene.cameras.main.setBounds(0, 0, 800, gameHeight - 175) //var cameraX = (this.character.body.position.x + this.character2.body.position.x) / 2 var cameraY = (this.character.body.position.y + this.character2.body.position.y) / 2 const walls = []; // create initial walls this.createWalls(0, 1000) const houseSprite = this.matter.add.image(400, - 360, 'house') houseSprite.setCollisionCategory(catBackground); houseSprite.setStatic(true) for (let i = 0; i < 2; i++) { const floor = this.matter.add.image(i * 800, 0, 'boden').setOrigin(0.5, 0.55) floor.setCollisionCategory(catFloor); floor.setStatic(true) } // Title this.presents = this.matter.scene.add.image(400, -800, 'presents') this.title = this.matter.scene.add.image(400, -490, 'title') this.ballSprite = this.matter.add.image(585, y - 472, 'ball') const ballScale = 0.56; this.ballSprite.setScale(ballScale) this.ballSprite.setCircle(150 * ballScale) this.ballSprite.setMass(1) this.ballSprite.setBounce(bounceFactor,bounceFactor) this.ballSprite.setIgnoreGravity(true) //console.log(this.ballSprite) //this.matter.add.circle(50, 500, 10) // this.ballSprite.setCollisionCategory(catBalls) this.ballSprite.setCollidesWith([catWalls, catFloor, catBalls, catChars]); // place camera initialliy this.cameraAnchor = this.matter.add.image(400, 0, 'ball') this.cameraAnchor.setVisible(false) this.matter.scene.cameras.main.startFollow(this.cameraAnchor, true, 0.99, 0.99) //player2? this.matter.scene.cameras.main.stopFollow(this.cameraAnchor, true, 0.99, 0.99) this.input.keyboard.on("keydown_F", () => { console.log(this.character.getBounds(), this.matter.world) console.log(this.matter.scene.cameras.main) }) this.input.keyboard.on("keydown_SPACE", () => { // Jump if (!this.gameStarted) { this.matter.scene.cameras.main.startFollow(this.cameraAnchor, true, 0.99, 0.99) //player2? this.matter.world.setBounds(0, 0, 800, gameHeight) this.startGame() } }) this.input.keyboard.on("keydown_UP", () => { // Jump if (gameRunning && this.character.canJump > 0) { //this.character.applyForce({x: 0, y: -0.8}) this.character.setVelocityY(-10) // TODO maybe second jump less high //this.character.setVelocityY(-5 * this.character.canJump) this.character.canJump -= 1; this.character.setFrame(1) } }) this.input.keyboard.on("keydown_W", () => { console.log(this.character2.getBounds(), this.matter.world) console.log(this.matter.scene.cameras.main) if (gameRunning && this.character2.canJump > 0) { //this.character.applyForce({x: 0, y: -0.8}) this.character2.setVelocityY(-10) // TODO maybe second jump less high //this.character.setVelocityY(-5 * this.character.canJump) this.character2.canJump -= 1; this.character2.setFrame(1) } }) this.input.keyboard.on("keydown_R", () => { this.scene.restart("TestScene") console.log(this) }) this.input.keyboard.on("keydown_ESC", () => { this.infoScreen.setVisible(!this.infoScreenVisible) this.infoScreenVisible = !this.infoScreenVisible this.children.bringToTop(this.infoScreen) }) //Character 2 Keys: //this.input.keyboard.on("keydown_UP", () => { // this.character.setScale(2) //}) //this.input.keyboard.on("keydown_DOWN", () => { // this.character.setScale(1) //}) this.matter.world.on('collisionstart', (event, bodyA, bodyB) => { //console.log(event, bodyA, bodyB) }) this.matter.world.on('beforeUpdate', (event) => { //console.log(event) //console.log(event, bodyA, bodyB) }) //setup collision // why does this.gameOver() fail inside the collision-handler? const gameOver = this.gameOver.bind(this); this.matter.world.on('collisionstart', function (event, bodyA, bodyB) { //console.log(this.walls) // // if ((bodyA.collisionFilter.category === catWalls || bodyB.collisionFilter.category === catWalls) && (bodyA.collisionFilter.category === catChars || bodyB.collisionFilter.category === catChars)) { if(bodyA.collisionFilter.category == catChars){ bodyA.gameObject.canJump = 2 bodyA.gameObject.setVelocityY(Math.min(0, bodyA.velocity.y)) bodyA.gameObject.setFrame(0) } if(bodyB.collisionFilter.category == catChars){ bodyB.gameObject.canJump = 2 bodyB.gameObject.setVelocityY(Math.min(0, bodyB.velocity.y)) bodyB.gameObject.setFrame(0) } } if ((bodyA.collisionFilter.category === catChars || bodyB.collisionFilter.category === catChars) && (bodyA.collisionFilter.category === catBalls || bodyB.collisionFilter.category === catBalls)) { let character; let ball; if(bodyA.collisionFilter.category == catChars) { character = bodyA.gameObject; ball = bodyB.gameObject; } if(bodyB.collisionFilter.category == catChars){ character = bodyB.gameObject; ball = bodyA.gameObject; } //who had the last touch? ball.lastTouchedBy = character; } if ((bodyA.collisionFilter.category === catFloor || bodyB.collisionFilter.category === catFloor) && (bodyA.collisionFilter.category === catBalls || bodyB.collisionFilter.category === catBalls)) { console.log('collision', event, bodyA, bodyB) gameOver(); } }) this.infoScreen = this.matter.scene.add.image(400, -400, 'info') this.infoScreen.setVisible(false) this.infoScreenVisible = false //console.log(this.background) // this.add.text(270, -300, "ESC for infos", { fontSize: 32, stroke: 'black', strokeThickness: 15 }); } update() { const cam = this.matter.scene.cameras.main this.background.setPosition(400, cam._scrollY + viewHeight / 2) this.infoScreen.setPosition(400, cam._scrollY + viewHeight / 2) // TODO Ghandi set camera position let cameraYPosition = 0; this.cameraAnchor.setPosition(400, this.character.y) if (gameRunning) { score = Math.max(score, -this.ballSprite.y - 500) //scoreText.setText(score) //this.background. this.character.setAngle(0) this.character2.setAngle(0) this.character.setVelocityX(this.character.body.velocity.x * 0.9); this.character2.setVelocityX(this.character2.body.velocity.x * 0.9); //this.character.setFrame(1) if (this.cursors.left.isDown) { this.character.setVelocityX(-speed) this.character.setFlipX(true) //t//his.character.setFrame(0) } if (this.cursors.right.isDown) { this.character.setVelocityX(speed) this.character.setFlipX(false) //this.character.setFrame(2) } if (this.cursors.down.isDown) { if (this.character.body.velocity.y < speed) { this.character.setVelocityY(speed) } //this.character.setFlipX(false) //this.character.setFrame(2) } if (this.cursors.up.isDown) { } //character2 if (this.cursors2.left.isDown) { this.character2.setVelocityX(-speed) this.character2.setFlipX(true) //t//his.character.setFrame(0) } if (this.cursors2.right.isDown) { this.character2.setVelocityX(speed) this.character2.setFlipX(false) //this.character.setFrame(2) } if (this.cursors2.down.isDown) { if (this.character2.body.velocity.y < speed) { this.character2.setVelocityY(speed) } //this.character.setFlipX(false) //this.character.setFrame(2) } if (this.cursors2.up.isDown) { } this.clouds.forEach(cloud => { if (cloud.cloud.x > 800) { cloud.direction = -1 } if (cloud.cloud.x < 0) { cloud.direction = 1 } cloud.cloud.setVelocity(cloud.direction, 0) }) if (this.ballSprite.y > (this.character.y + 500) ) { this.gameOver(); } // Check and process map extension if needed const oldGameHeight = gameHeight const newGameHeight = -this.ballSprite.y + 1000 if (newGameHeight > gameHeight) { gameHeight = newGameHeight + 1000 this.createClouds(oldGameHeight, gameHeight) this.createWalls(oldGameHeight, gameHeight) this.children.bringToTop(this.character) this.children.bringToTop(this.ballSprite) this.matter.scene.cameras.main.setBounds(0, -gameHeight - 1000, 800, gameHeight + 1000 - 150 ) } } else { // Move gameover-text with camera scoreText.setPosition(180, cam._scrollY + viewHeight / 2 - 350) gameoverText.setPosition(400, cam._scrollY + viewHeight / 2) } } } export default TestScene <file_sep>= gameoff 2018 == concept <file_sep>import { Scene, GameObjects, Matter } from 'phaser'; //import blazerMan from '../assets/BackupBlazerstories/mainC.png'; //import ball from '../assets/BounceNBounce/powerups/02powup.png'; import sheetPNG from '../assets/dataJsonPNG.png'; import sheetJSON from '../assets/dataJsonPNG.json'; import shapes from '../assets/characters.json'; import style from '../style/default.css'; var score = 0; var scoreString = "Score: "; var scoreText; var gamePausedString = "GAME IS PAUSED"; var gamePaused; var gameIsPaused = 0; class TestScene extends Scene { constructor() { super({ key: "TestScene" }) } preload () { //this.load.image('blazerMan', blazerMan) //this.load.image('ball', ball) console.log('sheetPNG'); console.log(sheetPNG); console.log('sheetJSON'); console.log(sheetJSON); console.log('shapes'); console.log(shapes); this.load.atlas('sheet', sheetPNG, sheetJSON); //this.load.atlas('sheet', 'assets/fruit-sprites.png', 'assets/fruit-sprites.json'); //this.load.multiatlas('cityscene', 'assets/cityscene.json', 'assets'); this.load.json('shapes', shapes); //this.player.body. //this.load.image('circle', circle); } create () { const gameHeight = 1000; gamePaused = this.add.text(200, -100, gamePausedString); var shapes = this.cache.json.get('shapes'); //var shapes = this.cache.json.get('shapes'); this.matter.world.setBounds(0, 0, 800, gameHeight); //this.matter.world.setBounds(0, 0, game.config.width, game.config.height); this.add.image(0, 0, 'sheet', 'scene/gameBackground1').setOrigin(0, 0); //this.add.image(0, 0, 'sheet', 'background').setOrigin(0, 0); var mainC = this.matter.add.sprite(0, 0, 'sheet', 'characters/blazerMan', {shape: shapes.mainC}); //var ground = this.matter.add.sprite(0, 0, 'sheet', 'ground', {shape: shapes.ground}); mainC.setPosition(0 + mainC.centerOfMass.x, 100 + mainC.centerOfMass.y); // position (0,280) //ground.setPosition(0 + ground.centerOfMass.x, 280 + ground.centerOfMass.y); // position (0,280)$ var hello = 1; var ball = this.matter.add.sprite(100, 50, 'sheet1', 'powerups/powup02', {shape: shapes.powup02}); // var mainC = this.matter.add.sprite(0, 0, 'sheet', 'mainC', {shape: shapes.mainC}); //frame 2 ='scene/gameBackground1' , 'dataJsonPNG.png') //var background = this.add.sprite(0, 0, 'cityscene', 'background.png'); // this.add.image(29, 10, 'sheet','02powup',);//.setOrigin(200,-200); //'sheet' assets/BounceNBounce/powerups/ console.log('add image:'); console.log(this.matter.add.image(62, 62, 'sheet', 'powerups/powup01').setOrigin(100,100)); console.log('added image.'); //this.matter.add.sprite(200, 50, 'sheet', 'crate', {shape: shapes.crate}); var catChars = this.matter.world.nextCategory(); var catWalls = this.matter.world.nextCategory(); //this.add.image(0, 0, 'sheet', 'background').setOrigin(0, 0); this.cursors = this.input.keyboard.createCursorKeys() console.log(this.matter) const y = gameHeight - 100 // mainC = this.matter.add.image(50, y, 'blazerMan') // mainC. mainC.setCollisionCategory(catChars); this.matter.scene.cameras.main.startFollow(mainC) /* const walls = []; this.matter.add.image(200, y, 'blazerMan') for (let i = y + 50; i > 1000; i -= 80) { const left = this.matter.add.image(0, i, 'blazerMan') left.setCollisionCategory(catWalls); left.setStatic(true) const right = this.matter.add.image(800, i, 'blazerMan') right.setCollisionCategory(catWalls); right.setStatic(true) walls.push(right) } */ this.ballSprite = this.matter.add.sprite(100, y - 400, ball) const bounceFactor = .8 this.ballSprite.setBounce(bounceFactor,bounceFactor) console.log('this.ballSprite:') console.log(this.ballSprite) //this.matter.add.circle(50, 500, 10) .setMass(20) //console.log(mainC) this.input.keyboard.on("keydown_A", () => { //console.log(mainC.getBounds()) }) this.input.keyboard.on("keydown_SPACE", () => { mainC.applyForce({x: 0, y: -0.8}) }) this.input.keyboard.on("keydown_P", () => { //console.log(gameIsPaused); if (gameIsPaused == 0){ gameIsPaused = 1; } else { gameIsPaused = 0; } }) //this.input.keyboard.on("keydown_DOWN", () => { // mainC.setScale(1) //}) this.matter.world.on('collisionstart', (event, bodyA, bodyB) => { //console.log(event, bodyA, bodyB) }) this.matter.world.on('beforeUpdate', (event) => { //console.log(event) //console.log(event, bodyA, bodyB) }) //setup collision mainC.setCollidesWith([ catWalls, catChars ]); this.matter.world.on('collisionstart', function (event) { }) scoreText = this.add.text(32, 24, scoreString + score); scoreText.visible = true; } update() { if (gameIsPaused == 0){ gamePaused.visible = false; mainC.setVelocity(0,0); mainC.setMass(0); mainC.setAngle(0) if (this.cursors.left.isDown) { mainC.setVelocityX(-5) mainC.setFlipX(true) } if (this.cursors.right.isDown) { mainC.setVelocityX(5) mainC.setFlipX(false) } if (this.cursors.up.isDown) { } if (this.cursors.down.isDown) { } } if (gameIsPaused == 1) { gamePaused.visible = true; mainC.setMass(20); } } } export default TestScene <file_sep>//matter-scene.js
230e45635cf63bceaf8c181500771fc2b4d54b5b
[ "JavaScript", "AsciiDoc" ]
6
JavaScript
Lounge-Dev-Knights/gameoff-2018
ce658c0c1e33d3eac1ca5f1719ad94029514aefb
e391c982a5862ed9eff6096d22283cab2758f3fe
refs/heads/main
<repo_name>papermatter/papermatter-api<file_sep>/.env.example CLOUDINARY_NAME= CLOUDINARY_KEY= CLOUDINARY_SECRET= DATABASE_URL=<file_sep>/README.md # The Paper Matter API ## One-Click Heroku deploy <a href="https://www.heroku.com/deploy/?template=https://github.com/papermatter/papermatter-api"> <img src="https://assets.strapi.io/uploads/Deploy_button_heroku_b1043fc67d.png" /> </a>
4c64c7cd93884cf96ad3690dd08ad0d4b3522b2d
[ "Markdown", "Shell" ]
2
Shell
papermatter/papermatter-api
2cdf6b99b998a5e8b2eec2d2cb04fcdce6209b60
33319791773038c56a037ff2873a48723202f8e2
refs/heads/master
<repo_name>AjithPanneerselvam/Go-Journey<file_sep>/Routines/Writer/main.go package main import ( "fmt" "bytes" ) type Writer interface { Write([]byte) (int, error) } type Closer interface { Close() (error) } type WriterCloser interface { Writer Closer } type BufferedWriterCloser struct { buffer *bytes.Buffer } func(bwc *BufferedWriterCloser) Write(data []byte) (int, error){ n, err := bwc.buffer.Write(data) if err != nil { return 0, err } v := make([]byte, 8) for bwc.buffer.Len() > 8 { _, err := bwc.buffer.Read(data) if err != nil{ return 0, err } _, err = fmt.Println(string(v)) if(err != nil){ return 0, err } } return n, nil } func(bwc *BufferedWriterCloser) Close() (error){ for bwc.buffer.Len() > 0 { data := bwc.buffer.Next(8) _, err := fmt.Println(data) if err != nil { return err } } return nil } func NewBufferedWriterCloser() *BufferedWriterCloser{ return &BufferedWriterCloser{buffer: bytes.NewBuffer([]byte{})} } func main(){ var wc WriterCloser = NewBufferedWriterCloser() wc.Write([]byte("Hey there, I'm a SDE Intern in Qube Cinemas")) wc.Close() }<file_sep>/Interfaces/main.go package main import ( "fmt" "Interfaces/pkgExample" ) type artithmetic interface{ increment() decrement() } type customInt int; func(i *customInt) increment(){ *i = *i + 1 } func(i *customInt) decrement(){ *i = *i - 1 } func main(){ var i artithmetic; var value customInt = 2 i = &value i.increment() i.decrement() i.increment() i.increment() i.increment() fmt.Println(i) pkgExample.Hello() }<file_sep>/Channels/PingPong/main.go package main import ( "fmt" ) func Ping(ping chan<- string, message string){ ping<- message } func PingPong(ping <-chan string, pong chan<- string){ message := <-ping pong<- message } func main(){ ping := make(chan string, 1) pong := make(chan string, 1) Ping(ping, "Ping Pong") PingPong(ping, pong) fmt.Println(<-pong) }<file_sep>/IO/ChainingReaders/main.go package main import ( "fmt" "io.Reader" "strings" "os" ) type alphaReader struct{ reader io.Reader } func NewAlphaReader(reader io.Reader) *alphaReader{ return &(alphaReader{reader: reader}) } func alpha(char byte) byte{ if(char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z'){ return char } return 0 } func(a *alphaReader) Read(p []byte) (int, error){ n, err := a.reader.Read(p) if(err != nil){ return 0, err } buffer := new([]byte, 4) for i := 0; i < n; i++ { if char = alpha(p[i]); char != 0{ buffer[i] = char } } copy(buffer, p) return 0, nil } func main(){ reader := NewAlphaReader(strings.NewReader("Hey there, Hope you are doing great in your job!!")) p := make([]byte, 4) for{ n, err := reader.Read(p) if(err == io.EOF){ break } fmt.Println(p[:n]) } fmt.Println() }<file_sep>/IO/IOPipes/main.go /* Pipe writers and readers Types io.PipeWriter and io.PipeReader model IO operations as in memory pipes. Data is written to the pipe’s writer-end and is read on the pipe’s reader-end using separate go routines. The following creates the pipe reader/writer pair using the io.Pipe() which is then used to copy data from a buffer proverbs to io.Stdout */ package main import ( "os" "bytes" "io" ) func main(){ proverbs := new(bytes.Buffer) proverbs.WriteString("Channels orchestrate mutexes serialize\n") proverbs.WriteString("Cgo is not Go\n") proverbs.WriteString("Errors are values\n") proverbs.WriteString("Don't panic\n") piperR, piperW := io.Pipe() go func(){ defer piperW.Close() io.Copy(piperW, proverbs) }() io.Copy(os.Stdout, piperR) piperR.Close() }<file_sep>/Interfaces/structInterfaces.go package main import( "fmt" ) type employee struct{ id int name string role string } func (e *employee) displayInfo(){ fmt.Println("ID: ", e.id, "\nName: ", e.name, "\nRole: ", e.role) } func main(){ emp := &employee{id: 1, name: "Ajith", role: "SDE Intern"} emp.displayInfo() }<file_sep>/Channels/Boring/main.go package main import ( "fmt" "time" ) func boring(message string, ch chan<- int){ for i := 0; ; i++{ ch <- fmt.Sprintf("%s %d", message, i) time.Sleep(time.Duration(rand.Intn(1e3))) } } func main(){ var ch chan int ch = make(chan int) go boring("boring") for i := 1; i <= 5; i++{ fmt.Println("You say: ", <-ch) } fmt.Println("I'm leaving! You are so boring") }<file_sep>/Routines/TestTheWaters/Sample1/main.go package main import ( "fmt" "time" ) func working(message string){ fmt.Println(message) } func main() { go working("Working") fmt.Println("I'm listening") time.Sleep(2 * time.Second) fmt.Println("I'm done") }<file_sep>/Random/main.go package main import ("fmt") func work(){ for i := 1; i < 10; i++ { fmt.Println("Hey there") } } func main(){ go work() a := 5 if a == 5 { fmt.Println(a) } var val int fmt.Scanf("%d", &val) slices = make([]int, val) for i := 0; i < val; i++ { fmt.Println(slices[i]) } }<file_sep>/Arrays/main.go package main import "fmt" type sampleStruct struct { name string marks *[]int } func main() { sample := sampleStruct{"ajith", &([]int{1,2,3,4,5})} fmt.Printf("%T\n", (*sample.marks)) for i := 0; i < len(*sample.marks); i++ { fmt.Println((*sample.marks)[i]) } }<file_sep>/JSON/json.go package main type SystemSpec struct { OSName string `json:osName` Processor string `json:processor` }
0959ec2d3316d9c8b92485365c944542ec76d190
[ "Go" ]
11
Go
AjithPanneerselvam/Go-Journey
b4e2929dba17cb3fd5c9fa10e0594deaf269ca58
00ce537b26754ae92d14963f525d66a4c1e1d892
refs/heads/master
<file_sep>package construtores_de_classes; public class Aplicacao { public static void main(String[] args) { Retangulo r1 = new Retangulo(); double area1 = r1.calcularArea(); System.out.println(area1); Retangulo r2 = new Retangulo(5,7); double area2 = r2.calcularArea(); System.out.println(area2); Quadrado q = new Quadrado(5); double areaQuadrado = q.calcularQuadrado(); System.out.println(areaQuadrado); } } <file_sep>package classes_e_objetos; public class Aplicacao { public static void main(String[] args) { //criando objeto Pessoa p1 = new Pessoa(); Pessoa p2 = new Pessoa(); //acessando atributos e metodos p2.nome = "Maria"; p1.nome = "Josť"; p1.receberFigurinhas(5); p1.receberFigurinhas(7); p1.darFigurinhas(2, p2); p2.darFigurinhas(1, p1); System.out.println(p1.nome + " => " + p1.numerosDeFigurinhas); System.out.println(p2.nome + " => " + p2.numerosDeFigurinhas); } } <file_sep>package modificadores_de_acesso_private_e_public; public class Aplicacao { public static void main(String[] args) { ContaBancaria c = new ContaBancaria(); c.setNumConta(5432235); c.setAtiva(true); c.depositar(5000); c.sacar(2000); double saldo = c.getSaldo(); System.out.println(saldo); } } <file_sep>package funcionamento_da_passagem_de_parametros_para_metodos; public class Valor { int v; } <file_sep>package variaveis; public class VariaveisTipoVar { public static void main(String[] args) { int x = 10; var x2 = 20; //não pode trocar o tipo depois da inicialização boolean y = false; var y2 = true; //var z; errado tem que inicializar a variável } } <file_sep># Fundamentos Java * 1 -> Trabalhando com variáveis * 2 -> Trabalhando com o tipo var * 3 -> Casting de tipos primitivos * 4 -> Estruturas de controle if e switch * 5 -> Usando a estrutura switch expression * 6 -> Estruturas de controle while, do-while e for * 7 -> Criando classes e objetos * 8 -> Sobrecarga de métodos * 9 -> Funcionamento da passagem de parâmetros para métodos * 10 -> Modificadores de Acesso, Construtores e Elementos Estáticos <file_sep>package variaveis; public class Casting { public static void main(String[] args) { //alterar tipo de dados //long x = 10; //double x = 35; //float x = 40.0F; //float x = (float)40.0; //short x = (short)100000; erro //byte x = (byte)130; erro //System.out.println(x); } } <file_sep>package sobrecarga_de_metodos; public class Aplicacao { public static void main(String[] args) { Matematica m = new Matematica(); int soma = m.somar(10, 20,5); System.out.println(soma); double soma2 = m.somar(10.0, 20.0); System.out.println(soma2); int soma3 = m.somar(5, 5); System.out.println(soma3); double soma4 = m.somar(10.2, 8); System.out.println(soma4); } }
224d12553c7f42f05efb08ab577af3fa030cca0f
[ "Markdown", "Java" ]
8
Java
bertolo321/fundamentos_java
380a2e76da992f5e1a156202749dd943aae07d79
b37fa173317ed08f9181b5375364686653bcd559
refs/heads/master
<repo_name>Apostlerus/opensoft<file_sep>/tests/unit/shoppingCart.spec.js import { shallowMount, createLocalVue } from '@vue/test-utils'; import VueMaterial from 'vue-material'; import ShoppingCart from '@/components/ShoppingCart.vue'; describe('ShoppingCart', () => { describe('ShoppingCart.vue', () => { const localVue = createLocalVue(); localVue.use(VueMaterial); it('should render content correctly', () => { const wrapper = shallowMount(ShoppingCart, { localVue, mocks: { $store: { state: {}, getters: { items: [ { id: 1, planNumber: 1, price: 13, active: false, }, { id: 2, planNumber: 2, price: 22, active: false, }, { id: 3, planNumber: 3, price: 34, active: false, }, ], licenses: [1, 2, 3, 10, 100, 1000], }, dispatch: jest.fn(), }, }, }); expect(wrapper.vm.$el).toMatchSnapshot(); }); }); describe('CartItem.vue', () => { }); }); <file_sep>/src/store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import jsonItems from '../data/items.json'; import numberOfLicenses from '../data/numberOfLicenses.json'; Vue.use(Vuex); export default new Vuex.Store({ state: { shoppingCart: { items: [], numberOfLicenses: [], }, }, mutations: { updateItems(state, items) { state.shoppingCart.items = items; }, loadNumberOfLicenses(state, licenses) { state.shoppingCart.numberOfLicenses = licenses; }, }, actions: { updateItems({ commit }, items) { commit('updateItems', items); }, loadItems({ commit }) { const { items } = jsonItems; if (!items) { return; } commit('updateItems', items); }, loadNumberOfLicenses({ commit }) { const { licenses } = numberOfLicenses; commit('loadNumberOfLicenses', licenses); }, }, modules: { }, getters: { items: state => state.shoppingCart.items, licenses: state => state.shoppingCart.numberOfLicenses, }, });
af0aa0d5f9a4485b4b7e29faae00da2242def71d
[ "JavaScript" ]
2
JavaScript
Apostlerus/opensoft
0e2b22fbe72700230ac091f7b135d6cc6c72b744
221cf9e41a72912a71c026ede520df33cf02551b
refs/heads/master
<file_sep>library(gh) my_repos <- gh("GET /users/:username/repos", username = "chendaniely", per_page = 100, .limit = Inf) saveRDS(my_repos, "my_repos.RDS")
269bb081ff978a5f875c0dc78ab664e7d90e62b0
[ "R" ]
1
R
chendaniely/github_repo_explorer
2a348ca1753bc39c4d6687c50ef28a2c398b35f3
ac0558ae2976fff963b6c20530bfb0338de30812
refs/heads/master
<file_sep>#!/usr/bin/python2 # Filename :simpleclass.py class Person: pass p = Person() print p <file_sep>#!/usr/bin/python #Filename: for.py for i in range(1,10,2): print i else: print 'The for loop is over' <file_sep>#!/usr/bin/python2 # FileName : classInit.py class Person: count = 0 def __init__(self,name,c): self.name = name self.count = c self.__class__.count = self.__class__.count + 1 def sayHello(self): print ("hello,my name is",self.name) print(Person.count) p = Person("swaroop",4) p.sayHello() print(Person.count) print(p.count) p1 = Person("demo",8) print(p1.count) print(Person.count) print(p.count) <file_sep># Bezier - last updated for NodeBox 1.8.2 # Author: <NAME> <<EMAIL>> # Manual: http://nodebox.net/code/index.php/Bezier # Copyright (c) 2007 by <NAME>. # Refer to the "Use" section on http://nodebox.net/code # Thanks to Dr. Florimond De Smedt at the Free University of Brussels for the math routines. from DrawingPrimitives import PathElement, Point, MOVETO, LINETO, CURVETO, CLOSE def _linepoint(t, x0, y0, x1, y1): """Returns coordinates for point at t on the line. Calculates the coordinates of x and y for a point at t on a straight line. The t parameter is a number between 0.0 and 1.0, x0 and y0 define the starting point of the line, x1 and y1 the ending point of the line, """ xt = x0 + t * (x1-x0) yt = y0 + t * (y1-y0) p = PathElement() p.cmd = LINETO p.x = p.ctrl1.x = p.ctrl2.x = xt p.y = p.ctrl1.y = p.ctrl2.y = yt return p def _linelength(x0, y0, x1, y1): """Returns the length of the line. """ from math import sqrt, pow a = pow(abs(x0 - x1), 2) b = pow(abs(y0 - y1), 2) c = sqrt(a+b) return c def _curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3, handles=False): """Returns coordinates for point at t on the spline. Calculates the coordinates of x and y for a point at t on the cubic bezier spline, and its control points, based on the de Casteljau interpolation algorithm. The t parameter is a number between 0.0 and 1.0, x0 and y0 define the starting point of the spline, x1 and y1 its control point, x3 and y3 the ending point of the spline, x2 and y2 its control point. If the handles parameter is set, returns not only the point at t, but the modified control points of p0 and p3 should this point split the path as well. """ x01 = x0 * (1-t) + x1 * t y01 = y0 * (1-t) + y1 * t x12 = x1 * (1-t) + x2 * t y12 = y1 * (1-t) + y2 * t x23 = x2 * (1-t) + x3 * t y23 = y2 * (1-t) + y3 * t p = PathElement() p.cmd = CURVETO p.ctrl1.x = x01 * (1-t) + x12 * t p.ctrl1.y = y01 * (1-t) + y12 * t p.ctrl2.x = x12 * (1-t) + x23 * t p.ctrl2.y = y12 * (1-t) + y23 * t p.x = p.ctrl1.x * (1-t) + p.ctrl2.x * t p.y = p.ctrl1.y * (1-t) + p.ctrl2.y * t if handles == False: return p else: return (p, Point(x01,y01), Point(x23,y23)) def _curvelength(x0, y0, x1, y1, x2, y2, x3, y3, n=10): """Returns the length of the spline. Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3, by adding the lengths of lineair lines between points at t. The number of points is defined by n (n=10 would add the lengths of lines between 0.0 and 0.1, between 0.1 and 0.2, and so on). The default n=10 is fine for most cases, usually resulting in a deviation of less than 0.01. """ from math import sqrt, pow length = 0 xi = x0 yi = y0 for i in range(n): t = 1.0 * (i+1) / n p = _curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3) c = sqrt(pow(abs(xi-p.x),2) + pow(abs(yi-p.y),2)) length += c #_ctx.line(xi,yi,p.x,p.y) xi = p.x yi = p.y return length def _tuple(point): """Returns the given PathElement point as a tuple. Extracting all the values in a point is a recurring operation. Meanwhile, solves a bug in NodeBox 1.0rc3, where the control points are sometimes stored as tuples, and not as Point objects. """ from types import TupleType if type(point.ctrl1) == TupleType: ctrl1x, ctrl1y = point.ctrl1[0], point.ctrl1[1] ctrl2x, ctrl2y = point.ctrl2[0], point.ctrl2[1] else: ctrl1x = point.ctrl1.x ctrl1y = point.ctrl1.y ctrl2x = point.ctrl2.x ctrl2y = point.ctrl2.y x = point.x y = point.y return (x, y, ctrl1x, ctrl1y, ctrl2x, ctrl2y) def length(path, segmented=False, n=10): """Returns the length of the path. Calculates the length of each spline in the path, using n as a number of points to measure. When segmented is True, returns a list containing the individual length of each spline as values between 0.0 and 1.0, defining the percentual length of each spline in relation to the total path length. """ length = 0 segments = [] first = True for point in path: if first == True: closeto = Point(point.x, point.y) first = False elif point.cmd == MOVETO: closeto = Point(point.x, point.y) segments.append(0) elif point.cmd == CLOSE: c = _linelength(x0, y0, closeto.x, closeto.y) segments.append(c) elif point.cmd == LINETO: c = _linelength(x0, y0, point.x, point.y) segments.append(c) elif point.cmd == CURVETO: x3, y3, x1, y1, x2, y2 = _tuple(point) c = _curvelength(x0, y0, x1, y1, x2, y2, x3, y3, n) segments.append(c) x0 = point.x y0 = point.y for s in segments: length += s for i in range(len(segments)): try: segments[i] = 1.0 * segments[i] / length except ZeroDivisionError: pass if segmented == False: return length else: return segments def _locate(path, t, segments=None): """Locates t on a specific segment in the path. Returns (index, t, PathElement) A path is a combination of lines and curves (segments). The returned index indicates the start of the segment that contains point t. The returned t is the absolute time on that segment, in contrast to the relative t on the whole of the path. The returned point is the last MOVETO, any subsequent CLOSETO after i closes to that point. """ if segments == None: segments = length(path, segmented=True) for i in range(len(segments)): if i == 0 or path[i].cmd == MOVETO: closeto = Point(path[i].x, path[i].y) if t <= segments[i] or i == len(segments)-1: break else: t -= segments[i] try: t /= segments[i] except: pass if i == len(segments)-1 and segments[i] == 0: i -= 1 return (i, t, closeto) def point(path, t, segments=None): """Returns coordinates for point at t on the path. Gets the length of the path, based on the length of each curve and line in the path. Determines in what segment t falls. Gets the point on that segment. When you supply the list of segment lengths yourself, as returned from length(path, segmented=True), point() works about thirty times faster in a for-loop, since it doesn't need to recalculate the length during each iteration. """ if len(path) == 0: return None i, t, closeto = _locate(path, t, segments=segments) x0 = path[i].x y0 = path[i].y x3, y3, x1, y1, x2, y2 = _tuple(path[i+1]) if path[i+1].cmd == CLOSE: return _linepoint(t, x0, y0, closeto.x, closeto.y) if path[i+1].cmd == LINETO: return _linepoint(t, x0, y0, x3, y3) elif path[i+1].cmd == CURVETO: return _curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3) class _Contours: """A list of contours in a path. A specific contour in the list is drawn on the fly; this way, the graphics state can be edited before returning each contour (e.g. change of color, ...) """ def __init__(self, path): self.path = path self.contours = [] empty = True previous = 0 for i in range(len(self.path)): if path[i].cmd == MOVETO: if not empty: self.contours.append(previous) empty = True previous = i elif path[i].cmd == LINETO or path[i].cmd == CURVETO: empty = False def __getitem__(self, index): i = self.contours[index] _ctx.beginpath(self.path[i].x, self.path[i].y) for j in range(i+1, len(self.path)): if self.path[j].cmd == MOVETO: break elif self.path[j].cmd == LINETO: _ctx.lineto(self.path[j].x, self.path[j].y) elif self.path[j].cmd == CURVETO: _ctx.curveto(self.path[j].ctrl1.x, self.path[j].ctrl1.y, self.path[j].ctrl2.x, self.path[j].ctrl2.y, self.path[j].x, self.path[j].y) elif self.path[j].cmd == CLOSE: _ctx.closepath() return _ctx.endpath(draw=False) def __iter__(self): for i in range(len(self)): yield self[i] def __len__(self): return len(self.contours) def contours(path): """Returns a list of contours in the path. A contour is a sequence of lines and curves separated from the next contour by a MOVETO. For example, the glyph "o" has two contours: the inner circle and the outer circle. """ return _Contours(path) def findpath(points, curvature=1.0): """Constructs a path between the given list of points. Interpolates the list of points and determines a smooth bezier path betweem them. The curvature parameter offers some control on how separate segments are stitched together: from straight angles to smooth curves. Curvature is only useful if the path has more than three points. """ #The list of points consists of Point objects, #but it shouldn't crash on something straightforward #as someone supplying a list of (x,y)-tuples. from types import TupleType for i in range(len(points)): if type(points[i]) == TupleType: points[i] = Point(points[i][0], points[i][1]) if len(points) == 0: return None if len(points) == 1: _ctx.beginpath(points[0].x, points[0].y) return _ctx.endpath(draw=False) if len(points) == 2: _ctx.beginpath(points[0].x, points[0].y) _ctx.lineto(points[1].x, points[1].y) return _ctx.endpath(draw=False) #Zero curvature means straight lines. curvature = max(0, min(1, curvature)) if curvature == 0: _ctx.beginpath(points[0].x, points[0].y) for i in range(len(points)): _ctx.lineto(points[i].x, points[i].y) return _ctx.endpath(draw=False) curvature = 4 + (1.0-curvature)*40 dx = {0: 0, len(points)-1: 0} dy = {0: 0, len(points)-1: 0} bi = {1: -0.25} ax = {1: (points[2].x-points[0].x-dx[0]) / 4} ay = {1: (points[2].y-points[0].y-dy[0]) / 4} for i in range(2, len(points)-1): bi[i] = -1 / (curvature + bi[i-1]) ax[i] = -(points[i+1].x-points[i-1].x-ax[i-1]) * bi[i] ay[i] = -(points[i+1].y-points[i-1].y-ay[i-1]) * bi[i] r = range(1, len(points)-1) r.reverse() for i in r: dx[i] = ax[i] + dx[i+1] * bi[i] dy[i] = ay[i] + dy[i+1] * bi[i] _ctx.beginpath(points[0].x, points[0].y) for i in range(len(points)-1): _ctx.curveto(points[i].x + dx[i], points[i].y + dy[i], points[i+1].x - dx[i+1], points[i+1].y - dy[i+1], points[i+1].x, points[i+1].y) return _ctx.endpath(draw=False) def split(path, t): """Returns a path copy with an extra point at t. """ i, t, closeto = _locate(path, t) x0 = path[i].x y0 = path[i].y x3, y3, x1, y1, x2, y2 = _tuple(path[i+1]) if path[i+1].cmd == CLOSE: point = _linepoint(t, x0, y0, closeto.x, closeto.y) if path[i+1].cmd == LINETO: point = _linepoint(t, x0, y0, x3, y3) if path[i+1].cmd == CURVETO: point, ctrl1, ctrl2 = _curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3, handles=True) _ctx.beginpath(path[0].x, path[0].y) for j in range(1, len(path)): if j == i+1: if point.cmd == CURVETO: _ctx.curveto(ctrl1.x, ctrl1.y, point.ctrl1.x, point.ctrl1.y, point.x, point.y) _ctx.curveto(point.ctrl2.x, point.ctrl2.y, ctrl2.x, ctrl2.y, path[j].x, path[j].y) #_ctx.line(point.ctrl1.x, point.ctrl1.y, point.x, point.y) #_ctx.line(point.ctrl2.x, point.ctrl2.y, point.x, point.y) #_ctx.oval(point.x-2, point.y-2, 4, 4) elif point.cmd == LINETO: _ctx.lineto(point.x, point.y) if path[j].cmd != CLOSE: _ctx.lineto(path[j].x, path[j].y) else: _ctx.closepath() else: if path[j].cmd == MOVETO: _ctx.moveto(path[j].x, path[j].y) if path[j].cmd == LINETO: _ctx.lineto(path[j].x, path[j].y) if path[j].cmd == CURVETO: _ctx.curveto(path[j].ctrl1.x, path[j].ctrl1.y, path[j].ctrl2.x, path[j].ctrl2.y, path[j].x, path[j].y) if path[j].cmd == CLOSE: _ctx.closepath() p = _ctx.endpath(draw=False) return p<file_sep>#!/usr/bin/env python2 # FileName : tryExcept.py import sys try: s = raw_input("Enter something -->") except EOFError: print '\nwhy did you do an EOF on me ?' sys.exit() except: print"\n some error/exception occurred" finally: print "system exit" sys.exit() print "Done" <file_sep>#!/usr/bin/python ''' Created on 2011/11/17 @author: saltwater ''' # -*- coding: utf-8 -*- import numpy as np def func(x): A = np.matrix([[1.0,0.0],[0.0,1.0]]) b = np.matrix([[4.0],[4.0]]) c = np.matrix([[8.0]]) return -x.transpose()*A*x + b.transpose()*x - c def nabrafunc(x): b = np.matrix([[4.0],[4.0]]) return -2.0*x + b def Func(x,t): return x + t*nabrafunc(x) def dFunc(x,x0): return nabrafunc(x).transpose()*nabrafunc(x0) def search(x0,t): T = 0.0 Td = 0.0 h = 0.0001 eps = 1e-10 x = Func(x0,t) xd = Func(x0,t) while(float(np.abs(dFunc(x,x0))[[0]]) > eps): h = np.sign(float(dFunc(x,x0)[[0]]))*np.abs(h) T = t Td = t + h x = Func(x0,T) xd = Func(x0,Td) if(float(func(x)[[0]]) < float(func(xd)[[0]])): while(float(func(x)[[0]]) < float(func(xd)[[0]])): h = 2.0 * h T = Td Td = T + h x = Func(x0,T) xd = Func(x0,Td) t = T h = h/2.0 else: while(float(func(x)[[0]]) > float(func(xd)[[0]])): h = h/2.0 Td = Td - h x = Func(x0,T) xd = Func(x0,Td) t = Td h = 2.0*h print "t:" print t return t def hillCliming(x): t = 1.0 delta = 10e-5 dx = t*nabrafunc(x) while(np.sqrt(float((dx.transpose()*dx)[[0]])) > delta): t = search(x,t) dx = t*nabrafunc(x) x = x + dx return x X = np.matrix([[4.0],[4.0]]) Xr = hillCliming(X) print "\nresult:" print Xr<file_sep>import codecs import base64 f = codecs.open("../data/base64.txt", "r", "utf-8") str=f.read() print(str) print(base64.encodestring(str)) f.close() <file_sep>#!/usr/bin/env python ''' Created on 2011/11/29 @author: saltwater ''' #-*- coding: utf-8 -*- import win32process as process import win32gui as gui from ctypes import * print windll.kernel32 print cdll.msvcrt <file_sep>pysrc ===== python source <file_sep>#!/usr/bin/env python2 # FileName : listComprehension.py listone = [2,3,4] listtwo = [2*i for i in listone if i>2] print listtwo <file_sep>''' Created on Dec 2, 2010 @author: liujk ''' def info(object,spacing = 10,collapse = 1): """Print method and doc Strings. Takes module,class,list,dictionary,or String.""" methodList = [method for method in dir(object) if callable(getattr(object,method))] processFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s) print "\n".join(["%s %s"% (method.ljust(spacing), processFunc(str(getattr(object,method).__doc__))) for method in methodList]) if __name__ == "__main__": print info.__doc__ <file_sep>#!/usr/bin/python #Filename: func_default.py def say(message,times=2): print message * times say('hello,') say('world,',3) <file_sep>#!/usr/bin/python #Filename: if.py time = 5 number = 23 while True: guess = int(raw_input('Enter an integer:')) if time == 0: print("you lose the game") exit() else: if guess == number: print 'Congratulations,you guessed it.' #New block starts here print "(but you do not win any prizes!)" #New block ends here exit() elif guess < number: print 'No, it is a little higher than that' #Another block #You can do whatever you want in a block... else: print 'No it is a little lower than that' #you must have guess > number to reach here time = time-1 #print 'Done' # This last statement is always executed, after the if statement is executed <file_sep>#!/usr/bin/python2 # FileName : method.py class Person: def sayHello(self): print("hello,") p = Person() p.sayHello() <file_sep>#!/usr/bin/env python ''' Created on 2011/11/10 @author: saltwater ''' #xOld = 0 #xNew = 6 # The algorithm starts at x=6 #eps = 0.01 # step size #precision = 0.00001 # #def f_prime(x): # return 4 * x**3 - 9 * x**2 # #while abs(xNew - xOld) > precision: # xOld = xNew # xNew = xOld - eps * f_prime(xNew) # print("Local minimum occurs at ", xNew) #from matplotlib.matlab import * #x = linspace(-4, 4, 200) #f1 = power(10, x) #f2 = power(e, x) #f3 = power(2, x) #plot(x, f1, 'r', x, f2, 'b', x, f3, 'g', linewidth=2) #axis([-4, 4, -0.5, 8]) #text(1, 7.5, r'$10^x$', fontsize=16) #text(2.2, 7.5, r'$e^x$', fontsize=16) #text(3.2, 7.5, r'$2^x$', fonsize=16) #title('A simple example', fontsize=16) #savefig('power.png', dpi=75) #show() #import numpy, scipy, pylab, random #pylab.ylim([0,1000]) # #xs = [] #rawsignal = [] #with open("test.dat", 'r') as f: # for line in f: # if line[0] != '#' and len(line) > 0: # xs.append( int( line.split()[0] ) ) # rawsignal.append( int( line.split()[1] ) ) # #h, w = 3, 1 #pylab.figure(figsize=(12,9)) #pylab.subplots_adjust(hspace=.7) # #pylab.subplot(h,w,1) #pylab.title("Signal") #pylab.plot(xs,rawsignal) # #pylab.subplot(h,w,2) #pylab.title("FFT") #fft = scipy.fft(rawsignal) ##~ pylab.axis([None,None,0,1000]) #pylab.ylim([0,1000]) #pylab.plot(abs(fft)) # #pylab.savefig("SIG.png",dpi=200) #pylab.show() while True: x=float(raw_input('enter a number')) n=0 a=1 b=1 y=0 while n<10: n=n+1 while b<=2*n-1: a=a*b b=b+1 s=1.0*((-1)**(n+1))*(x**(2*n-1))/a y=y+s print y
13c82daebac8b4423a0c55f673a80e2588322341
[ "Markdown", "Python" ]
15
Python
saltwater/pysrc
61c9ff78c15f85bbcebbc49680c41f3aea8b0625
06a4bee122a318b32346db70bd3b520005918f43
refs/heads/master
<repo_name>capotej/central_logger<file_sep>/lib/central_logger.rb $:.unshift File.dirname(__FILE__) require 'mongo' require 'central_logger/mongo_logger' require 'central_logger/filter' require 'central_logger/initializer' require 'railtie' <file_sep>/test/test_helper.rb require 'test/unit' require 'shoulda' require 'mocha' # mock rails class require 'pathname' require 'rails' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) Shoulda.autoload_macros("#{File.dirname(__FILE__)}/..") class Test::Unit::TestCase def log(msg) @central_logger.mongoize({"id" => 1}) do @central_logger.debug(msg) end end def log_exception(msg) @central_logger.mongoize({"id" => 1}) do raise msg end end def log_metadata(options) @central_logger.mongoize({"id" => 1}) do @central_logger.add_metadata(options) end end def require_bogus_active_record require 'active_record' end def common_setup @con = @central_logger.mongo_connection @collection = @con[@central_logger.mongo_collection_name] end end
e81b043a87e3f4b8a3f483c3780c0caa6cd71249
[ "Ruby" ]
2
Ruby
capotej/central_logger
66e094041e6f2f279f425d65712cb8f334e9bdcd
6c4e13dd3b1df674c6ee131159a11242a186ccb8
refs/heads/master
<file_sep>using System; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Wraps a given <see cref="IRepository{T, TId}"/> and handles any exceptions of the specified type. /// </summary> public class RepositoryExceptionHandler<T, TId, TException> : QueryServiceExceptionHandler<T, TId, TException>, IRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> where TException : Exception { /// <summary> /// Initializes a new instance of the <see cref="RepositoryExceptionHandler{T, TId, TException}"/> class, /// decorating the given <see cref="IRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IRepository{T, TId}"/> to be decorated.</param> /// <param name="handler">The handler that will be called when an exception is caught.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="handler"/> is <c>null</c>.</exception> public RepositoryExceptionHandler(IRepository<T, TId> inner, Action<TException> handler) : base(inner, handler) { Inner = inner; } /// <summary> /// Gets a reference to the <see cref="IRepository{T, TId}"/> being decorated. /// </summary> public new IRepository<T, TId> Inner { get; } /// <inheritdoc/> public void Add(T item) { try { Inner.Add(item); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public void AddOrUpdate(T item) { try { Inner.AddOrUpdate(item); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public void Update(T item) { try { Inner.Update(item); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public void Remove(T item) { try { Inner.Remove(item); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public void Remove(TId id) { try { Inner.Remove(id); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public bool TryAdd(T item) { try { return Inner.TryAdd(item); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public bool TryUpdate(T item) { try { return Inner.TryUpdate(item); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public bool TryRemove(T item) { try { return Inner.TryRemove(item); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public bool TryRemove(TId id) { try { return Inner.TryRemove(id); } catch (TException ex) { Handler.Invoke(ex); return false; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Wraps a given <see cref="IAsyncQueryService{T, TId}"/> and handles any exceptions of the specified type. /// </summary> /// <typeparam name="T">The type of entities in the data store.</typeparam> /// <typeparam name="TId">The type of the unique identity value of the entities in the data store.</typeparam> /// <typeparam name="TException">"The type of exception to be handled.</typeparam> public class AsyncQueryServiceExceptionHandler<T, TId, TException> : AsyncQueryServiceDecorator<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> where TException : Exception { /// <summary> /// Initializes a new instance of the <see cref="AsyncQueryServiceExceptionHandler{T, TId, TException}"/> class, /// decorating the given <see cref="IAsyncQueryService{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncQueryService{T, TId}"/> to be decorated.</param> /// <param name="handler">The handler that will be called when an exception is caught.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="handler"/> is <c>null</c>.</exception> public AsyncQueryServiceExceptionHandler(IAsyncQueryService<T, TId> inner, Action<TException> handler) : base(inner) { Handler = handler ?? throw new ArgumentNullException(nameof(handler)); } /// <summary> /// Gets a reference to the handler that will be called when an exception is caught. /// </summary> protected Action<TException> Handler { get; } /// <inheritdoc/> public override async Task<long> GetCountAsync() { try { return await Inner.GetCountAsync().ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return 0; } } /// <inheritdoc/> public override async Task<IEnumerable<T>> GetAllAsync() { try { return await Inner.GetAllAsync().ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return Enumerable.Empty<T>(); } } /// <inheritdoc/> public override async Task<T> GetByIdAsync(TId id) { try { return await Inner.GetByIdAsync(id).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return default(T); } } /// <inheritdoc/> public override async Task<T> TryGetByIdAsync(TId id) { try { return await Inner.TryGetByIdAsync(id).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return default(T); } } } } <file_sep>using System; using OnionSeed.Extensions; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IAsyncUnitOfWork"/> to work like an <see cref="IUnitOfWork"/>. /// </summary> public class SyncUnitOfWorkAdapter : AsyncUnitOfWorkDecorator, IUnitOfWork { /// <summary> /// Initializes a new instance of the <see cref="SyncUnitOfWorkAdapter"/> class, /// wrapping the given <see cref="IAsyncUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncUnitOfWork"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public SyncUnitOfWorkAdapter(IAsyncUnitOfWork inner) : base(inner) { } /// <inheritdoc/> public void Commit() => AsyncExtensions.RunSynchronously(() => Inner.CommitAsync()); } } <file_sep>using System; using System.Threading.Tasks; using OnionSeed.Extensions; using OnionSeed.Types; namespace OnionSeed.Factories { /// <inheritdoc/> /// <summary> /// A factory that can construct new entity instances and populate them with new unique identity values. /// </summary> /// <typeparam name="T">The type of entities created by the factory.</typeparam> /// <typeparam name="TId">The type of the unique identity values.</typeparam> public class EntityFactory<T, TId> : IFactory<T>, IAsyncFactory<T> where T : IWritableEntity<TId>, new() where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given abstract factory class. /// </summary> /// <param name="keyGenerator">The factory that will be used to synchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="keyGenerator"/> is <b>null</b>.</exception> /// <remarks>Only use this constructor if the factory will only be used synchronously.</remarks> public EntityFactory(IFactory<TId> keyGenerator) : this(() => keyGenerator.CreateNew()) { if (keyGenerator == null) throw new ArgumentNullException(nameof(keyGenerator)); } /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given abstract factory class. /// </summary> /// <param name="asyncKeyGenerator">The factory that will be used to asynchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="asyncKeyGenerator"/> is <b>null</b>.</exception> /// <remarks>Only use this constructor if the factory will only be used asynchronously.</remarks> public EntityFactory(IAsyncFactory<TId> asyncKeyGenerator) : this(() => asyncKeyGenerator.CreateNewAsync()) { if (asyncKeyGenerator == null) throw new ArgumentNullException(nameof(asyncKeyGenerator)); } /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given abstract factory classes. /// </summary> /// <param name="keyGenerator">The factory that will be used to synchronously generate unique identity values.</param> /// <param name="asyncKeyGenerator">The factory that will be used to asynchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="keyGenerator"/> is <b>null</b>. /// -or- <paramref name="asyncKeyGenerator"/> is <c>null</c>.</exception> /// <remarks>Only use this constructor if the factory will only be used asynchronously.</remarks> public EntityFactory(IFactory<TId> keyGenerator, IAsyncFactory<TId> asyncKeyGenerator) : this(() => keyGenerator.CreateNew(), () => asyncKeyGenerator.CreateNewAsync()) { if (keyGenerator == null) throw new ArgumentNullException(nameof(keyGenerator)); if (asyncKeyGenerator == null) throw new ArgumentNullException(nameof(asyncKeyGenerator)); } /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given factory method. /// </summary> /// <param name="keyGenerator">The factory method that will be used to synchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="keyGenerator"/> is <b>null</b>.</exception> /// <remarks>Only use this constructor if the factory will only be used synchronously.</remarks> public EntityFactory(Func<TId> keyGenerator) : this(keyGenerator, () => Task.Run(keyGenerator)) { } /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given factory method. /// </summary> /// <param name="asyncKeyGenerator">The factory method that will be used to asynchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="asyncKeyGenerator"/> is <b>null</b>.</exception> /// <remarks>Only use this constructor if the factory will only be used asynchronously.</remarks> public EntityFactory(Func<Task<TId>> asyncKeyGenerator) : this(() => asyncKeyGenerator.RunSynchronously(), asyncKeyGenerator) { } /// <summary> /// Initializes a new instance of the <see cref="EntityFactory{T,TId}"/> class, /// which will generate keys using the given factory methods. /// </summary> /// <param name="keyGenerator">The factory method that will be used to synchronously generate unique identity values.</param> /// <param name="asyncKeyGenerator">The factory method that will be used to asynchronously generate unique identity values.</param> /// <exception cref="ArgumentNullException"><paramref name="keyGenerator"/> is <b>null</b>. /// -or- <paramref name="asyncKeyGenerator"/> is <c>null</c>.</exception> public EntityFactory(Func<TId> keyGenerator, Func<Task<TId>> asyncKeyGenerator) { KeyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator)); AsyncKeyGenerator = asyncKeyGenerator ?? throw new ArgumentNullException(nameof(asyncKeyGenerator)); } /// <summary> /// Gets the factory method that will be used to generate unique identity values. /// </summary> protected Func<TId> KeyGenerator { get; } /// <summary> /// Gets the asynchronous factory method that will be used to generate unique identity values. /// </summary> protected Func<Task<TId>> AsyncKeyGenerator { get; } /// <inheritdoc /> public virtual T CreateNew() { var id = KeyGenerator.Invoke(); return new T { Id = id }; } /// <inheritdoc /> public virtual async Task<T> CreateNewAsync() { var id = await AsyncKeyGenerator.Invoke().ConfigureAwait(false); return new T { Id = id }; } } } <file_sep>using System; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Wraps a given <see cref="IUnitOfWork"/> and handles any exceptions of the specified type. /// </summary> /// <typeparam name="TException">"The type of exception to be handled.</typeparam> public class UnitOfWorkExceptionHandler<TException> : UnitOfWorkDecorator where TException : Exception { /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionHandler{TException}"/> class, /// decorating the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be decorated.</param> /// <param name="handler">The handler that will be called when an exception is caught.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="handler"/> is <c>null</c>.</exception> public UnitOfWorkExceptionHandler(IUnitOfWork inner, Action<TException> handler) : base(inner) { Handler = handler ?? throw new ArgumentNullException(nameof(handler)); } /// <summary> /// Gets a reference to the handler that will be called when an exception is caught. /// </summary> protected Action<TException> Handler { get; } /// <inheritdoc/> public override void Commit() { try { Inner.Commit(); } catch (TException ex) { Handler.Invoke(ex); } } } } <file_sep>using System; using Microsoft.Extensions.Logging; using OnionSeed.Extensions; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Wraps a given <see cref="IUnitOfWork"/> and logs any exceptions of the specified type. /// </summary> public class UnitOfWorkExceptionLogger<TException> : UnitOfWorkExceptionHandler<TException> where TException : Exception { /// <summary> /// The default severity of exceptions. /// </summary> public const LogLevel DefaultLogLevel = LogLevel.Error; /// <summary> /// The default event ID. /// </summary> public static readonly EventId DefaultEventId = 0; /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// decorating the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be decorated.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger) : this(inner, logger, null) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="message">A format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, string message, params object[] args) : this(inner, logger, DefaultLogLevel, message, args) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="logLevel">The severity of the exception.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, LogLevel logLevel) : this(inner, logger, logLevel, null) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="logLevel">The severity of the exception.</param> /// <param name="message">A format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, LogLevel logLevel, string message, params object[] args) : this(inner, logger, logLevel, DefaultEventId, message, args) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="eventId">The id of the event.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, EventId eventId) : this(inner, logger, eventId, null) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="eventId">The id of the event.</param> /// <param name="message">A format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, EventId eventId, string message, params object[] args) : this(inner, logger, DefaultLogLevel, eventId, message, args) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="logLevel">The severity of the exception.</param> /// <param name="eventId">The id of the event.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, LogLevel logLevel, EventId eventId) : this(inner, logger, logLevel, eventId, null) { } /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkExceptionLogger{TException}"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <param name="logger">The logger where caught exceptions will be written.</param> /// <param name="logLevel">The severity of the exception.</param> /// <param name="eventId">The id of the event.</param> /// <param name="message">A format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="logger"/> is <c>null</c>.</exception> public UnitOfWorkExceptionLogger( IUnitOfWork inner, ILogger logger, LogLevel logLevel, EventId eventId, string message, params object[] args) : base(inner, ex => logger.Log(logLevel, eventId, ex, message ?? string.Empty, args)) { if (logger == null) throw new ArgumentNullException(nameof(logger)); } } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IAsyncQueryService{T, TId}"/>. /// </summary> public abstract class AsyncQueryServiceDecorator<T, TId> : IAsyncQueryService<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="AsyncQueryServiceDecorator{T, TId}"/> class, /// decorating the given <see cref="IAsyncQueryService{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncQueryService{T, TId}"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncQueryServiceDecorator(IAsyncQueryService<T, TId> inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IAsyncQueryService{T, TId}"/> being decorated. /// </summary> protected IAsyncQueryService<T, TId> Inner { get; } /// <inheritdoc/> public virtual Task<long> GetCountAsync() => Inner.GetCountAsync(); /// <inheritdoc/> public virtual Task<IEnumerable<T>> GetAllAsync() => Inner.GetAllAsync(); /// <inheritdoc/> public virtual Task<T> GetByIdAsync(TId id) => Inner.GetByIdAsync(id); /// <inheritdoc/> public virtual Task<T> TryGetByIdAsync(TId id) => Inner.TryGetByIdAsync(id); } } <file_sep>using System; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class UnitOfWorkTapTests { private readonly Mock<IUnitOfWork> _mockMain = new Mock<IUnitOfWork>(MockBehavior.Strict); private readonly Mock<IUnitOfWork> _mockTap = new Mock<IUnitOfWork>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeMain, bool includeTap) { // Arrange var main = includeMain ? _mockMain.Object : null; var tap = includeTap ? _mockTap.Object : null; // Act Action action = () => new UnitOfWorkTap(main, tap); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Commit_ShouldSkipTap_WhenMainThrowsException() { // Arrange _mockMain .Setup(r => r.Commit()) .Throws(new InvalidOperationException()); var subject = new UnitOfWorkTap(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.Commit(); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Commit_ShouldCallMain_AndTap() { // Arrange _mockMain.Setup(r => r.Commit()); _mockTap.Setup(r => r.Commit()); var subject = new UnitOfWorkTap(_mockMain.Object, _mockTap.Object); // Act subject.Commit(); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } } } <file_sep>using System; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Decorates an <see cref="IRepository{T, TId}"/>, /// mirroring commands to a secondary, "tap" <see cref="IRepository{T, TId}"/>. /// </summary> /// <remarks>This decorator functions like a network tap: commands are executed first against the /// inner repository; if they succeed, they are then executed against the tap repository as well. /// Queries are only executed against the inner repository, and anything returned from the tap repository is ignored. /// <para>This essentially allows for the creation of a duplicate copy of the data, /// and is intended to be used for things like caching, backup, or reporting.</para></remarks> public class RepositoryTap<T, TId> : RepositoryDecorator<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="RepositoryTap{T,TKey}"/> class, /// using the given repositories. /// </summary> /// <param name="inner">The <see cref="IRepository{T, TId}"/> to be decorated.</param> /// <param name="tap">The tap repository, where commands will be mirrored.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="tap"/> is <c>null</c>.</exception> public RepositoryTap(IRepository<T, TId> inner, IRepository<T, TId> tap) : base(inner) { Tap = tap ?? throw new ArgumentNullException(nameof(tap)); } /// <summary> /// Gets a reference to the tap repository. /// </summary> public IRepository<T, TId> Tap { get; } /// <inheritdoc/> public override void Add(T item) { Inner.Add(item); Tap.AddOrUpdate(item); } /// <inheritdoc/> public override void AddOrUpdate(T item) { Inner.AddOrUpdate(item); Tap.AddOrUpdate(item); } /// <inheritdoc/> public override void Update(T item) { Inner.Update(item); Tap.AddOrUpdate(item); } /// <inheritdoc/> public override void Remove(T item) { Inner.Remove(item); Tap.Remove(item); } /// <inheritdoc/> public override void Remove(TId id) { Inner.Remove(id); Tap.Remove(id); } /// <inheritdoc/> public override bool TryAdd(T item) { var success = Inner.TryAdd(item); if (success) Tap.AddOrUpdate(item); return success; } /// <inheritdoc/> public override bool TryUpdate(T item) { var success = Inner.TryUpdate(item); if (success) Tap.AddOrUpdate(item); return success; } /// <inheritdoc/> public override bool TryRemove(T item) { var success = Inner.TryRemove(item); Tap.Remove(item); return success; } /// <inheritdoc/> public override bool TryRemove(TId id) { var success = Inner.TryRemove(id); Tap.Remove(id); return success; } } } <file_sep>using System; using System.Collections.Generic; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc /> /// <summary> /// Defines a mechanism that can be used to store entities in a data store /// and query them back out again. /// </summary> public interface IRepository<T, in TId> : IQueryService<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Adds an entity to the data store. /// </summary> /// <param name="item">The entity to be added to the data store.</param> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> was not assigned a unique identity value.</exception> /// <exception cref="ArgumentException">The data store already contains an entity with a matching unique identity value.</exception> void Add(T item); /// <summary> /// Adds an entity to the data store, or updates it if it already exists in the data store. /// </summary> /// <param name="item">The entity to be added to or updated in the data store.</param> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> was not assigned a unique identity value.</exception> void AddOrUpdate(T item); /// <summary> /// Updates the specified entity in the data store. /// </summary> /// <param name="item">The entity to be updated in the data store.</param> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> has a <c>null</c> unique identity value.</exception> /// <exception cref="KeyNotFoundException">The specified entity was not found in the data store.</exception> void Update(T item); /// <summary> /// Removes the given entity from the data store. /// </summary> /// <param name="item">The entity to be removed from the data store.</param> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> has a <c>null</c> unique identity value.</exception> /// <remarks>If the given entity is not found in the data store, this method is a no-op.</remarks> void Remove(T item); /// <summary> /// Removes the specified entity from the data store. /// </summary> /// <param name="id">The unique identity value of the entity to be removed from the data store.</param> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception> /// <remarks>If the specified entity is not found in the data store, this method is a no-op.</remarks> void Remove(TId id); /// <summary> /// Attempts to add an entity to the data store. /// </summary> /// <param name="item">The entity to be added to the data store.</param> /// <returns><c>true</c> if the entity was added successfully; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> has a <c>null</c> unique identity value.</exception> bool TryAdd(T item); /// <summary> /// Attempts to update the specified entity in the data store. /// </summary> /// <param name="item">The entity to be updated in the data store.</param> /// <returns><c>true</c> if the entity was updated successfully; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> has a <c>null</c> unique identity value.</exception> bool TryUpdate(T item); /// <summary> /// Attempts to remove the given entity from the data store. /// </summary> /// <param name="item">The entity to be removed from the data store.</param> /// <returns><c>true</c> if the entity was removed successfully, or <c>false</c> if it was not found.</returns> /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>. /// -or- <paramref name="item"/> has a <c>null</c> unique identity value.</exception> /// <remarks>If the given entity is not found in the data store, this method is a no-op.</remarks> bool TryRemove(T item); /// <summary> /// Attempts to remove the specified entity from the data store. /// </summary> /// <param name="id">The unique identity value of the entity to be removed from the data store.</param> /// <returns><c>true</c> if the entity was removed successfully, or <c>false</c> if it was not found.</returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception> /// <remarks>If the specified entity is not found in the data store, this method is a no-op.</remarks> bool TryRemove(TId id); } } <file_sep>using System; namespace OnionSeed.Types { /// <summary> /// Defines an object that is not fundamentally identified by its attributes, but rather by a unique identity value. /// </summary> /// <typeparam name="TId">The type of the unique identity value.</typeparam> /// <remarks>Entities are not defined primarily by their attributes. /// They represent a thread of identity that runs through time and often across distinct representations. /// Sometimes an entity must be matched with another entity even though their attributes differ. /// Sometimes an entity must be distinguished from other entities even though their attributes are the same. /// Mistaken identity in these cases can lead to data corruption; thus, a unique identity value is created /// for the entity so it can be tracked regardless of the state of its attributes.</remarks> public interface IEntity<out TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Gets the unique identity value. /// </summary> TId Id { get; } } } <file_sep>using System; using System.Collections.Generic; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class RepositoryTapTests { private readonly Mock<IRepository<FakeEntity<int>, int>> _mockMain = new Mock<IRepository<FakeEntity<int>, int>>(MockBehavior.Strict); private readonly Mock<IRepository<FakeEntity<int>, int>> _mockTap = new Mock<IRepository<FakeEntity<int>, int>>(MockBehavior.Strict); private readonly List<FakeEntity<int>> _data = new List<FakeEntity<int>> { new FakeEntity<int> { Id = 1, Name = "Bill" }, new FakeEntity<int> { Id = 2, Name = "Jane" }, new FakeEntity<int> { Id = 3, Name = "Jake" }, new FakeEntity<int> { Id = 4, Name = "Megan" } }; [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeMain, bool includeTap) { // Arrange var main = includeMain ? _mockMain.Object : null; var tap = includeTap ? _mockTap.Object : null; // Act Action action = () => new RepositoryTap<FakeEntity<int>, int>(main, tap); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void GetCount_ShouldCallMain_AndReturnResult() { // Arrange _mockMain .Setup(r => r.GetCount()) .Returns(_data.Count); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.GetCount(); // Assert result.Should().Be(_data.Count); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void GetAll_ShouldCallMain_AndReturnResult() { // Arrange _mockMain .Setup(r => r.GetAll()) .Returns(_data); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.GetAll(); // Assert result.Should().BeSameAs(_data); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void GetById_ShouldCallMain_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.GetById(person.Id)) .Returns(person); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.GetById(person.Id); // Assert result.Should().BeSameAs(person); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryGetById_ShouldCallMain_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryGetById(person.Id, out person)) .Returns(true); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var success = subject.TryGetById(person.Id, out FakeEntity<int> result); // Assert success.Should().BeTrue(); result.Should().BeSameAs(person); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Add_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.Add(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.Add(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Add_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain.Setup(r => r.Add(person)); _mockTap.Setup(r => r.AddOrUpdate(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act subject.Add(person); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void AddOrUpdate_ShouldSkipTap_WhenMainhrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.AddOrUpdate(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.AddOrUpdate(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void AddOrUpdate_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain.Setup(r => r.AddOrUpdate(person)); _mockTap.Setup(r => r.AddOrUpdate(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act subject.AddOrUpdate(person); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Update_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.Update(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.Update(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Update_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain.Setup(r => r.Update(person)); _mockTap.Setup(r => r.AddOrUpdate(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act subject.Update(person); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Remove_ShouldSkipTap_WhenEntityIsGiven_AndMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.Remove(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.Remove(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Remove_ShouldCallMain_AndTap_WhenEntityIsGiven() { // Arrange var person = _data[1]; _mockMain.Setup(r => r.Remove(person)); _mockTap.Setup(r => r.Remove(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act subject.Remove(person); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Remove_ShouldSkipTap_WhenIdIsGiven_AndMainThrowsException() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.Remove(id)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.Remove(id); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void Remove_ShouldCallMain_AndTap_WhenIdIsGiven() { // Arrange var id = _data[1].Id; _mockMain.Setup(r => r.Remove(id)); _mockTap.Setup(r => r.Remove(id)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act subject.Remove(id); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryAdd_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAdd(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.TryAdd(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryAdd_ShouldSkipTap_WhenMainReturnsFalse() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAdd(person)) .Returns(false); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryAdd(person); // Assert result.Should().BeFalse(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryAdd_ShouldCallMain_AndTap_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAdd(person)) .Returns(true); _mockTap.Setup(r => r.AddOrUpdate(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryAdd(person); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryUpdate_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdate(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.TryUpdate(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryUpdate_ShouldSkipTap_WhenMainReturnsFalse() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdate(person)) .Returns(false); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryUpdate(person); // Assert result.Should().BeFalse(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryUpdate_ShouldCallMain_AndTap_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdate(person)) .Returns(true); _mockTap.Setup(r => r.AddOrUpdate(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryUpdate(person); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemove_ShouldSkipTap_WhenEntityIsGiven_AndMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryRemove(person)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.TryRemove(person); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemove_ShouldCallMain_AndTap_AndReturnResult_WhenEntityIsGiven() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryRemove(person)) .Returns(true); _mockTap.Setup(r => r.Remove(person)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryRemove(person); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemove_ShouldSkipTap_WhenIdIsGiven_AndMainThrowsException() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.TryRemove(id)) .Throws(new InvalidOperationException()); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Action action = () => subject.TryRemove(id); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemove_ShouldCallMain_AndTap_AndReturnResult_WhenIdIsGiven() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.TryRemove(id)) .Returns(true); _mockTap.Setup(r => r.Remove(id)); var subject = new RepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = subject.TryRemove(id); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncUnitOfWorkAdapterTests { private readonly Mock<IUnitOfWork> _mockInner = new Mock<IUnitOfWork>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new AsyncUnitOfWorkAdapter(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public async Task CommitAsync_ShouldCallSyncMethod() { // Arrange _mockInner.Setup(i => i.Commit()); var subject = new AsyncUnitOfWorkAdapter(_mockInner.Object); // Act await subject.CommitAsync().ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } } } <file_sep>using System; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IRepository{T, TId}"/>. /// </summary> public abstract class RepositoryDecorator<T, TId> : QueryServiceDecorator<T, TId>, IRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="RepositoryDecorator{T, TId}"/> class, /// decorating the given <see cref="IRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IRepository{T, TId}"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public RepositoryDecorator(IRepository<T, TId> inner) : base(inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IRepository{T, TId}"/> being decorated. /// </summary> protected new IRepository<T, TId> Inner { get; } /// <inheritdoc/> public virtual void Add(T item) => Inner.Add(item); /// <inheritdoc/> public virtual void AddOrUpdate(T item) => Inner.AddOrUpdate(item); /// <inheritdoc/> public virtual void Update(T item) => Inner.Update(item); /// <inheritdoc/> public virtual void Remove(T item) => Inner.Remove(item); /// <inheritdoc/> public virtual void Remove(TId id) => Inner.Remove(id); /// <inheritdoc/> public virtual bool TryAdd(T item) => Inner.TryAdd(item); /// <inheritdoc/> public virtual bool TryUpdate(T item) => Inner.TryUpdate(item); /// <inheritdoc/> public virtual bool TryRemove(T item) => Inner.TryRemove(item); /// <inheritdoc/> public virtual bool TryRemove(TId id) => Inner.TryRemove(id); } } <file_sep>public static class Constants { public static class Build { public const string DefaultVersion = "1.0.0"; public static string Version = DefaultVersion; public static string Configuration = "Debug"; } public static class EnvironmentVariables { public const string GitPassword = "<PASSWORD>"; public const string GitUsername = "GIT_USERNAME"; public const string NuGetRootUri = "NUGET_ROOTURI"; public const string NuGetApiKey = "NUGET_APIKEY"; public const string Version = "APPVEYOR_BUILD_VERSION"; } public static class NuGet { public readonly static string[] DependencyFeeds = { "https://api.nuget.org/v3/index.json" }; } } <file_sep>using System; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace OnionSeed.Extensions { public class AsyncExtensionsTests { [Fact] public void RunSynchronously_ShouldExecuteAsyncMethod() { // Arrange var called = false; Func<Task> method = () => { called = true; return Task.Delay(30); }; // Act method.RunSynchronously(); // Assert called.Should().BeTrue(); } [Fact] public void RunSynchronously_ShouldExecuteAsyncMethod_AndReturnResult() { // Arrange const int value = 21; Func<Task<int>> method = () => { return Task.Delay(30) .ContinueWith(t => value, TaskScheduler.Current); }; // Act var result = method.RunSynchronously(); // Assert result.Should().Be(value); } } } <file_sep>namespace OnionSeed.Factories { /// <summary> /// Identifies the different ways a sequential GUID can be structured. /// </summary> /// <remarks>Different databases store GUID values in different ways internally. /// If this is not taken into consideration, GUID values can be much slower to persist than simple integer values. /// But by selecting a format that matches a database's storage particulars, we can largely negate that overhead.</remarks> public enum SequentialGuidType { /// <summary> /// Indicates that the GUID values will be stored as strings in the database, /// with the sequential data at the beginning of the string value of the GUID. /// <p>This works well for: /// <list type="bullet"> /// <item> /// <description>MySQL (using <c>char(36)</c>)</description> /// </item> /// <item> /// <description>PostgreSQL (using <c>uuid</c>)</description> /// </item> /// <item> /// <description>SQLite (when stored as 36 characters of text)</description> /// </item> /// </list></p></summary> SequentialAsString = 0, /// <summary> /// Indicates that the GUID values will be stored as raw binary data. /// <p>This works well for: /// <list type="bullet"> /// <item> /// <description>Oracle (using <c>raw(16)</c>)</description> /// </item> /// <item> /// <description>SQLite (when stored as 16 bytes of binary data)</description> /// </item> /// </list></p></summary> SequentialAsBinary = 1, /// <summary> /// Indicates that the GUID values will be stored as raw binary data, /// with the least-significant bytes containing the sequential data. /// <p>This works well for: /// <list type="bullet"> /// <item> /// <description>SQL Server (using <c>uniqueidentifier</c>)</description> /// </item> /// </list></p></summary> SequentialAtEnd = 2 } } <file_sep>using System; using System.Linq; using FluentAssertions; using Xunit; namespace OnionSeed.Types { public class RangeTests { [Theory] [InlineData(null, null)] [InlineData(null, "Z")] [InlineData("A", null)] public void Constructor_ShouldCheckForNullParameters(string min, string max) { // Act Action action = () => new Range<string>(min, max); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Constructor_ShouldThrowException_WhenMinIsGreaterThanMax() { // Act Action action = () => new Range<int>(5, 4); // Assert action.Should().Throw<ArgumentOutOfRangeException>(); } [Theory] [InlineData(1, 1, true, false)] [InlineData(1, 2, false, true)] public void Constructor_ShouldInitializeProperties(int min, int max, bool degenerate, bool proper) { // Act var result = new Range<int>(min, max); // Assert result.MinValue.Should().Be(min); result.MaxValue.Should().Be(max); result.IsDegenerate.Should().Be(degenerate); result.IsProper.Should().Be(proper); } [Theory] [InlineData(1, 1, 1, 1, true)] [InlineData(1, 1, 1, 2, false)] [InlineData(1, 1, 0, 1, false)] [InlineData(1, 1, 2, 2, false)] public void EqualityOperators_ShouldReturnCorrectResults(int leftMin, int leftMax, int rightMin, int rightMax, bool areEqual) { // Arrange var left = new Range<int>(leftMin, leftMax); var right = new Range<int>(rightMin, rightMax); // ReSharper disable ConditionIsAlwaysTrueOrFalse // ReSharper disable EqualExpressionComparison #pragma warning disable CS1718 // Comparison made to same variable #pragma warning disable SA1131 // Use readable conditions // Act, Assert (null == left).Should().BeFalse(); (left == null).Should().BeFalse(); (left == left).Should().BeTrue(); (left == right).Should().Be(areEqual); (right == left).Should().Be(areEqual); (null != left).Should().BeTrue(); (left != null).Should().BeTrue(); (left != left).Should().BeFalse(); (left != right).Should().Be(!areEqual); (right != left).Should().Be(!areEqual); left.Equals((object)null).Should().BeFalse(); left.Equals((object)left).Should().BeTrue(); left.Equals((object)right).Should().Be(areEqual); left.Equals(null).Should().BeFalse(); left.Equals(left).Should().BeTrue(); left.Equals(right).Should().Be(areEqual); // ReSharper enable ConditionIsAlwaysTrueOrFalse // ReSharper enable EqualExpressionComparison #pragma warning restore CS1718 // Comparison made to same variable #pragma warning restore SA1131 // Use readable conditions } [Fact] public void GetHashCode_ShouldReturnValue() { // Arrange var subject = new Range<int>(3, 5); // Act var result = subject.GetHashCode(); // Assert result.Should().Be(1186); } [Fact] public void ToString_ShouldOutputStringRepresentation() { // Arrange var subject = new Range<int>(3, 5); // Act var result = subject.ToString(); // Assert result.Should().Be("[3,5]"); } [Fact] public void Enumerate_ShouldValidateParameters() { // Arrange var subject = new Range<int>(1, 5); // Act Action action = () => subject.Enumerate(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Enumerate_ShouldStartAtMin_AndStopAtMax() { // Arrange var subject = new Range<int>(1, 5); // Act var result = subject.Enumerate(x => x + 1).ToList(); // Assert result.Should().BeEquivalentTo(new[] { 1, 2, 3, 4, 5 }); result.Should().BeInAscendingOrder(); } [Fact] public void EnumerateBackward_ShouldValidateParameters() { // Arrange var subject = new Range<int>(1, 5); // Act Action action = () => subject.EnumerateBackward(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void EnumerateBackward_ShouldStartAtMax_AndStopAtMin() { // Arrange var subject = new Range<int>(1, 5); // Act var result = subject.EnumerateBackward(x => x - 1).ToList(); // Assert result.Should().BeEquivalentTo(new[] { 5, 4, 3, 2, 1 }); result.Should().BeInDescendingOrder(); } } } <file_sep>#if STATIC_TASKS using System; using FluentAssertions; using Xunit; namespace OnionSeed { public class TaskHelpersTests { [Fact] public void CompletedTask_ShouldReturnCompletedTask() { // Act var result = TaskHelpers.CompletedTask; // Assert result.Should().NotBeNull(); result.IsCanceled.Should().BeFalse(); result.IsCompleted.Should().BeTrue(); result.IsFaulted.Should().BeFalse(); } [Fact] public void FromException_ShouldThrowException_WhenReturnTypeIsNotGiven_AndExceptionIsNull() { // Act Action action = () => TaskHelpers.FromException(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void FromException_ShouldReturnFaultedTask_WhenReturnTypeIsNotGiven() { // Act var result = TaskHelpers.FromException(new InvalidOperationException("huh")); // Assert result.Should().NotBeNull(); result.IsCanceled.Should().BeFalse(); result.IsCompleted.Should().BeTrue(); result.IsFaulted.Should().BeTrue(); } [Fact] public void FromException_ShouldThrowException_WhenReturnTypeIsGiven_AndExceptionIsNull() { // Act Action action = () => TaskHelpers.FromException<string>(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void FromException_ShouldReturnFaultedTask_WhenReturnTypeIsGiven() { // Act var result = TaskHelpers.FromException<string>(new InvalidOperationException("huh")); // Assert result.Should().NotBeNull(); result.IsCanceled.Should().BeFalse(); result.IsCompleted.Should().BeTrue(); result.IsFaulted.Should().BeTrue(); } } } #endif <file_sep>#load "./Constants.cake" #load "./Git.cake" Task("SetReleaseConfig") .Does(() => { var config = "Release"; Information($"Configuration set to '{config}'"); Constants.Build.Configuration = config; }); Task("DotNetVersion") .Does(() => { StartProcess("dotnet", new ProcessSettings { Arguments = new ProcessArgumentBuilder() .Append("--version") }); }); Task("Clean") .Does(() => { DotNetCoreClean(".", new DotNetCoreCleanSettings { Configuration = Constants.Build.Configuration, Verbosity = DotNetCoreVerbosity.Minimal }); }); Task("Restore") .Does(() => { DotNetCoreRestore(new DotNetCoreRestoreSettings { Sources = Constants.NuGet.DependencyFeeds, Verbosity = DotNetCoreVerbosity.Minimal }); }); Task("SetVersion") .Does(() => { Constants.Build.Version = EnvironmentVariable(Constants.EnvironmentVariables.Version) ?? Constants.Build.DefaultVersion; if (!Git.CurrentBranchIsMaster()) Constants.Build.Version += $"-{Git.CurrentBranch()}"; Information($"Building version {Constants.Build.Version}"); }); Task("Build") .Does(() => { DotNetCoreBuild(".", new DotNetCoreBuildSettings { Configuration = Constants.Build.Configuration, MSBuildSettings = new DotNetCoreMSBuildSettings() .SetVersion(Constants.Build.Version), NoRestore = true, Verbosity = DotNetCoreVerbosity.Minimal }); }); Task("Test") .DoesForEach(GetSubDirectories("./test"), project => { DotNetCoreTest(project.FullPath, new DotNetCoreTestSettings { Configuration = Constants.Build.Configuration, NoBuild = true, NoRestore = true, Verbosity = DotNetCoreVerbosity.Normal }); }); Task("Pack") .DoesForEach(GetSubDirectories("./src"), project => { DotNetCorePack(project.FullPath, new DotNetCorePackSettings { Configuration = Constants.Build.Configuration, MSBuildSettings = new DotNetCoreMSBuildSettings() .SetVersion(Constants.Build.Version), NoBuild = true, NoRestore = true, Verbosity = DotNetCoreVerbosity.Normal }); }); Task("Push") .Does(() => { var rootUri = EnvironmentVariable(Constants.EnvironmentVariables.NuGetRootUri); if (string.IsNullOrWhiteSpace(rootUri)) throw new InvalidOperationException("NuGet publish root was not found"); var apiKey = EnvironmentVariable(Constants.EnvironmentVariables.NuGetApiKey); if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("NuGet API key was not found"); foreach (var package in GetFiles("./src/**/*.nupkg")) { var packageName = package.GetFilenameWithoutExtension().ToString().Replace($".{Constants.Build.Version}", string.Empty); var publishUri = $"{rootUri}/{packageName}"; DotNetCoreNuGetPush(package.FullPath, new DotNetCoreNuGetPushSettings { ApiKey = apiKey, Source = publishUri }); } }); <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <summary> /// Defines a mechanism that can be used to asynchronously query entities from a data store. /// </summary> /// <typeparam name="T">The type of entities in the data store.</typeparam> /// <typeparam name="TId">The type of the unique identity value of the entities in the data store.</typeparam> public interface IAsyncQueryService<T, in TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Gets the number of entities in the data store. /// </summary> /// <returns>A task representing the operation. Upon completion, it will contain /// the number of entities in the data store.</returns> Task<long> GetCountAsync(); /// <summary> /// Begins an enumeration of all entities in the data store. /// </summary> /// <returns>A task representing the operation. Upon completion, it will contain /// an enumeration of all entities in the data store.</returns> Task<IEnumerable<T>> GetAllAsync(); /// <summary> /// Gets a specific entity from the data store by its unique identity value. /// </summary> /// <param name="id">The unique identity value of the entity.</param> /// <returns>A task representing the operation. Upon completion, it will contain /// the entity that has the given unique identity value.</returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception> /// <exception cref="KeyNotFoundException">The specified unique identity value does not exist in the data store.</exception> Task<T> GetByIdAsync(TId id); /// <summary> /// Attempts to get a specific entity from the data store by its unique identity value. /// </summary> /// <param name="id">The unique identity value of the entity.</param> /// <returns>A task representing the operation. Upon completion, it will contain /// the entity that has the given unique identity value, /// or <c>null</c> if the specified entity was not found.</returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception> Task<T> TryGetByIdAsync(TId id); } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncQueryServiceAdapterTests { private readonly Mock<IQueryService<FakeEntity<int>, int>> _mockInner = new Mock<IQueryService<FakeEntity<int>, int>>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new AsyncQueryServiceAdapter<FakeEntity<int>, int>(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public async Task GetCountAsync_ShouldCallSyncMethod_AndReturnResult() { // Arrange const long count = 38; _mockInner .Setup(i => i.GetCount()) .Returns(count); var subject = new AsyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = await subject.GetCountAsync().ConfigureAwait(false); // Assert result.Should().Be(count); _mockInner.VerifyAll(); } [Fact] public async Task GetAllAsync_ShouldCallSyncMethod_AndReturnResult() { // Arrange var data = Enumerable.Empty<FakeEntity<int>>(); _mockInner .Setup(i => i.GetAll()) .Returns(data); var subject = new AsyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = await subject.GetAllAsync().ConfigureAwait(false); // Assert result.Should().BeSameAs(data); _mockInner.VerifyAll(); } [Fact] public async Task GetByIdAsync_ShouldCallSyncMethod_AndReturnResult() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.GetById(entity.Id)) .Returns(entity); var subject = new AsyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = await subject.GetByIdAsync(entity.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(entity); _mockInner.VerifyAll(); } [Fact] public async Task TryGetByIdAsync_ShouldCallSyncMethod_AndReturnFalse_WhenEntityIsNotFound() { // Arrange const int id = 42; FakeEntity<int> person = null; _mockInner .Setup(i => i.TryGetById(id, out person)) .Returns(false); var subject = new AsyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = await subject.TryGetByIdAsync(id).ConfigureAwait(false); // Assert result.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryGetByIdAsync_ShouldCallSyncMethod_AndReturnTrue_WhenEntityIsFound() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryGetById(entity.Id, out entity)) .Returns(true); var subject = new AsyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = await subject.TryGetByIdAsync(entity.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(entity); _mockInner.VerifyAll(); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Factories { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Tests don't need to end in 'Async'.")] public class EntityFactoryTests { [Fact] public void Constructor_ShouldThrowException_WhenAbstractFactoryIsNull() { // Arrange IFactory<int> factory = null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(factory); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Constructor_ShouldThrowException_WhenAsyncAbstractFactoryIsNull() { // Arrange IAsyncFactory<int> asyncFactory = null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(asyncFactory); // Assert action.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldThrowException_WhenAbstractFactoriesAreNull(bool includeFactory, bool includeAsyncFactory) { // Arrange var factory = includeFactory ? new Mock<IFactory<int>>().Object : null; var asyncFactory = includeAsyncFactory ? new Mock<IAsyncFactory<int>>().Object : null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(factory, asyncFactory); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Constructor_ShouldThrowException_WhenFactoryMethodIsNull() { // Arrange Func<int> factory = null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(factory); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Constructor_ShouldThrowException_WhenAsyncFactoryMethodIsNull() { // Arrange Func<Task<int>> asyncFactory = null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(asyncFactory); // Assert action.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldThrowException_WhenFactoryMethodsAreNull(bool includeFactory, bool includeAsyncFactory) { // Arrange var factory = includeFactory ? new Mock<Func<int>>().Object : null; var asyncFactory = includeAsyncFactory ? new Mock<Func<Task<int>>>().Object : null; // Act Action action = () => new EntityFactory<FakeEntity<int>, int>(factory, asyncFactory); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void CreateNew_ShouldCreateEntity_WhenSyncAbstractFactoryIsGiven() { // Arrange const int id = 17; var mockFactory = new Mock<IFactory<int>>(MockBehavior.Strict); mockFactory.Setup(f => f.CreateNew()).Returns(id); var subject = new EntityFactory<FakeEntity<int>, int>(mockFactory.Object); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockFactory.VerifyAll(); } [Fact] public void CreateNew_ShouldCreateEntity_WhenAsyncAbstractFactoryIsGiven() { // Arrange const int id = 17; var mockAsyncFactory = new Mock<IAsyncFactory<int>>(MockBehavior.Strict); mockAsyncFactory.Setup(f => f.CreateNewAsync()).Returns(Task.FromResult(id)); var subject = new EntityFactory<FakeEntity<int>, int>(mockAsyncFactory.Object); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockAsyncFactory.VerifyAll(); } [Fact] public void CreateNew_ShouldCreateEntity_UsingSync_WhenBothAbstractFactoriesAreGiven() { // Arrange const int id = 17; var mockFactory = new Mock<IFactory<int>>(MockBehavior.Strict); mockFactory.Setup(f => f.CreateNew()).Returns(id); var mockAsyncFactory = new Mock<IAsyncFactory<int>>(MockBehavior.Strict); var subject = new EntityFactory<FakeEntity<int>, int>(mockFactory.Object, mockAsyncFactory.Object); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockFactory.VerifyAll(); mockAsyncFactory.VerifyAll(); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public void CreateNew_ShouldCreateEntity_WhenSyncFactoryMethodIsGiven() { // Arrange const int id = 17; Func<int> factory = () => id; var subject = new EntityFactory<FakeEntity<int>, int>(factory); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public void CreateNew_ShouldCreateEntity_WhenAsyncFactoryMethodIsGiven() { // Arrange const int id = 17; Func<Task<int>> asyncFactory = () => Task.FromResult(id); var subject = new EntityFactory<FakeEntity<int>, int>(asyncFactory); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public void CreateNew_ShouldCreateEntity_UsingSync_WhenBothFactoryMethodsAreGiven() { // Arrange const int id = 17; Func<int> factory = () => id; Func<Task<int>> asyncFactory = () => Task.FromResult(5); var subject = new EntityFactory<FakeEntity<int>, int>(factory, asyncFactory); // Act var result = subject.CreateNew(); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } [Fact] public async Task CreateNewAsync_ShouldCreateEntity_WhenSyncAbstractFactoryIsGiven() { // Arrange const int id = 17; var mockFactory = new Mock<IFactory<int>>(MockBehavior.Strict); mockFactory.Setup(f => f.CreateNew()).Returns(id); var subject = new EntityFactory<FakeEntity<int>, int>(mockFactory.Object); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockFactory.VerifyAll(); } [Fact] public async Task CreateNewAsync_ShouldCreateEntity_WhenAsyncAbstractFactoryIsGiven() { // Arrange const int id = 17; var mockAsyncFactory = new Mock<IAsyncFactory<int>>(MockBehavior.Strict); mockAsyncFactory.Setup(f => f.CreateNewAsync()).Returns(Task.FromResult(id)); var subject = new EntityFactory<FakeEntity<int>, int>(mockAsyncFactory.Object); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockAsyncFactory.VerifyAll(); } [Fact] public async Task CreateNewAsync_ShouldCreateEntity_UsingAsync_WhenBothAbstractFactoriesAreGiven() { // Arrange const int id = 17; var mockFactory = new Mock<IFactory<int>>(MockBehavior.Strict); var mockAsyncFactory = new Mock<IAsyncFactory<int>>(MockBehavior.Strict); mockAsyncFactory.Setup(f => f.CreateNewAsync()).Returns(Task.FromResult(id)); var subject = new EntityFactory<FakeEntity<int>, int>(mockFactory.Object, mockAsyncFactory.Object); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); mockFactory.VerifyAll(); mockAsyncFactory.VerifyAll(); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public async Task CreateNewAsync_ShouldCreateEntity_WhenSyncFactoryMethodIsGiven() { // Arrange const int id = 17; Func<int> factory = () => id; var subject = new EntityFactory<FakeEntity<int>, int>(factory); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public async Task CreateNewAsync_ShouldCreateEntity_WhenAsyncFactoryMethodIsGiven() { // Arrange const int id = 17; Func<Task<int>> asyncFactory = () => Task.FromResult(id); var subject = new EntityFactory<FakeEntity<int>, int>(asyncFactory); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } [Fact] [SuppressMessage("Style", "IDE0039:Use local function", Justification = "Testing lambda expressions.")] public async Task CreateNewAsync_ShouldCreateEntity_UsingAsync_WhenBothFactoryMethodsAreGiven() { // Arrange const int id = 17; Func<int> factory = () => 5; Func<Task<int>> asyncFactory = () => Task.FromResult(id); var subject = new EntityFactory<FakeEntity<int>, int>(factory, asyncFactory); // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); result.Id.Should().Be(id); } } } <file_sep>using System; using OnionSeed.Types; namespace OnionSeed { public class FakeEntity<TKey> : IWritableEntity<TKey> where TKey : IEquatable<TKey>, IComparable<TKey> { public TKey Id { get; set; } public string Name { get; set; } } } <file_sep>using System; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Decorates an <see cref="IAsyncRepository{T, TId}"/>, /// mirroring commands to a secondary, "tap" <see cref="IAsyncRepository{T, TId}"/>. /// </summary> /// <remarks>This decorator functions like a network tap: commands are executed first against the /// inner repository; if they succeed, they are then executed against the tap repository as well. /// Queries are only executed against the inner repository, and anything returned from the tap repository is ignored. /// <para>This essentially allows for the creation of a duplicate copy of the data, /// and is intended to be used for things like caching, backup, or reporting.</para></remarks> public class AsyncRepositoryTap<T, TId> : AsyncRepositoryDecorator<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="AsyncRepositoryTap{T,TKey}"/> class, /// using the given repositories. /// </summary> /// <param name="inner">The <see cref="IAsyncRepository{T, TId}"/> to be decorated.</param> /// <param name="tap">The tap repository, where commands will be duplicated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="tap"/> is <c>null</c>.</exception> public AsyncRepositoryTap(IAsyncRepository<T, TId> inner, IAsyncRepository<T, TId> tap) : base(inner) { Tap = tap ?? throw new ArgumentNullException(nameof(tap)); } /// <summary> /// Gets a reference to the tap repository. /// </summary> public IAsyncRepository<T, TId> Tap { get; } /// <inheritdoc/> public override async Task AddAsync(T item) { await Inner.AddAsync(item).ConfigureAwait(false); await Tap.AddOrUpdateAsync(item).ConfigureAwait(false); } /// <inheritdoc/> public override async Task AddOrUpdateAsync(T item) { await Inner.AddOrUpdateAsync(item).ConfigureAwait(false); await Tap.AddOrUpdateAsync(item).ConfigureAwait(false); } /// <inheritdoc/> public override async Task UpdateAsync(T item) { await Inner.UpdateAsync(item).ConfigureAwait(false); await Tap.AddOrUpdateAsync(item).ConfigureAwait(false); } /// <inheritdoc/> public override async Task RemoveAsync(T item) { await Inner.RemoveAsync(item).ConfigureAwait(false); await Tap.RemoveAsync(item).ConfigureAwait(false); } /// <inheritdoc/> public override async Task RemoveAsync(TId id) { await Inner.RemoveAsync(id).ConfigureAwait(false); await Tap.RemoveAsync(id).ConfigureAwait(false); } /// <inheritdoc/> public override async Task<bool> TryAddAsync(T item) { var success = await Inner.TryAddAsync(item).ConfigureAwait(false); if (success) await Tap.AddOrUpdateAsync(item).ConfigureAwait(false); return success; } /// <inheritdoc/> public override async Task<bool> TryUpdateAsync(T item) { var success = await Inner.TryUpdateAsync(item).ConfigureAwait(false); if (success) await Tap.AddOrUpdateAsync(item).ConfigureAwait(false); return success; } /// <inheritdoc/> public override async Task<bool> TryRemoveAsync(T item) { var success = await Inner.TryRemoveAsync(item).ConfigureAwait(false); await Tap.RemoveAsync(item).ConfigureAwait(false); return success; } /// <inheritdoc/> public override async Task<bool> TryRemoveAsync(TId id) { var success = await Inner.TryRemoveAsync(id).ConfigureAwait(false); await Tap.RemoveAsync(id).ConfigureAwait(false); return success; } } } <file_sep>namespace OnionSeed.Data { /// <summary> /// Defines an atomic transaction whose changes are to be committed as a collective whole. /// </summary> public interface IUnitOfWork { /// <summary> /// Commits any pending changes. /// </summary> void Commit(); } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncUnitOfWorkExceptionHandlerTests { private readonly Mock<IAsyncUnitOfWork> _mockInner = new Mock<IAsyncUnitOfWork>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new AsyncUnitOfWorkExceptionHandler<InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public async Task CommitAsync_ShouldCallInner() { // Arrange InvalidOperationException exception = null; _mockInner .Setup(i => i.CommitAsync()) .Returns(CompletedTask()); var subject = new AsyncUnitOfWorkExceptionHandler<InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.CommitAsync().ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task CommitAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.CommitAsync()) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncUnitOfWorkExceptionHandler<InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.CommitAsync().ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } private static Task ExceptionTask(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException(ex); #else return Task.FromException(ex); #endif } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>#load "./build/DotNet.cake" var target = Argument("target", "CI"); Task("FullBuild") .IsDependentOn("DotNetVersion") .IsDependentOn("Clean") .IsDependentOn("Restore") .IsDependentOn("SetVersion") .IsDependentOn("Build"); Task("CI") .IsDependentOn("FullBuild") .IsDependentOn("Test"); Task("Publish") .IsDependentOn("SetReleaseConfig") .IsDependentOn("CI") .IsDependentOn("TagBuild") .IsDependentOn("Pack") .IsDependentOn("Push"); RunTarget(target); <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncRepositoryExceptionHandlerTests { private readonly Mock<IAsyncRepository<FakeEntity<int>, int>> _mockInner = new Mock<IAsyncRepository<FakeEntity<int>, int>>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public async Task AddAsync_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.AddAsync(entity)) .Returns(CompletedTask()); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.AddAsync(entity).ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task AddAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.AddAsync(entity)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.AddAsync(entity).ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task AddOrUpdateAsync_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.AddOrUpdateAsync(entity)) .Returns(CompletedTask()); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.AddOrUpdateAsync(entity).ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task AddOrUpdateAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.AddOrUpdateAsync(entity)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.AddOrUpdateAsync(entity).ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task UpdateAsync_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.UpdateAsync(entity)) .Returns(CompletedTask()); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.UpdateAsync(entity).ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task UpdateAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.UpdateAsync(entity)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.UpdateAsync(entity).ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallInner_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.RemoveAsync(entity)) .Returns(CompletedTask()); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.RemoveAsync(entity).ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldInvokeHandle_WhenEntityIsGiven_AndInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.RemoveAsync(entity)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.RemoveAsync(entity).ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallInner_WhenIdIsGiven() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.RemoveAsync(id)) .Returns(CompletedTask()); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldInvokeHandle_WhenIdIsGiven_AndInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.RemoveAsync(id)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryAddAsync_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryAddAsync(entity)) .ReturnsAsync(true); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryAddAsync(entity).ConfigureAwait(false); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryAddAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryAddAsync(entity)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryAddAsync(entity).ConfigureAwait(false); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryUpdateAsync_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryUpdateAsync(entity)) .ReturnsAsync(true); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryUpdateAsync(entity).ConfigureAwait(false); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryUpdateAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryUpdateAsync(entity)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryUpdateAsync(entity).ConfigureAwait(false); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallInner_AndReturnResult_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemoveAsync(entity)) .ReturnsAsync(true); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryRemoveAsync(entity).ConfigureAwait(false); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldInvokeHandle_WhenEntityIsGiven_AndInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemoveAsync(entity)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryRemoveAsync(entity).ConfigureAwait(false); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallInner_AndReturnResult_WhenIdIsGiven() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemoveAsync(id)) .ReturnsAsync(true); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryRemoveAsync(id).ConfigureAwait(false); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldInvokeHandle_WhenIdIsGiven_AndInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemoveAsync(id)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryRemoveAsync(id).ConfigureAwait(false); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } private static Task ExceptionTask(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException(ex); #else return Task.FromException(ex); #endif } private static Task<T> ExceptionTask<T>(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException<T>(ex); #else return Task.FromException<T>(ex); #endif } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>using System; namespace OnionSeed.Types { /// <inheritdoc /> /// <summary> /// Represents an entity in a state where it's unique identity value can be set /// (for example, when creating a new instance or re-hydrating an instance from a data store). /// </summary> public interface IWritableEntity<TId> : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Gets or sets the unique identity value. /// </summary> new TId Id { get; set; } } } <file_sep>using System; using System.Threading.Tasks; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IUnitOfWork"/> to work like an <see cref="IAsyncUnitOfWork"/>. /// </summary> public class AsyncUnitOfWorkAdapter : UnitOfWorkDecorator, IAsyncUnitOfWork { /// <summary> /// Initializes a new instance of the <see cref="AsyncUnitOfWorkAdapter"/> class, /// wrapping the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncUnitOfWorkAdapter(IUnitOfWork inner) : base(inner) { } /// <inheritdoc/> public Task CommitAsync() => Task.Run(() => Inner.Commit()); } } <file_sep>public static class Git { public static string CurrentBranch() { return Execute("rev-parse --abbrev-ref HEAD"); } public static bool CurrentBranchIsMaster() { return CurrentBranch().Equals("master", StringComparison.OrdinalIgnoreCase); } public static string Execute(string arguments) { var git = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = "git", Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }); return git.StandardOutput.ReadToEnd().Trim(); } } Task("TagBuild") .WithCriteria(Git.CurrentBranchIsMaster()) .Does(() => { var username = EnvironmentVariable(Constants.EnvironmentVariables.GitUsername); var password = EnvironmentVariable(Constants.EnvironmentVariables.GitPassword); password = System.Net.WebUtility.UrlEncode(password); var origin = new Uri(Git.Execute("config --get remote.origin.url")); var uri = $"https://{username}:{password}@{origin.Host}{origin.PathAndQuery}"; if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)) { StartProcess("git", new ProcessSettings { Arguments = new ProcessArgumentBuilder() .Append("tag") .Append(Constants.Build.Version) }); StartProcess("git", new ProcessSettings { Arguments = new ProcessArgumentBuilder() .Append("push") .Append(uri) .Append(Constants.Build.Version) }); } }); <file_sep># About OnionSeed OnionSeed is intended to be a small library that contains basic types and pattern definitions that are typically used in enterprise architecture. It is a "seed" from which a well-structured, layerd application can be built. I've used variations of these objects many times in my own projects and at work, and wanted a place to stash them for better reuse. ## DDD and Onion Architecture These two software development paradigms have probably been the most influential on me, and have greatly shaped the code in OnionSeed. If you're not familiar with either one of them, I highly recommend doing some research - it's great stuff. Both paradigms have been around for several years, and there's a good amount of information out there about them: - **Domain-Driven Design** was first described by <NAME> in his [awesome book](http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215), and you can get a quick overview on [Wikipedia](https://en.wikipedia.org/wiki/Domain-driven_design). - **Onion Architecture** was first defined by <NAME> on his [personal blog](http://jeffreypalermo.com/blog/the-onion-architecture-part-1/). The interfaces defined in OnionSeed are designed to help encourage the patterns identified in these two paradigms. The code here all belongs in the very center of the Onion, at the center of the Domain Model itself. It's meant to be the seed that an application grows out of, and as such it should have no external dependencies except the .NET Framework itself. ## External Tooling The goal is for this code to be as robust as possible, while still emphasizing code cleanliness and simplicity. I realize those two goals are sometimes at odds with each other, and in those cases I favor robustness over cleanliness. I figure developers can deal with a little clutter (and maybe read some comments) if that means the code can be more effective. This doesn't mean I condone sloppiness, but there are a few external tools that I've allowed to add a degree of "clutter" to the code: - I allow [Microsoft's CodeAnalysis tool](https://msdn.microsoft.com/en-us/library/3z0aeatx.aspx?f=255&MSPPError=-2147217396) to run (almost) its full ruleset to make sure I consider any recommendations it has. This means I occasionally include suppression attributes whenever a rule needs to be ignored. - I'm drawn to the idea of [Design by Contract](https://en.wikipedia.org/wiki/Design_by_contract), and have an appreciation for [Microsoft's CodeContracts project](http://research.microsoft.com/en-us/projects/contracts/). It's still not completely out of the research phase, but it has some core libraries included in the official .NET Framework now. I hope that means they'll eventually make it a first-class citizen of the .NET world. It's still got some quirks at this point, but it's really pretty useful once you get used to it. I've applied contracts to the code in OnionSeed, so they'll be available to you if you use CodeContracts in your own project. The contracts are compiled into their own external assembly though, so they'll just be ignored if you're _not_ using CodeContracts. You will however need to install the extension if you want to build the OnionSeed source code.<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace OnionSeed.Factories { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Tests don't need to end in 'Async'.")] public class SequentialGuidFactoryTests { private const int TestIterations = 100000; [Fact] public void Constructor_ShouldThrowException_WhenTypeIsNotRecognized() { // Act Action action = () => new SequentialGuidFactory((SequentialGuidType)10); // Assert action.Should().Throw<ArgumentOutOfRangeException>(); } [Fact] public void CreateNew_ShouldReturnNewGuid_WithoutCollisions_WhenTypeIsBinary() { // Arrange var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAsBinary); for (var i = 0; i < TestIterations; i++) { // Act var result = subject.CreateNew(); // Assert uniqueResults.Add(result).Should().BeTrue(); var sequentialBytes = result.ToByteArray().Take(SequentialGuidFactory.NumberOfSequentialBytes).ToArray(); sequentialData[i] = BitConverter.ToString(sequentialBytes); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } [Fact] public void CreateNew_ShouldReturnNewGuid_WithoutCollisions_WhenTypeIsString() { // Arrange const int numberOfChars = (SequentialGuidFactory.NumberOfSequentialBytes * 2) + 1; // 2 chars per byte, plus one hyphen var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAsString); for (var i = 0; i < TestIterations; i++) { // Act var result = subject.CreateNew(); // Assert uniqueResults.Add(result).Should().BeTrue(); sequentialData[i] = result.ToString().Substring(0, numberOfChars); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } [Fact] public void CreateNew_ShouldReturnNewGuid_WithoutCollisions_WhenSequenceIsAtEnd() { // Arrange const int numberOfChars = SequentialGuidFactory.NumberOfSequentialBytes * 2; // 2 chars per byte var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAtEnd); for (var i = 0; i < TestIterations; i++) { // Act var result = subject.CreateNew(); // Assert uniqueResults.Add(result).Should().BeTrue(); var guidString = result.ToString(); sequentialData[i] = guidString.Substring(guidString.Length - numberOfChars, numberOfChars); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } [Fact] public async Task CreateNewAsync_ShouldReturnNewGuid_WithoutCollisions_WhenTypeIsBinary() { // Arrange var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAsBinary); for (var i = 0; i < TestIterations; i++) { // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert uniqueResults.Add(result).Should().BeTrue(); var sequentialBytes = result.ToByteArray().Take(SequentialGuidFactory.NumberOfSequentialBytes).ToArray(); sequentialData[i] = BitConverter.ToString(sequentialBytes); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } [Fact] public async Task CreateNewAsync_ShouldReturnNewGuid_WithoutCollisions_WhenTypeIsString() { // Arrange const int numberOfChars = (SequentialGuidFactory.NumberOfSequentialBytes * 2) + 1; // 2 chars per byte, plus one hyphen var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAsString); for (var i = 0; i < TestIterations; i++) { // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert uniqueResults.Add(result).Should().BeTrue(); sequentialData[i] = result.ToString().Substring(0, numberOfChars); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } [Fact] public async Task CreateNewAsync_ShouldReturnNewGuid_WithoutCollisions_WhenSequenceIsAtEnd() { // Arrange const int numberOfChars = SequentialGuidFactory.NumberOfSequentialBytes * 2; // 2 chars per byte var uniqueResults = new HashSet<Guid>(); var sequentialData = new string[TestIterations]; var subject = new SequentialGuidFactory(SequentialGuidType.SequentialAtEnd); for (var i = 0; i < TestIterations; i++) { // Act var result = await subject.CreateNewAsync().ConfigureAwait(false); // Assert uniqueResults.Add(result).Should().BeTrue(); var guidString = result.ToString(); sequentialData[i] = guidString.Substring(guidString.Length - numberOfChars, numberOfChars); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); sequentialData.Should().BeInAscendingOrder(); } } } <file_sep>using System; using System.Collections.Generic; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IQueryService{T, TId}"/>. /// </summary> public abstract class QueryServiceDecorator<T, TId> : IQueryService<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="QueryServiceDecorator{T, TId}"/> class, /// decorating the given <see cref="IQueryService{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IQueryService{T, TId}"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public QueryServiceDecorator(IQueryService<T, TId> inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IQueryService{T, TId}"/> being decorated. /// </summary> protected IQueryService<T, TId> Inner { get; } /// <inheritdoc/> public virtual long GetCount() => Inner.GetCount(); /// <inheritdoc/> public virtual IEnumerable<T> GetAll() => Inner.GetAll(); /// <inheritdoc/> public virtual T GetById(TId id) => Inner.GetById(id); /// <inheritdoc/> public virtual bool TryGetById(TId id, out T result) => Inner.TryGetById(id, out result); } } <file_sep>using System; using FluentAssertions; using Xunit; namespace OnionSeed.Extensions { public class ComparableExtensionsTests { [Fact] public void IsLessThan_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsLessThan(4); Action action2 = () => ((IComparable<int>)null).IsLessThan(4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, true)] [InlineData(2, 2, false)] [InlineData(3, 2, false)] public void IsLessThan_ShouldReturnCorrectValues(int left, int right, bool expected) { // Act, Assert ((IComparable)left).IsLessThan(right).Should().Be(expected); ((IComparable<int>)left).IsLessThan(right).Should().Be(expected); } [Fact] public void IsLessThanOrEqualTo_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsLessThanOrEqualTo(4); Action action2 = () => ((IComparable<int>)null).IsLessThanOrEqualTo(4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, true)] [InlineData(2, 2, true)] [InlineData(3, 2, false)] public void IsLessThanOrEqualTo_ShouldReturnCorrectValues(int left, int right, bool expected) { // Act, Assert ((IComparable)left).IsLessThanOrEqualTo(right).Should().Be(expected); ((IComparable<int>)left).IsLessThanOrEqualTo(right).Should().Be(expected); } [Fact] public void IsEqualTo_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsEqualTo(4); Action action2 = () => ((IComparable<int>)null).IsEqualTo(4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, false)] [InlineData(2, 2, true)] [InlineData(3, 2, false)] public void IsEqualTo_ShouldReturnCorrectValues(int left, int right, bool expected) { // Act, Assert ((IComparable)left).IsEqualTo(right).Should().Be(expected); ((IComparable<int>)left).IsEqualTo(right).Should().Be(expected); } [Fact] public void IsGreaterThanOrEqualTo_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsGreaterThanOrEqualTo(4); Action action2 = () => ((IComparable<int>)null).IsGreaterThanOrEqualTo(4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, false)] [InlineData(2, 2, true)] [InlineData(3, 2, true)] public void IsGreaterThanOrEqualTo_ShouldReturnCorrectValues(int left, int right, bool expected) { // Act, Assert ((IComparable)left).IsGreaterThanOrEqualTo(right).Should().Be(expected); ((IComparable<int>)left).IsGreaterThanOrEqualTo(right).Should().Be(expected); } [Fact] public void IsGreaterThan_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsGreaterThan(4); Action action2 = () => ((IComparable<int>)null).IsGreaterThan(4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, false)] [InlineData(2, 2, false)] [InlineData(3, 2, true)] public void IsGreaterThan_ShouldReturnCorrectValues(int left, int right, bool expected) { // Act, Assert ((IComparable)left).IsGreaterThan(right).Should().Be(expected); ((IComparable<int>)left).IsGreaterThan(right).Should().Be(expected); } [Fact] public void IsBetween_ShouldValidateParameters() { // Act Action action1 = () => ((IComparable)null).IsBetween(2, 4); Action action2 = () => ((IComparable<int>)null).IsBetween(2, 4); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, 4, false)] [InlineData(2, 2, 4, true)] [InlineData(3, 2, 4, true)] [InlineData(4, 2, 4, true)] [InlineData(5, 2, 4, false)] public void IsBetween_ShouldReturnCorrectValues(int left, int min, int max, bool expected) { // Act, Assert ((IComparable)left).IsBetween(min, max).Should().Be(expected); ((IComparable<int>)left).IsBetween(min, max).Should().Be(expected); } [Fact] public void ConstrainToMin_ShouldValidateParameters() { // Act Action action1 = () => ((string)null).ConstrainToMin(4); Action action2 = () => ((string)null).ConstrainToMin("hello"); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, 2)] [InlineData(2, 2, 2)] [InlineData(3, 2, 3)] public void ConstrainToMin_ShouldReturnCorrectValues(int left, int right, int expected) { // Act, Assert left.ConstrainToMin((object)right).Should().Be(expected); left.ConstrainToMin(right).Should().Be(expected); } [Fact] public void ConstrainToMax_ShouldValidateParameters() { // Act Action action1 = () => ((string)null).ConstrainToMax(4); Action action2 = () => ((string)null).ConstrainToMax("hello"); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, 1)] [InlineData(2, 2, 2)] [InlineData(3, 2, 2)] public void ConstrainToMax_ShouldReturnCorrectValues(int left, int right, int expected) { // Act, Assert left.ConstrainToMax((object)right).Should().Be(expected); left.ConstrainToMax(right).Should().Be(expected); } [Fact] public void ConstrainTo_ShouldValidateParameters() { // Act Action action1 = () => ((string)null).ConstrainTo(2, 4); Action action2 = () => ((string)null).ConstrainTo("hello", "goodbye"); // Assert action1.Should().Throw<ArgumentNullException>(); action2.Should().Throw<ArgumentNullException>(); } [Theory] [InlineData(1, 2, 4, 2)] [InlineData(2, 2, 4, 2)] [InlineData(3, 2, 4, 3)] [InlineData(4, 2, 4, 4)] [InlineData(5, 2, 4, 4)] public void ConstrainTo_ShouldReturnCorrectValues(int left, int min, int max, int expected) { // Act, Assert left.ConstrainTo((object)min, max).Should().Be(expected); left.ConstrainTo(min, max).Should().Be(expected); } } } <file_sep>using System; using System.Linq; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class QueryServiceExceptionHandlerTests { private readonly Mock<IQueryService<FakeEntity<int>, int>> _mockInner = new Mock<IQueryService<FakeEntity<int>, int>>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public void GetCount_ShouldCallInner_AndReturnResult() { // Arrange const long count = 123; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetCount()) .Returns(count); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetCount(); // Assert result.Should().Be(count); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void GetCount_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange InvalidOperationException exception = null; _mockInner .Setup(i => i.GetCount()) .Throws(new InvalidOperationException()); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetCount(); // Assert result.Should().Be(0); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void GetAll_ShouldCallInner_AndReturnResult() { // Arrange var data = Enumerable.Empty<FakeEntity<int>>(); InvalidOperationException exception = null; _mockInner .Setup(i => i.GetAll()) .Returns(data); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetAll(); // Assert result.Should().BeSameAs(data); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void GetAll_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange InvalidOperationException exception = null; _mockInner .Setup(i => i.GetAll()) .Throws(new InvalidOperationException()); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetAll(); // Assert result.Should().NotBeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void GetById_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetById(entity.Id)) .Returns(entity); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetById(entity.Id); // Assert result.Should().BeSameAs(entity); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void GetById_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetById(id)) .Throws(new InvalidOperationException()); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.GetById(id); // Assert result.Should().BeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void TryGetById_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryGetById(entity.Id, out entity)) .Returns(true); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var success = subject.TryGetById(entity.Id, out FakeEntity<int> result); // Assert success.Should().BeTrue(); result.Should().BeSameAs(entity); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryGetById_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryGetById(entity.Id, out entity)) .Throws(new InvalidOperationException()); var subject = new QueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var success = subject.TryGetById(entity.Id, out FakeEntity<int> result); // Assert success.Should().BeFalse(); result.Should().BeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using OnionSeed.Extensions; namespace OnionSeed.Types { /// <summary> /// An ordered pair of values, representing a segment. /// </summary> /// <typeparam name="T">The type of the values in the range.</typeparam> /// <remarks>This class is designed to represent a range of values, such as a date range. /// While it overlaps somewhat with <see cref="Enumerable.Range"/>, it's supposed to be a little more optimized. /// <see cref="Enumerable.Range"/> returns a list of all the values in the specified range, whereas this class /// only stores the min and max values. A <see cref="Range{T}"/> object can still be enumerated just as easily, /// but it is all done dynamically, incrementing/decrementing values on the fly.</remarks> public class Range<T> : IEquatable<Range<T>> where T : IComparable<T> { /// <summary> /// Initializes a new instance of the <see cref="Range{T}"/> class using the given parameters. /// </summary> /// <param name="min">The minimum value for the range.</param> /// <param name="max">The maximum value for the range.</param> /// <exception cref="ArgumentNullException"><paramref name="min"/> is <b>null</b>. /// -or- <paramref name="max"/> is <b>null</b>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="min"/> is greater than <paramref name="max"/>.</exception> /// <remarks>The <see cref="Range{T}"/> class is inclusive; that is to say, both <paramref name="min"/> and /// <paramref name="max"/> are included in the range. /// <para>If <paramref name="min"/> and <paramref name="max"/> are equal then the range contains only that single value /// and is considered to be degenerate. If <paramref name="min"/> and <paramref name="max"/> are not equal, then the range /// contains multiple values and is considered to be proper.</para></remarks> public Range(T min, T max) { if (min == null) throw new ArgumentNullException(nameof(min)); if (max == null) throw new ArgumentNullException(nameof(max)); if (min.IsGreaterThan(max)) throw new ArgumentOutOfRangeException(nameof(min), "The min value cannot be greater than the max value."); MinValue = min; MaxValue = max; if (min.IsEqualTo(max)) IsDegenerate = true; else IsProper = true; } /// <summary> /// Gets the minimum value for the range. /// </summary> public T MinValue { get; } /// <summary> /// Gets the maximum value for the range. /// </summary> public T MaxValue { get; } /// <summary> /// Gets a value indicating whether the range contains only a single value. /// </summary> public bool IsDegenerate { get; } /// <summary> /// Gets a value indicating whether the range contains multiple values. /// </summary> public bool IsProper { get; } /// <summary> /// Returns a value indicating whether the given values are equal. /// </summary> /// <param name="left">The value on the left side of the operator.</param> /// <param name="right">The value on the right side of the operator.</param> /// <returns><b>true</b> if <paramref name="left"/> and <paramref name="right"/> are equal; otherwise, <b>false</b>.</returns> public static bool operator ==(Range<T> left, Range<T> right) { return Equals(left, right); } /// <summary> /// Returns a value indicating whether the given values are not equal. /// </summary> /// <param name="left">The value on the left side of the operator.</param> /// <param name="right">The value on the right side of the operator.</param> /// <returns><b>true</b> if <paramref name="left"/> and <paramref name="right"/> are not equal; otherwise, <b>false</b>.</returns> public static bool operator !=(Range<T> left, Range<T> right) { return !Equals(left, right); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns><b>true</b> if the specified object is equal to the current object; otherwise, <b>false</b>.</returns> public override bool Equals(object obj) { return Equals(obj as Range<T>); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns><b>true</b> if the current object is equal to the other parameter; otherwise, <b>false</b>.</returns> public bool Equals(Range<T> other) { if (other == null) return false; return other.MinValue.IsEqualTo(MinValue) && other.MaxValue.IsEqualTo(MaxValue); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { unchecked { var hashCode = MinValue.GetHashCode(); hashCode = (hashCode * 397) ^ MaxValue.GetHashCode(); return hashCode; } } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"[{MinValue},{MaxValue}]"; } /// <summary> /// Enumerates the values that fall within the range, in ascending order (from <see cref="MinValue"/> to <see cref="MaxValue"/>). /// </summary> /// <param name="increment">The method that determines how to increment from one value to the next.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains all the values in the range, /// in ascending order, as determined by the <paramref name="increment"/> algorithm.</returns> /// <exception cref="ArgumentNullException"><paramref name="increment"/> is <b>null</b>.</exception> /// <remarks>If <paramref name="increment"/> does not move the current value from <see cref="MinValue"/> towards <see cref="MaxValue"/>, /// then this enumeration will result in an infinite loop.</remarks> public IEnumerable<T> Enumerate(Func<T, T> increment) { if (increment == null) throw new ArgumentNullException(nameof(increment)); return Enumerate(MinValue, increment, x => x.IsLessThanOrEqualTo(MaxValue)); } /// <summary> /// Enumerates the values that fall within the range, in descending order (from <see cref="MaxValue"/> to <see cref="MinValue"/>). /// </summary> /// <param name="decrement">The method that determines how to decrement from one value to the next.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains all the values in the range, /// in descending order, as determined by the <paramref name="decrement"/> algorithm.</returns> /// <exception cref="ArgumentNullException"><paramref name="decrement"/> is <b>null</b>.</exception> /// <remarks>If <paramref name="decrement"/> does not move the current value from <see cref="MaxValue"/> towards <see cref="MinValue"/>, /// then this enumeration will result in an infinite loop.</remarks> public IEnumerable<T> EnumerateBackward(Func<T, T> decrement) { if (decrement == null) throw new ArgumentNullException(nameof(decrement)); return Enumerate(MaxValue, decrement, x => x.IsGreaterThanOrEqualTo(MinValue)); } private static IEnumerable<T> Enumerate(T current, Func<T, T> step, Predicate<T> shouldContinue) { do { yield return current; current = step(current); } while (shouldContinue(current)); } } } <file_sep>using System; using System.Linq; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class SyncQueryServiceAdapterTests { private readonly Mock<IAsyncQueryService<FakeEntity<int>, int>> _mockInner = new Mock<IAsyncQueryService<FakeEntity<int>, int>>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new SyncQueryServiceAdapter<FakeEntity<int>, int>(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void GetCount_ShouldCallAsyncMethod_AndReturnResult() { // Arrange const long count = 38; _mockInner .Setup(i => i.GetCountAsync()) .ReturnsAsync(count); var subject = new SyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = subject.GetCount(); // Assert result.Should().Be(count); _mockInner.VerifyAll(); } [Fact] public void GetAll_ShouldCallAsyncMethod_AndReturnResult() { // Arrange var data = Enumerable.Empty<FakeEntity<int>>(); _mockInner .Setup(i => i.GetAllAsync()) .ReturnsAsync(data); var subject = new SyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = subject.GetAll(); // Assert result.Should().BeSameAs(data); _mockInner.VerifyAll(); } [Fact] public void GetById_ShouldCallAsyncMethod_AndReturnResult() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.GetByIdAsync(entity.Id)) .ReturnsAsync(entity); var subject = new SyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var result = subject.GetById(entity.Id); // Assert result.Should().BeSameAs(entity); _mockInner.VerifyAll(); } [Fact] public void TryGetById_ShouldCallAsyncMethod_AndReturnFalse_WhenEntityIsNotFound() { // Arrange const int id = 42; _mockInner .Setup(i => i.TryGetByIdAsync(id)) .ReturnsAsync((FakeEntity<int>)null); var subject = new SyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var success = subject.TryGetById(id, out FakeEntity<int> result); // Assert success.Should().BeFalse(); result.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryGetById_ShouldCallAsyncMethod_AndReturnTrue_WhenEntityIsFound() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryGetByIdAsync(entity.Id)) .ReturnsAsync(entity); var subject = new SyncQueryServiceAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var success = subject.TryGetById(entity.Id, out FakeEntity<int> result); // Assert success.Should().BeTrue(); result.Should().BeSameAs(entity); _mockInner.VerifyAll(); } } } <file_sep>using System; using OnionSeed.Extensions; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IAsyncRepository{T, TId}"/> to work like an <see cref="IRepository{T, TId}"/>. /// </summary> public class SyncRepositoryAdapter<T, TId> : SyncQueryServiceAdapter<T, TId>, IRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="SyncRepositoryAdapter{T, TId}"/> class, /// wrapping the given <see cref="IAsyncRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncRepository{T, TId}"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public SyncRepositoryAdapter(IAsyncRepository<T, TId> inner) : base(inner) { Inner = inner; } /// <summary> /// Gets a reference to the <see cref="IAsyncRepository{T, TId}"/> being decorated. /// </summary> public new IAsyncRepository<T, TId> Inner { get; } /// <inheritdoc/> public void Add(T item) => AsyncExtensions.RunSynchronously(() => Inner.AddAsync(item)); /// <inheritdoc/> public void AddOrUpdate(T item) => AsyncExtensions.RunSynchronously(() => Inner.AddOrUpdateAsync(item)); /// <inheritdoc/> public void Update(T item) => AsyncExtensions.RunSynchronously(() => Inner.UpdateAsync(item)); /// <inheritdoc/> public void Remove(T item) => AsyncExtensions.RunSynchronously(() => Inner.RemoveAsync(item)); /// <inheritdoc/> public void Remove(TId id) => AsyncExtensions.RunSynchronously(() => Inner.RemoveAsync(id)); /// <inheritdoc/> public bool TryAdd(T item) => AsyncExtensions.RunSynchronously(() => Inner.TryAddAsync(item)); /// <inheritdoc/> public bool TryUpdate(T item) => AsyncExtensions.RunSynchronously(() => Inner.TryUpdateAsync(item)); /// <inheritdoc/> public bool TryRemove(T item) => AsyncExtensions.RunSynchronously(() => Inner.TryRemoveAsync(item)); /// <inheritdoc/> public bool TryRemove(TId id) => AsyncExtensions.RunSynchronously(() => Inner.TryRemoveAsync(id)); } } <file_sep>using System; namespace OnionSeed.Extensions { /// <summary> /// Contains extension methods for the <see cref="IComparable"/> and <see cref="IComparable{T}"/> interfaces, to make them more fluent. /// </summary> public static class ComparableExtensions { /// <summary> /// Returns a value indicating whether <paramref name="source"/> is less than <paramref name="other"/>. /// </summary> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is less than <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsLessThan(this IComparable source, object other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) < 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is less than <paramref name="other"/>. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is less than <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsLessThan<T>(this IComparable<T> source, T other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) < 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is less than or equal to <paramref name="other"/>. /// </summary> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is less than or equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsLessThanOrEqualTo(this IComparable source, object other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) <= 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is less than or equal to <paramref name="other"/>. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is less than or equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsLessThanOrEqualTo<T>(this IComparable<T> source, T other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) <= 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is equal to <paramref name="other"/>. /// </summary> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsEqualTo(this IComparable source, object other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) == 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is equal to <paramref name="other"/>. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsEqualTo<T>(this IComparable<T> source, T other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) == 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is greater than or equal to <paramref name="other"/>. /// </summary> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is greater than or equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsGreaterThanOrEqualTo(this IComparable source, object other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) >= 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is greater than or equal to <paramref name="other"/>. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is greater than or equal to <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsGreaterThanOrEqualTo<T>(this IComparable<T> source, T other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) >= 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is greater than <paramref name="other"/>. /// </summary> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is greater than <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsGreaterThan(this IComparable source, object other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) > 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is greater than <paramref name="other"/>. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="other">The other value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is greater than <paramref name="other"/>; otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsGreaterThan<T>(this IComparable<T> source, T other) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.CompareTo(other) > 0; } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is between <paramref name="min"/> and <paramref name="max"/> (inclusive). /// </summary> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is between <paramref name="min"/> and <paramref name="max"/> (inclusive); otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsBetween(this IComparable source, object min, object max) { return IsGreaterThanOrEqualTo(source, min) && IsLessThanOrEqualTo(source, max); } /// <summary> /// Returns a value indicating whether <paramref name="source"/> is between <paramref name="min"/> and <paramref name="max"/> (inclusive). /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><b>true</b> if <paramref name="source"/> is between <paramref name="min"/> and <paramref name="max"/> (inclusive); otherwise, <b>false</b>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static bool IsBetween<T>(this IComparable<T> source, T min, T max) { return IsGreaterThanOrEqualTo(source, min) && IsLessThanOrEqualTo(source, max); } /// <summary> /// Limits the source value to a defined minimum. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="min"/>, if <paramref name="source"/> is less than <paramref name="min"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static object ConstrainToMin<T>(this T source, object min) where T : IComparable { return IsLessThan(source, min) ? min : source; } /// <summary> /// Limits the source value to a defined minimum. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="min"/>, if <paramref name="source"/> is less than <paramref name="min"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static T ConstrainToMin<T>(this T source, T min) where T : IComparable<T> { return IsLessThan(source, min) ? min : source; } /// <summary> /// Limits the source value to a defined maximum. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="max"/>, if <paramref name="source"/> is greater than <paramref name="max"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static object ConstrainToMax<T>(this T source, object max) where T : IComparable { return IsGreaterThan(source, max) ? max : source; } /// <summary> /// Limits the source value to a defined maximum. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="max"/>, if <paramref name="source"/> is greater than <paramref name="max"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static T ConstrainToMax<T>(this T source, T max) where T : IComparable<T> { return IsGreaterThan(source, max) ? max : source; } /// <summary> /// Limits the source value to a defined range. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="min"/> if <paramref name="source"/> is less than <paramref name="min"/>, /// or <paramref name="max"/> if <paramref name="source"/> is greater than <paramref name="max"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static object ConstrainTo<T>(this T source, object min, object max) where T : IComparable { if (IsLessThan(source, min)) return min; return IsGreaterThan(source, max) ? max : source; } /// <summary> /// Limits the source value to a defined range. /// </summary> /// <typeparam name="T">The type of the values being compared.</typeparam> /// <param name="source">The source value.</param> /// <param name="min">The minimum value being compared to <paramref name="source"/>.</param> /// <param name="max">The maximum value being compared to <paramref name="source"/>.</param> /// <returns><paramref name="min"/> if <paramref name="source"/> is less than <paramref name="min"/>, /// or <paramref name="max"/> if <paramref name="source"/> is greater than <paramref name="max"/>; otherwise, <paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <b>null</b>.</exception> public static T ConstrainTo<T>(this T source, T min, T max) where T : IComparable<T> { if (IsLessThan(source, min)) return min; return IsGreaterThan(source, max) ? max : source; } } } <file_sep>using System.Threading.Tasks; namespace OnionSeed.Data { /// <summary> /// Defines an atomic transaction whose changes are to be asynchronously committed as a collective whole. /// </summary> public interface IAsyncUnitOfWork { /// <summary> /// Commits any pending changes. /// </summary> /// <returns>A task representing the operation.</returns> Task CommitAsync(); } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncQueryServiceExceptionHandlerTests { private readonly Mock<IAsyncQueryService<FakeEntity<int>, int>> _mockInner = new Mock<IAsyncQueryService<FakeEntity<int>, int>>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public async Task GetCountAsync_ShouldCallInner_AndReturnResult() { // Arrange const long count = 123; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetCountAsync()) .ReturnsAsync(count); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetCountAsync().ConfigureAwait(false); // Assert result.Should().Be(count); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task GetCountAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange InvalidOperationException exception = null; _mockInner .Setup(i => i.GetCountAsync()) .Returns(ExceptionTask<long>(new InvalidOperationException())); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetCountAsync().ConfigureAwait(false); // Assert result.Should().Be(0); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task GetAllAsync_ShouldCallInner_AndReturnResult() { // Arrange var data = Enumerable.Empty<FakeEntity<int>>(); InvalidOperationException exception = null; _mockInner .Setup(i => i.GetAllAsync()) .ReturnsAsync(data); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetAllAsync().ConfigureAwait(false); // Assert result.Should().BeSameAs(data); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task GetAllAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange InvalidOperationException exception = null; _mockInner .Setup(i => i.GetAllAsync()) .Returns(ExceptionTask<IEnumerable<FakeEntity<int>>>(new InvalidOperationException())); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetAllAsync().ConfigureAwait(false); // Assert result.Should().NotBeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task GetByIdAsync_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetByIdAsync(entity.Id)) .ReturnsAsync(entity); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetByIdAsync(entity.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(entity); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task GetByIdAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.GetByIdAsync(id)) .Returns(ExceptionTask<FakeEntity<int>>(new InvalidOperationException())); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.GetByIdAsync(id).ConfigureAwait(false); // Assert result.Should().BeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryGetByIdAsync_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryGetByIdAsync(entity.Id)) .ReturnsAsync(entity); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryGetByIdAsync(entity.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(entity); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public async Task TryGetByIdAsync_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryGetByIdAsync(entity.Id)) .Returns(ExceptionTask<FakeEntity<int>>(new InvalidOperationException())); var subject = new AsyncQueryServiceExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = await subject.TryGetByIdAsync(entity.Id).ConfigureAwait(false); // Assert result.Should().BeNull(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } private static Task<T> ExceptionTask<T>(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException<T>(ex); #else return Task.FromException<T>(ex); #endif } } } <file_sep>using System; using System.Threading.Tasks; namespace OnionSeed.Factories { /// <inheritdoc/> /// <summary> /// Generates sequential GUID values that can be used as unique identity values for entities. /// </summary> /// <remarks>The GUIDs generated by this class are sequential, which means they can be used as primary keys in a relational database without incurring /// many of the performance hits that would normally come with doing so. The implementation itself encapsulates a strategy by <NAME> on /// <a href="http://www.codeproject.com/Articles/388157/GUIDs-as-fast-primary-keys-under-multiple-database">CodeProject</a>.</remarks> public class SequentialGuidFactory : IFactory<Guid>, IAsyncFactory<Guid> { /// <summary> /// The number of sequential bytes in the GUID. /// </summary> public const int NumberOfSequentialBytes = 6; private const int TotalNumberOfBytes = 16; // Total number of bytes in the GUID private const int NumberOfRandomBytes = TotalNumberOfBytes - NumberOfSequentialBytes; // Number of random bytes in the GUID private const int SequentialOffset = 2; // Only use the least-significant bytes of the 8-byte time stamp private const int NumberOfBytesInData1 = 4; // Size of Data1 block of GUID private const int NumberOfBytesInData2 = 2; // Size of Data2 block of GUID /// <summary> /// Initializes a new instance of the <see cref="SequentialGuidFactory"/> class, which will generate keys as specified by <paramref name="sequentialGuidType"/>. /// </summary> /// <param name="sequentialGuidType">The type of sequential GUID values generated by the current instance.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="sequentialGuidType"/> is not set to a recognized value.</exception> public SequentialGuidFactory(SequentialGuidType sequentialGuidType) { if (!Enum.IsDefined(typeof(SequentialGuidType), sequentialGuidType)) throw new ArgumentOutOfRangeException(nameof(sequentialGuidType)); SequentialGuidType = sequentialGuidType; } /// <summary> /// Gets the type of sequential GUID values generated by the current instance. /// </summary> public SequentialGuidType SequentialGuidType { get; } /// <inheritdoc/> public Guid CreateNew() { var randomBytes = GenerateRandomBytes(); var sequentialBytes = GenerateSequentialBytes(); var guidBytes = new byte[TotalNumberOfBytes]; CombineBytes(randomBytes, sequentialBytes, guidBytes); return new Guid(guidBytes); } /// <inheritdoc/> public Task<Guid> CreateNewAsync() => Task.Run(() => CreateNew()); private static byte[] GenerateRandomBytes() { return Guid.NewGuid().ToByteArray(); } private static byte[] GenerateSequentialBytes() { var timestamp = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; // Returns milliseconds (10 ms resolution) var sequentialBytes = BitConverter.GetBytes(timestamp); if (BitConverter.IsLittleEndian) { Array.Reverse(sequentialBytes); } return sequentialBytes; } private void CombineBytes(byte[] randomBytes, byte[] sequentialBytes, byte[] buffer) { if (SequentialGuidType == SequentialGuidType.SequentialAtEnd) { Buffer.BlockCopy(randomBytes, 0, buffer, 0, NumberOfRandomBytes); Buffer.BlockCopy(sequentialBytes, SequentialOffset, buffer, NumberOfRandomBytes, NumberOfSequentialBytes); } else { Buffer.BlockCopy(sequentialBytes, SequentialOffset, buffer, 0, NumberOfSequentialBytes); Buffer.BlockCopy(randomBytes, 0, buffer, NumberOfSequentialBytes, NumberOfRandomBytes); } // If formatting as a string, we have to reverse the order of the Data1 and Data2 blocks on little-endian systems if (SequentialGuidType == SequentialGuidType.SequentialAsString && BitConverter.IsLittleEndian) { Array.Reverse(buffer, 0, NumberOfBytesInData1); Array.Reverse(buffer, NumberOfBytesInData1, NumberOfBytesInData2); } } } } <file_sep>using System; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class RepositoryExceptionHandlerTests { private readonly Mock<IRepository<FakeEntity<int>, int>> _mockInner = new Mock<IRepository<FakeEntity<int>, int>>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public void Add_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner.Setup(i => i.Add(entity)); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Add(entity); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void Add_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.Add(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Add(entity); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void AddOrUpdate_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner.Setup(i => i.AddOrUpdate(entity)); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.AddOrUpdate(entity); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void AddOrUpdate_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.AddOrUpdate(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.AddOrUpdate(entity); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void Update_ShouldCallInner() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner.Setup(i => i.Update(entity)); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Update(entity); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void Update_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.Update(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Update(entity); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldCallInner_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner.Setup(i => i.Remove(entity)); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Remove(entity); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldInvokeHandle_WhenEntityIsGiven_AndInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.Remove(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Remove(entity); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldCallInner_WhenIdIsGiven() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner.Setup(i => i.Remove(id)); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Remove(id); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldInvokeHandle_WhenIdIsGiven_AndInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.Remove(id)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Remove(id); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void TryAdd_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryAdd(entity)) .Returns(true); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryAdd(entity); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryAdd_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryAdd(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryAdd(entity); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void TryUpdate_ShouldCallInner_AndReturnResult() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryUpdate(entity)) .Returns(true); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryUpdate(entity); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryUpdate_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryUpdate(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryUpdate(entity); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldCallInner_AndReturnResult_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemove(entity)) .Returns(true); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryRemove(entity); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldInvokeHandle_WhenEntityIsGiven_AndInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemove(entity)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryRemove(entity); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldCallInner_AndReturnResult_WhenIdIsGiven() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemove(id)) .Returns(true); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryRemove(id); // Assert result.Should().BeTrue(); exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldInvokeHandle_WhenIdIsGiven_AndInnerThrowsException() { // Arrange const int id = 47; InvalidOperationException exception = null; _mockInner .Setup(i => i.TryRemove(id)) .Throws(new InvalidOperationException()); var subject = new RepositoryExceptionHandler<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act var result = subject.TryRemove(id); // Assert result.Should().BeFalse(); exception.Should().NotBeNull(); _mockInner.VerifyAll(); } } } <file_sep>using System; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Wraps a given <see cref="IAsyncRepository{T, TId}"/> and handles any exceptions of the specified type. /// </summary> public class AsyncRepositoryExceptionHandler<T, TId, TException> : AsyncQueryServiceExceptionHandler<T, TId, TException>, IAsyncRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> where TException : Exception { /// <summary> /// Initializes a new instance of the <see cref="AsyncRepositoryExceptionHandler{T, TId, TException}"/> class, /// decorating the given <see cref="IAsyncRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncRepository{T, TId}"/> to be decorated.</param> /// <param name="handler">The handler that will be called when an exception is caught.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="handler"/> is <c>null</c>.</exception> public AsyncRepositoryExceptionHandler(IAsyncRepository<T, TId> inner, Action<TException> handler) : base(inner, handler) { Inner = inner; } /// <summary> /// Gets a reference to the <see cref="IAsyncRepository{T, TId}"/> being decorated. /// </summary> public new IAsyncRepository<T, TId> Inner { get; } /// <inheritdoc/> public async Task AddAsync(T item) { try { await Inner.AddAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public async Task AddOrUpdateAsync(T item) { try { await Inner.AddOrUpdateAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public async Task UpdateAsync(T item) { try { await Inner.UpdateAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public async Task RemoveAsync(T item) { try { await Inner.RemoveAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public async Task RemoveAsync(TId id) { try { await Inner.RemoveAsync(id).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); } } /// <inheritdoc/> public async Task<bool> TryAddAsync(T item) { try { return await Inner.TryAddAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public async Task<bool> TryUpdateAsync(T item) { try { return await Inner.TryUpdateAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public async Task<bool> TryRemoveAsync(T item) { try { return await Inner.TryRemoveAsync(item).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return false; } } /// <inheritdoc/> public async Task<bool> TryRemoveAsync(TId id) { try { return await Inner.TryRemoveAsync(id).ConfigureAwait(false); } catch (TException ex) { Handler.Invoke(ex); return false; } } } } <file_sep>using System; using System.Threading.Tasks; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IAsyncUnitOfWork"/>. /// </summary> public abstract class AsyncUnitOfWorkDecorator : IAsyncUnitOfWork { /// <summary> /// Initializes a new instance of the <see cref="AsyncUnitOfWorkDecorator"/> class, /// decorating the given <see cref="IAsyncUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncUnitOfWork"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncUnitOfWorkDecorator(IAsyncUnitOfWork inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IAsyncUnitOfWork"/> being decorated. /// </summary> protected IAsyncUnitOfWork Inner { get; } /// <inheritdoc/> public virtual Task CommitAsync() => Inner.CommitAsync(); } } <file_sep>using System; using System.Threading.Tasks; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Decorates an <see cref="IAsyncUnitOfWork"/>, /// mirroring commands to a secondary, "tap" <see cref="IAsyncUnitOfWork"/>. /// </summary> /// <remarks>This decorator functions like a network tap: commands are executed first against the /// inner unit of work; if they succeed, they are then executed against the tap unit of work as well. /// Queries are only executed against the inner unit of work, and anything returned from the tap unit of work is ignored. /// <para>This essentially allows for the creation of a duplicate copy of the data, /// and is intended to be used for things like caching, backup, or reporting.</para></remarks> public class AsyncUnitOfWorkTap : AsyncUnitOfWorkDecorator { /// <summary> /// Initializes a new instance of the <see cref="AsyncUnitOfWorkTap"/> class, /// using the given units of work. /// </summary> /// <param name="inner">The <see cref="IAsyncUnitOfWork"/> to be decorated.</param> /// <param name="tap">The tap unit of work, where commands will be duplicated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>. /// -or- <paramref name="tap"/> is <c>null</c>.</exception> public AsyncUnitOfWorkTap(IAsyncUnitOfWork inner, IAsyncUnitOfWork tap) : base(inner) { Tap = tap ?? throw new ArgumentNullException(nameof(tap)); } /// <summary> /// Gets a reference to the tap unit of work. /// </summary> public IAsyncUnitOfWork Tap { get; } /// <inheritdoc/> public override async Task CommitAsync() { await Inner.CommitAsync().ConfigureAwait(false); await Tap.CommitAsync().ConfigureAwait(false); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncUnitOfWorkTapTests { private readonly Mock<IAsyncUnitOfWork> _mockMain = new Mock<IAsyncUnitOfWork>(MockBehavior.Strict); private readonly Mock<IAsyncUnitOfWork> _mockTap = new Mock<IAsyncUnitOfWork>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeMain, bool includeTap) { // Arrange var main = includeMain ? _mockMain.Object : null; var tap = includeTap ? _mockTap.Object : null; // Act Action action = () => new AsyncUnitOfWorkTap(main, tap); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void CommitAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange _mockMain .Setup(r => r.CommitAsync()) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncUnitOfWorkTap(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.CommitAsync().ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task CommitAsync_ShouldCallMain_AndTap() { // Arrange _mockMain .Setup(r => r.CommitAsync()) .Returns(CompletedTask()); _mockTap .Setup(r => r.CommitAsync()) .Returns(CompletedTask()); var subject = new AsyncUnitOfWorkTap(_mockMain.Object, _mockTap.Object); // Act await subject.CommitAsync().ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } private static Task ExceptionTask(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException(ex); #else return Task.FromException(ex); #endif } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>using System; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IAsyncRepository{T, TId}"/>. /// </summary> public abstract class AsyncRepositoryDecorator<T, TId> : AsyncQueryServiceDecorator<T, TId>, IAsyncRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="AsyncRepositoryDecorator{T, TId}"/> class, /// decorating the given <see cref="IAsyncRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncRepository{T, TId}"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncRepositoryDecorator(IAsyncRepository<T, TId> inner) : base(inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IAsyncRepository{T, TId}"/> being decorated. /// </summary> protected new IAsyncRepository<T, TId> Inner { get; } /// <inheritdoc/> public virtual Task AddAsync(T item) => Inner.AddAsync(item); /// <inheritdoc/> public virtual Task AddOrUpdateAsync(T item) => Inner.AddOrUpdateAsync(item); /// <inheritdoc/> public virtual Task UpdateAsync(T item) => Inner.UpdateAsync(item); /// <inheritdoc/> public virtual Task RemoveAsync(T item) => Inner.RemoveAsync(item); /// <inheritdoc/> public virtual Task RemoveAsync(TId id) => Inner.RemoveAsync(id); /// <inheritdoc/> public virtual Task<bool> TryAddAsync(T item) => Inner.TryAddAsync(item); /// <inheritdoc/> public virtual Task<bool> TryUpdateAsync(T item) => Inner.TryUpdateAsync(item); /// <inheritdoc/> public virtual Task<bool> TryRemoveAsync(T item) => Inner.TryRemoveAsync(item); /// <inheritdoc/> public virtual Task<bool> TryRemoveAsync(TId id) => Inner.TryRemoveAsync(id); } } <file_sep>#if STATIC_TASKS using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; namespace OnionSeed { /// <summary> /// Contains static helpers for <see cref="Task"/>. /// </summary> [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public static class TaskHelpers { /// <summary> /// Gets a task that's already been completed successfully. /// </summary> public static Task CompletedTask { get; } = Task.FromResult(0); /// <summary>Creates a <see cref="Task"/> that's completed exceptionally with the specified exception.</summary> /// <param name="exception">The exception with which to complete the task.</param> /// <returns>The faulted task.</returns> /// <exception cref="ArgumentNullException"><paramref name="exception"/> is <c>null</c>.</exception> public static Task FromException(Exception exception) { return FromException<int>(exception); } /// <summary>Creates a <see cref="Task{TResult}"/> that's completed exceptionally with the specified exception.</summary> /// <typeparam name="TResult">The type of the result returned by the task.</typeparam> /// <param name="exception">The exception with which to complete the task.</param> /// <returns>The faulted task.</returns> /// <exception cref="ArgumentNullException"><paramref name="exception"/> is <c>null</c>.</exception> public static Task<TResult> FromException<TResult>(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); var source = new TaskCompletionSource<TResult>(); source.SetException(exception); return source.Task; } } } #endif <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class SyncRepositoryAdapterTests { private readonly Mock<IAsyncRepository<FakeEntity<int>, int>> _mockInner = new Mock<IAsyncRepository<FakeEntity<int>, int>>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new SyncRepositoryAdapter<FakeEntity<int>, int>(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Add_ShouldCallAsyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.AddAsync(entity)) .Returns(CompletedTask()); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act subject.Add(entity); // Assert _mockInner.VerifyAll(); } [Fact] public void AddOrUpdate_ShouldCallAsyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.AddOrUpdateAsync(entity)) .Returns(CompletedTask()); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act subject.AddOrUpdate(entity); // Assert _mockInner.VerifyAll(); } [Fact] public void Update_ShouldCallAsyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.UpdateAsync(entity)) .Returns(CompletedTask()); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act subject.Update(entity); // Assert _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldCallAsyncMethod_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.RemoveAsync(entity)) .Returns(CompletedTask()); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act subject.Remove(entity); // Assert _mockInner.VerifyAll(); } [Fact] public void Remove_ShouldCallAsyncMethod_WhenIdIsGiven() { // Arrange const int id = 42; _mockInner .Setup(i => i.RemoveAsync(id)) .Returns(CompletedTask()); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act subject.Remove(id); // Assert _mockInner.VerifyAll(); } [Fact] public void TryAdd_ShouldCallAsyncMethod() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryAddAsync(entity)) .ReturnsAsync(expected); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = subject.TryAdd(entity); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public void TryUpdate_ShouldCallAsyncMethod() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryUpdateAsync(entity)) .ReturnsAsync(expected); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = subject.TryUpdate(entity); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldCallAsyncMethod_WhenEntityIsGiven() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryRemoveAsync(entity)) .ReturnsAsync(expected); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = subject.TryRemove(entity); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public void TryRemove_ShouldCallAsyncMethod_WhenIdIsGiven() { // Arrange const bool expected = true; const int id = 42; _mockInner .Setup(i => i.TryRemoveAsync(id)) .ReturnsAsync(expected); var subject = new SyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = subject.TryRemove(id); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>using System; using System.Collections.Generic; using OnionSeed.Extensions; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IAsyncQueryService{T, TId}"/> to work like an <see cref="IQueryService{T, TId}"/>. /// </summary> public class SyncQueryServiceAdapter<T, TId> : AsyncQueryServiceDecorator<T, TId>, IQueryService<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="SyncQueryServiceAdapter{T, TId}"/> class, /// wrapping the given <see cref="IAsyncQueryService{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IAsyncQueryService{T, TId}"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public SyncQueryServiceAdapter(IAsyncQueryService<T, TId> inner) : base(inner) { } /// <inheritdoc/> public long GetCount() => AsyncExtensions.RunSynchronously(() => Inner.GetCountAsync()); /// <inheritdoc/> public IEnumerable<T> GetAll() => AsyncExtensions.RunSynchronously(() => Inner.GetAllAsync()); /// <inheritdoc/> public T GetById(TId id) => AsyncExtensions.RunSynchronously(() => Inner.GetByIdAsync(id)); /// <inheritdoc/> public bool TryGetById(TId id, out T result) { result = AsyncExtensions.RunSynchronously(() => Inner.TryGetByIdAsync(id)); return !Equals(result, default(T)); } } } <file_sep>using System; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { public class UnitOfWorkExceptionHandlerTests { private readonly Mock<IUnitOfWork> _mockInner = new Mock<IUnitOfWork>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeHandler) { // Arrange var inner = includeInner ? _mockInner.Object : null; var handler = includeHandler ? (Exception ex) => { } : (Action<Exception>)null; // Act Action action = () => new UnitOfWorkExceptionHandler<InvalidOperationException>(inner, handler); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); } [Fact] public void Commit_ShouldCallInner() { // Arrange InvalidOperationException exception = null; _mockInner.Setup(i => i.Commit()); var subject = new UnitOfWorkExceptionHandler<InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Commit(); // Assert exception.Should().BeNull(); _mockInner.VerifyAll(); } [Fact] public void Commit_ShouldInvokeHandle_WhenInnerThrowsException() { // Arrange var entity = new FakeEntity<int>() { Id = 47 }; InvalidOperationException exception = null; _mockInner .Setup(i => i.Commit()) .Throws(new InvalidOperationException()); var subject = new UnitOfWorkExceptionHandler<InvalidOperationException>(_mockInner.Object, ex => exception = ex); // Act subject.Commit(); // Assert exception.Should().NotBeNull(); _mockInner.VerifyAll(); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncRepositoryAdapterTests { private readonly Mock<IRepository<FakeEntity<int>, int>> _mockInner = new Mock<IRepository<FakeEntity<int>, int>>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new AsyncRepositoryAdapter<FakeEntity<int>, int>(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public async Task AddAsync_ShouldCallSyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner.Setup(i => i.Add(entity)); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act await subject.AddAsync(entity).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } [Fact] public async Task AddOrUpdateAsync_ShouldCallSyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner.Setup(i => i.AddOrUpdate(entity)); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act await subject.AddOrUpdateAsync(entity).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } [Fact] public async Task UpdateAsync_ShouldCallSyncMethod() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner.Setup(i => i.Update(entity)); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act await subject.UpdateAsync(entity).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallSyncMethod_WhenEntityIsGiven() { // Arrange var entity = new FakeEntity<int> { Id = 42 }; _mockInner.Setup(i => i.Remove(entity)); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act await subject.RemoveAsync(entity).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallSyncMethod_WhenIdIsGiven() { // Arrange const int id = 42; _mockInner.Setup(i => i.Remove(id)); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); } [Fact] public async Task TryAddAsync_ShouldCallSyncMethod_AndReturnResult() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryAdd(entity)) .Returns(expected); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = await subject.TryAddAsync(entity).ConfigureAwait(false); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public async Task TryUpdateAsync_ShouldCallSyncMethod_AndReturnResult() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryUpdate(entity)) .Returns(expected); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = await subject.TryUpdateAsync(entity).ConfigureAwait(false); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallSyncMethod_AndReturnResult_WhenEntityIsGiven() { // Arrange const bool expected = true; var entity = new FakeEntity<int> { Id = 42 }; _mockInner .Setup(i => i.TryRemove(entity)) .Returns(expected); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = await subject.TryRemoveAsync(entity).ConfigureAwait(false); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallSyncMethod_AndReturnResult_WhenIdIsGiven() { // Arrange const bool expected = true; const int id = 42; _mockInner .Setup(i => i.TryRemove(id)) .Returns(expected); var subject = new AsyncRepositoryAdapter<FakeEntity<int>, int>(_mockInner.Object); // Act var actual = await subject.TryRemoveAsync(id).ConfigureAwait(false); // Assert actual.Should().Be(expected); _mockInner.VerifyAll(); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncRepositoryTapTests { private readonly Mock<IAsyncRepository<FakeEntity<int>, int>> _mockMain = new Mock<IAsyncRepository<FakeEntity<int>, int>>(MockBehavior.Strict); private readonly Mock<IAsyncRepository<FakeEntity<int>, int>> _mockTap = new Mock<IAsyncRepository<FakeEntity<int>, int>>(MockBehavior.Strict); private readonly List<FakeEntity<int>> _data = new List<FakeEntity<int>> { new FakeEntity<int> { Id = 1, Name = "Bill" }, new FakeEntity<int> { Id = 2, Name = "Jane" }, new FakeEntity<int> { Id = 3, Name = "Jake" }, new FakeEntity<int> { Id = 4, Name = "Megan" } }; [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeMain, bool includeTap) { // Arrange var main = includeMain ? _mockMain.Object : null; var tap = includeTap ? _mockTap.Object : null; // Act Action action = () => new AsyncRepositoryTap<FakeEntity<int>, int>(main, tap); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public async Task GetCountAsync_ShouldCallMain_AndReturnResult() { // Arrange _mockMain .Setup(r => r.GetCountAsync()) .Returns(Task.FromResult<long>(_data.Count)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.GetCountAsync().ConfigureAwait(false); // Assert result.Should().Be(_data.Count); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task GetAllAsync_ShouldCallMain_AndReturnResult() { // Arrange _mockMain .Setup(r => r.GetAllAsync()) .Returns(Task.FromResult<IEnumerable<FakeEntity<int>>>(_data)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.GetAllAsync().ConfigureAwait(false); // Assert result.Should().BeSameAs(_data); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task GetByIdAsync_ShouldCallMain_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.GetByIdAsync(person.Id)) .Returns(Task.FromResult(person)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.GetByIdAsync(person.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(person); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryGetByIdAsync_ShouldCallMain_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryGetByIdAsync(person.Id)) .Returns(Task.FromResult(person)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryGetByIdAsync(person.Id).ConfigureAwait(false); // Assert result.Should().BeSameAs(person); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void AddAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.AddAsync(person)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.AddAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task AddAsync_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.AddAsync(person)) .Returns(CompletedTask()); _mockTap .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act await subject.AddAsync(person).ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void AddOrUpdateAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.AddOrUpdateAsync(person)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.AddOrUpdateAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task AddOrUpdateAsync_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); _mockTap .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act await subject.AddOrUpdateAsync(person).ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void UpdateAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.UpdateAsync(person)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.UpdateAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task UpdateAsync_ShouldCallMain_AndTap() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.UpdateAsync(person)) .Returns(CompletedTask()); _mockTap .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act await subject.UpdateAsync(person).ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void RemoveAsync_ShouldSkipTap_WhenEntityIsGiven_AndMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.RemoveAsync(person)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.RemoveAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallMain_AndTap_WhenEntityIsGiven() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.RemoveAsync(person)) .Returns(CompletedTask()); _mockTap .Setup(r => r.RemoveAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act await subject.RemoveAsync(person).ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void RemoveAsync_ShouldSkipTap_WhenIdIsGiven_AndMainThrowsException() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.RemoveAsync(id)) .Returns(ExceptionTask(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.RemoveAsync(id).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task RemoveAsync_ShouldCallMain_AndTap_WhenIdIsGiven() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.RemoveAsync(id)) .Returns(CompletedTask()); _mockTap .Setup(r => r.RemoveAsync(id)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryAddAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAddAsync(person)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.TryAddAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryAddAsync_ShouldSkipTap_WhenMainReturnsFalse() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAddAsync(person)) .Returns(Task.FromResult(false)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryAddAsync(person).ConfigureAwait(false); // Assert result.Should().BeFalse(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryAddAsync_ShouldCallMain_AndTap_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryAddAsync(person)) .Returns(Task.FromResult(true)); _mockTap .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryAddAsync(person).ConfigureAwait(false); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryUpdateAsync_ShouldSkipTap_WhenMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdateAsync(person)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.TryUpdateAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryUpdateAsync_ShouldSkipTap_WhenMainReturnsFalse() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdateAsync(person)) .Returns(Task.FromResult(false)); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryUpdateAsync(person).ConfigureAwait(false); // Assert result.Should().BeFalse(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryUpdateAsync_ShouldCallMain_AndTap_AndReturnResult() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryUpdateAsync(person)) .Returns(Task.FromResult(true)); _mockTap .Setup(r => r.AddOrUpdateAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryUpdateAsync(person).ConfigureAwait(false); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemoveAsync_ShouldSkipTap_WhenEntityIsGiven_AndMainThrowsException() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryRemoveAsync(person)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.TryRemoveAsync(person).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallMain_AndTap_AndReturnResult_WhenEntityIsGiven() { // Arrange var person = _data[1]; _mockMain .Setup(r => r.TryRemoveAsync(person)) .Returns(Task.FromResult(true)); _mockTap .Setup(r => r.RemoveAsync(person)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryRemoveAsync(person).ConfigureAwait(false); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public void TryRemoveAsync_ShouldSkipTap_WhenIdIsGiven_AndMainThrowsException() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.TryRemoveAsync(id)) .Returns(ExceptionTask<bool>(new InvalidOperationException())); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act Func<Task> action = async () => await subject.TryRemoveAsync(id).ConfigureAwait(false); // Assert action.Should().Throw<InvalidOperationException>(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } [Fact] public async Task TryRemoveAsync_ShouldCallMain_AndTap_AndReturnResult_WhenIdIsGiven() { // Arrange var id = _data[1].Id; _mockMain .Setup(r => r.TryRemoveAsync(id)) .Returns(Task.FromResult(true)); _mockTap .Setup(r => r.RemoveAsync(id)) .Returns(CompletedTask()); var subject = new AsyncRepositoryTap<FakeEntity<int>, int>(_mockMain.Object, _mockTap.Object); // Act var result = await subject.TryRemoveAsync(id).ConfigureAwait(false); // Assert result.Should().BeTrue(); _mockMain.VerifyAll(); _mockTap.VerifyAll(); } private static Task ExceptionTask(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException(ex); #else return Task.FromException(ex); #endif } private static Task<T> ExceptionTask<T>(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException<T>(ex); #else return Task.FromException<T>(ex); #endif } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class SyncUnitOfWorkAdapterTests { private readonly Mock<IAsyncUnitOfWork> _mockInner = new Mock<IAsyncUnitOfWork>(MockBehavior.Strict); [Fact] public void Constructor_ShouldThrowException_WhenInnerIsNull() { // Act Action action = () => new SyncUnitOfWorkAdapter(null); // Assert action.Should().Throw<ArgumentNullException>(); } [Fact] public void Commit_ShouldCallAsyncMethod() { // Arrange _mockInner .Setup(i => i.CommitAsync()) .Returns(CompletedTask()); var subject = new SyncUnitOfWorkAdapter(_mockInner.Object); // Act subject.Commit(); // Assert _mockInner.VerifyAll(); } private static Task CompletedTask() { #if STATIC_TASKS return TaskHelpers.CompletedTask; #else return Task.CompletedTask; #endif } } } <file_sep>using System; using System.Threading.Tasks; namespace OnionSeed.Factories { /// <inheritdoc/> /// <summary> /// Generates random GUID values that can be used as unique identity values for entities. /// </summary> public class GuidFactory : IFactory<Guid>, IAsyncFactory<Guid> { /// <inheritdoc/> public Guid CreateNew() => Guid.NewGuid(); /// <inheritdoc/> public Task<Guid> CreateNewAsync() => Task.FromResult(Guid.NewGuid()); } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IQueryService{T, TId}"/> to work like an <see cref="IAsyncQueryService{T, TId}"/>. /// </summary> public class AsyncQueryServiceAdapter<T, TId> : QueryServiceDecorator<T, TId>, IAsyncQueryService<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="AsyncQueryServiceAdapter{T, TId}"/> class, /// wrapping the given <see cref="IQueryService{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IQueryService{T, TId}"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncQueryServiceAdapter(IQueryService<T, TId> inner) : base(inner) { } /// <inheritdoc/> public Task<long> GetCountAsync() => Task.Run(() => Inner.GetCount()); /// <inheritdoc/> public Task<IEnumerable<T>> GetAllAsync() => Task.Run(() => Inner.GetAll()); /// <inheritdoc/> public Task<T> GetByIdAsync(TId id) => Task.Run(() => Inner.GetById(id)); /// <inheritdoc/> public Task<T> TryGetByIdAsync(TId id) => Task.Run(() => Inner.TryGetById(id, out T result) ? result : default(T)); } } <file_sep>using System; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// The base class for decorators for <see cref="IUnitOfWork"/>. /// </summary> public abstract class UnitOfWorkDecorator : IUnitOfWork { /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkDecorator"/> class, /// decorating the given <see cref="IUnitOfWork"/>. /// </summary> /// <param name="inner">The <see cref="IUnitOfWork"/> to be decorated.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public UnitOfWorkDecorator(IUnitOfWork inner) { Inner = inner ?? throw new ArgumentNullException(nameof(inner)); } /// <summary> /// Gets a reference to the <see cref="IUnitOfWork"/> being decorated. /// </summary> protected IUnitOfWork Inner { get; } /// <inheritdoc/> public virtual void Commit() => Inner.Commit(); } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace OnionSeed.Factories { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Tests don't need to end in 'Async'.")] public class GuidFactoryTests { private const int TestIterations = 1000000; [Fact] public void CreateNew_ShouldReturnNewGuid_WithoutCollisions() { // Arrange var uniqueResults = new HashSet<Guid>(); var subject = new GuidFactory(); for (var i = 0; i < TestIterations; i++) { // Act var result = subject.CreateNew(); // Assert uniqueResults.Add(result).Should().BeTrue(); } uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); } [Fact] public async Task CreateNewAsync_ShouldReturnNewGuid_WithoutCollisions() { // Arrange var tasks = new Task<Guid>[TestIterations]; var subject = new GuidFactory(); for (var i = 0; i < TestIterations; i++) { // Act tasks[i] = subject.CreateNewAsync(); } // Assert await Task.WhenAll(tasks).ConfigureAwait(false); var uniqueResults = new HashSet<Guid>(tasks.Select(t => t.Result)); uniqueResults.Should().HaveCount(TestIterations); uniqueResults.Should().NotContain(Guid.Empty); } } } <file_sep>using System; using System.Threading.Tasks; using OnionSeed.Types; namespace OnionSeed.Data { /// <inheritdoc/> /// <summary> /// Adapts an <see cref="IRepository{T, TId}"/> to work like an <see cref="IAsyncRepository{T, TId}"/>. /// </summary> public class AsyncRepositoryAdapter<T, TId> : AsyncQueryServiceAdapter<T, TId>, IAsyncRepository<T, TId> where T : IEntity<TId> where TId : IEquatable<TId>, IComparable<TId> { /// <summary> /// Initializes a new instance of the <see cref="AsyncRepositoryAdapter{T, TId}"/> class, /// wrapping the given <see cref="IRepository{T, TId}"/>. /// </summary> /// <param name="inner">The <see cref="IRepository{T, TId}"/> to be wrapped.</param> /// <exception cref="ArgumentNullException"><paramref name="inner"/> is <c>null</c>.</exception> public AsyncRepositoryAdapter(IRepository<T, TId> inner) : base(inner) { Inner = inner; } /// <summary> /// Gets a reference to the <see cref="IRepository{T, TId}"/> being decorated. /// </summary> public new IRepository<T, TId> Inner { get; } /// <inheritdoc/> public Task AddAsync(T item) => Task.Run(() => Inner.Add(item)); /// <inheritdoc/> public Task AddOrUpdateAsync(T item) => Task.Run(() => Inner.AddOrUpdate(item)); /// <inheritdoc/> public Task UpdateAsync(T item) => Task.Run(() => Inner.Update(item)); /// <inheritdoc/> public Task RemoveAsync(T item) => Task.Run(() => Inner.Remove(item)); /// <inheritdoc/> public Task RemoveAsync(TId id) => Task.Run(() => Inner.Remove(id)); /// <inheritdoc/> public Task<bool> TryAddAsync(T item) => Task.Run(() => Inner.TryAdd(item)); /// <inheritdoc/> public Task<bool> TryUpdateAsync(T item) => Task.Run(() => Inner.TryUpdate(item)); /// <inheritdoc/> public Task<bool> TryRemoveAsync(T item) => Task.Run(() => Inner.TryRemove(item)); /// <inheritdoc/> public Task<bool> TryRemoveAsync(TId id) => Task.Run(() => Inner.TryRemove(id)); } } <file_sep>using System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Internal; namespace OnionSeed.Extensions { /// <summary> /// Contains extension methods for the <see cref="ILogger"/> type. /// </summary> /// <remarks>This code is a partial extraction from the Microsoft.Extensions.Logging package for .NET Core 2.1, here: /// https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions.cs /// Once .NET Core 2.1 is released, this should be filtered out.</remarks> public static class LoggerExtensions { private static readonly Func<object, Exception, string> _messageFormatter = MessageFormatter; /// <summary> /// Formats and writes a log message at the specified log level. /// </summary> /// <param name="logger">The <see cref="ILogger"/> to write to.</param> /// <param name="logLevel">Entry will be written on this level.</param> /// <param name="message">Format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> public static void Log(this ILogger logger, LogLevel logLevel, string message, params object[] args) { logger.Log(logLevel, 0, null, message, args); } /// <summary> /// Formats and writes a log message at the specified log level. /// </summary> /// <param name="logger">The <see cref="ILogger"/> to write to.</param> /// <param name="logLevel">Entry will be written on this level.</param> /// <param name="eventId">The event id associated with the log.</param> /// <param name="message">Format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string message, params object[] args) { logger.Log(logLevel, eventId, null, message, args); } /// <summary> /// Formats and writes a log message at the specified log level. /// </summary> /// <param name="logger">The <see cref="ILogger"/> to write to.</param> /// <param name="logLevel">Entry will be written on this level.</param> /// <param name="exception">The exception to log.</param> /// <param name="message">Format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> public static void Log(this ILogger logger, LogLevel logLevel, Exception exception, string message, params object[] args) { logger.Log(logLevel, 0, exception, message, args); } /// <summary> /// Formats and writes a log message at the specified log level. /// </summary> /// <param name="logger">The <see cref="ILogger"/> to write to.</param> /// <param name="logLevel">Entry will be written on this level.</param> /// <param name="eventId">The event id associated with the log.</param> /// <param name="exception">The exception to log.</param> /// <param name="message">Format string of the log message.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } private static string MessageFormatter(object state, Exception error) { return state.ToString(); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Internal; using Moq; using Xunit; namespace OnionSeed.Data { [SuppressMessage("AsyncUsage.CSharp.Naming", "UseAsyncSuffix:Use Async suffix", Justification = "Test methods don't need to end in 'Async'.")] public class AsyncRepositoryExceptionLoggerTests { private readonly Mock<IAsyncRepository<FakeEntity<int>, int>> _mockInner = new Mock<IAsyncRepository<FakeEntity<int>, int>>(MockBehavior.Strict); private readonly Mock<ILogger> _mockLogger = new Mock<ILogger>(MockBehavior.Strict); [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger() { // Arrange const int id = 37; _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(LogLevel.Error, 0, It.IsAny<object>(), It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenMessageIsGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, "Test"); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenMessageIsGiven() { // Arrange const int id = 37; const string message = "inside {0}"; const string arg = "out"; var formattedMessage = new FormattedLogValues(message, arg); _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(LogLevel.Error, 0, formattedMessage, It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, message, arg); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenLogLevelIsGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, LogLevel.Debug); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenLogLevelIsGiven() { // Arrange const int id = 37; const LogLevel logLevel = LogLevel.Debug; _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(logLevel, 0, It.IsAny<object>(), It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, logLevel); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenLogLevelAndMessageAreGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, LogLevel.Debug, "Test"); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenLogLevelAndMessageAreGiven() { // Arrange const int id = 37; const LogLevel logLevel = LogLevel.Debug; const string message = "inside {0}"; const string arg = "out"; var formattedMessage = new FormattedLogValues(message, arg); _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(logLevel, 0, formattedMessage, It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, logLevel, message, arg); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenEventIdIsGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, 5); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenEventIdIsGiven() { // Arrange const int id = 37; const int eventId = 5; _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(LogLevel.Error, eventId, It.IsAny<object>(), It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, eventId); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenEventIdAndMessageAreGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, 5, "Test"); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenEventIdAndMessageAreGiven() { // Arrange const int id = 37; const int eventId = 5; const string message = "inside {0}"; const string arg = "out"; var formattedMessage = new FormattedLogValues(message, arg); _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(LogLevel.Error, eventId, formattedMessage, It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, eventId, message, arg); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenLogLevelAndEventIdAreGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, LogLevel.Debug, 5); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenLogLevelAndEventIdAreGiven() { // Arrange const int id = 37; const LogLevel logLevel = LogLevel.Debug; const int eventId = 5; _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(logLevel, eventId, It.IsAny<object>(), It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, logLevel, eventId); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] public void Constructor_ShouldValidateParameters_WhenLogLevelAndEventIdAndMessageAreGiven(bool includeInner, bool includeLogger) { // Arrange var inner = includeInner ? _mockInner.Object : null; var logger = includeLogger ? _mockLogger.Object : null; // Act Action action = () => new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(inner, logger, LogLevel.Debug, 5, "Test"); // Arrange action.Should().Throw<ArgumentNullException>(); _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } [Fact] public async Task Constructor_ShouldSetUpExceptionLogger_WhenLogLevelAndEventIdAndMessageAreGiven() { // Arrange const int id = 37; const LogLevel logLevel = LogLevel.Debug; const int eventId = 5; const string message = "inside {0}"; const string arg = "out"; var formattedMessage = new FormattedLogValues(message, arg); _mockInner .Setup(s => s.RemoveAsync(id)) .Returns(ExceptionTask<long>(new InvalidOperationException())); _mockLogger .Setup(l => l.Log(logLevel, eventId, formattedMessage, It.IsAny<InvalidOperationException>(), It.IsAny<Func<object, Exception, string>>())); var subject = new AsyncRepositoryExceptionLogger<FakeEntity<int>, int, InvalidOperationException>(_mockInner.Object, _mockLogger.Object, logLevel, eventId, message, arg); // Act await subject.RemoveAsync(id).ConfigureAwait(false); // Assert _mockInner.VerifyAll(); _mockLogger.VerifyAll(); } private static Task<T> ExceptionTask<T>(Exception ex) { #if STATIC_TASKS return TaskHelpers.FromException<T>(ex); #else return Task.FromException<T>(ex); #endif } } }
635bc02e4486381901f6beede76e1627d4055968
[ "Markdown", "C#" ]
64
C#
TaffarelJr/OnionSeed
2f317a752ff3227b60146ef3e6181a612ff5a6be
b2cd63c012a9fff6ec1b4bbe93a957b5b8082f27
refs/heads/master
<file_sep>// // ZombieGridCellTypes.h // Zombies_Leveler // // Created by <NAME> on 6/03/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // typedef NSInteger ZombieCellType; enum { ZombieCell_EmptyCell, ZombieCell_Player1SpawnPoint, ZombieCell_Player2SpawnPoint, ZombieCell_Player3SpawnPoint, ZombieCell_Player4SpawnPoint, ZombieCell_ZombieGroup1SpawnPoint, ZombieCell_ZombieGroup2SpawnPoint, ZombieCell_ZombieGroup3SpawnPoint, ZombieCell_ZombieGroup4SpawnPoint };
a2d9028d171770c3cfbb7e585fbd0641c5f169f8
[ "C" ]
1
C
nshgraph/iOS_Prj1_LevelMaker
70b0785c3b423d0ea4ffc9e61f7faf15d5570344
59273aacfd3d80a0924901efa186dde65ad344c4
refs/heads/master
<file_sep>package com.user.reg.web.dto; import org.springframework.web.multipart.MultipartFile; public class UserDTO { private String name; private String sex; private String contact; private String email; private int zip; private String address; private String hobbies; private String qualification; private String dob; private MultipartFile imageFile; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getZip() { return zip; } public void setZip(int zip) { this.zip = zip; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getHobbies() { return hobbies; } public void setHobbies(String hobbies) { this.hobbies = hobbies; } public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification = qualification; } public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } public MultipartFile getImageFile() { return imageFile; } public void setImageFile(MultipartFile imageFile) { this.imageFile = imageFile; } @Override public String toString() { return "UserDTO [name=" + name + ", sex=" + sex + ", contact=" + contact + ", email=" + email + ", zip=" + zip + ", address=" + address + ", hobbies=" + hobbies + ", qualification=" + qualification + ", dob=" + dob + ", imageFile=" + imageFile + "]"; } } <file_sep>package com.user.reg.web.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.user.reg.web.dto.UserDTO; import com.user.reg.web.service.UserServices; @Controller public class UserController { @Autowired private UserServices services; @RequestMapping(value = "/saveUser", method = RequestMethod.POST) public String register(Model model, @ModelAttribute("userDTO") UserDTO userDTO) { String message = services.SaveUser(userDTO); model.addAttribute("message", message); return "registeration"; } @RequestMapping(value = "/getUsers", method = RequestMethod.GET) public String getUsers(Model model) { List<UserDTO> users = services.getUserInfo(); model.addAttribute("users", users); return "users"; } } <file_sep>package com.user.reg.web.dao; import java.util.List; import com.user.reg.web.model.UserModel; public interface UserDao { public void saveUser(UserModel userModel); public List<UserModel> getUser(); public List<UserModel> getUsers(); } <file_sep># User-registration-mvc Save images and fetch all records used hibernate join <file_sep>package com.user.reg.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @Import(DBHibernateConfiguration.class) @ComponentScan(basePackages = "com.user.reg.web.*") public class WebComponentApplicationConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/*").addResourceLocations("/"); } @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(1); registry.viewResolver(viewResolver); } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver vResolver = new CommonsMultipartResolver(); vResolver.setMaxUploadSize(1000000); vResolver.setDefaultEncoding("utf-8"); return vResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("registeration"); } } <file_sep>package com.user.reg.web.dao; import java.io.IOException; import java.sql.Blob; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.web.multipart.MultipartFile; import com.user.reg.web.model.UserModel; @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory factory; public void saveUser(UserModel userModel) { getSession().save(userModel); } private Session getSession() { Session session = factory.getCurrentSession(); if (session == null) { session = factory.openSession(); } return session; } public Blob getImageBlob(MultipartFile file) { Blob blob = null; try { blob = Hibernate.getLobCreator(getSession()).createBlob( file.getInputStream(), 0); } catch (IOException e) { e.printStackTrace(); } return blob; } /* This method will return all of user and image */ @SuppressWarnings("unchecked") public List<UserModel> getUser() { final String HQL_JOIN = "select a.imageFile, u.name,u.sex,u.contact,u.email,u.address,u.zip,u.hobbies,u.qualification,u.d from user_table u, attachment_table a where u.USERID=u.user_attach_fk"; return getSession().createSQLQuery(HQL_JOIN).list(); } @SuppressWarnings("unchecked") @Override public List<UserModel> getUsers() { return getSession().createCriteria(UserModel.class).list(); } } <file_sep>package com.user.reg.web.model; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "User_Table") public class UserModel { @Id @GenericGenerator(name = "uid", strategy = "increment") @GeneratedValue(generator = "uid") @Column(name = "USERID") private int id; private String name; private String sex; private String contact; private String email; private int zip; private String address; private String hobbies; private String qualification; @Column(name="d") private Date date; @ManyToOne(targetEntity = AttachmentModel.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "user_attach_fk", referencedColumnName = "attachmentId") private AttachmentModel attachmentModel; public UserModel(String name, String sex, String contact, String email, int zip, String address, String hobbies, String qualification, Date date) { this.name = name; this.sex = sex; this.contact = contact; this.email = email; this.zip = zip; this.address = address; this.hobbies = hobbies; this.qualification = qualification; this.date = date; } public UserModel() { /* * Here i used constructor for easy mapping but it's not recommended * always getter and setter is preferable */ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getZip() { return zip; } public void setZip(int zip) { this.zip = zip; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getHobbies() { return hobbies; } public void setHobbies(String hobbies) { this.hobbies = hobbies; } public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification = qualification; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public AttachmentModel getAttachmentModel() { return attachmentModel; } public void setAttachmentModel(AttachmentModel attachmentModel) { this.attachmentModel = attachmentModel; } } <file_sep>package com.user.reg.web.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.user.reg.web.dao.UserDao; import com.user.reg.web.dto.UserDTO; import com.user.reg.web.util.UserUtility; @Service @Transactional public class UserServices { @Autowired private UserDao dao; @Autowired private UserUtility utility; public String SaveUser(UserDTO user) { String message = ""; if (user != null) { dao.saveUser(utility.mapDtoToModel(user)); message = "Registration successfully"; } else { message = "Registration failed.."; } return message; } public List<UserDTO> getUserInfo() { return utility.getDtoFromModel(dao.getUsers()); } } <file_sep>package com.user.reg.web.model; import java.io.Serializable; import java.sql.Blob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "Attachment_Table") public class AttachmentModel implements Serializable { /** * */ private static final long serialVersionUID = 7592301854725064206L; @Id @GenericGenerator(name = "aid", strategy = "increment") @GeneratedValue(generator = "aid") @Column(name="attachmentId") private int id; @Lob private Blob imageFile; public int getId() { return id; } public void setId(int id) { this.id = id; } public Blob getImageFile() { return imageFile; } public void setImageFile(Blob imageFile) { this.imageFile = imageFile; } }
053b8aa12f543d5177d6bc3c1d39c58cc5a17d84
[ "Markdown", "Java" ]
9
Java
MixContent/User-registration-mvc
7d17e3a686dc3fd201ca65028d2390b73d08b4ba
d5c0f40a9bddd113aa39732b4c2168262d72c332
refs/heads/master
<file_sep><?php /** * Provides the extra fields needed to store a user * * @package silverstripe-facebook * @subpackage extension **/ class FacebookUser extends DataExtension { /** * Stores the users' instance of Facebook * * @var Facebook **/ static $facebook; /** * Whether or not to allow duplicate Facebook accounts on the same DataObject type. * * @var boolean **/ protected $allowDuplicateFacebookAccounts = false; /** * Whether or not to overwrite existing Facebook account data on the current DataObject. * * @var boolean **/ protected $overwriteExistingFacebookAccount = false; static $db = array( "FacebookUserID" => "V<PASSWORD>(255)", "FacebookAccessToken" => "<PASSWORD>)" ); /** * This method holds the functionality to complete the oauth flow through the CMS * * @param $fields FieldList **/ public function updateCMSFields(FieldList $fields) { // Remove fields that may have been added elsewhere. $fields->removeByName("FacebookUser"); $fields->removeByName("FacebookUserID"); $fields->removeByName("FacebookAccessToken"); // Add our new fields. $fields->addFieldsToTab("Root.Main", ToggleCompositeField::create('FacebookUser', 'Facebook User', array( TextField::create("FacebookUserID", "User ID"), TextField::create("FacebookAccessToken", "Access Token") ) )->setHeadingLevel(4) ); } /** * Set whether or not to allow duplicate facebook accounts on this type of DataObject * * @param $bool boolean **/ public function setAllowDuplicateFacebookAccounts($bool) { $this->allowDuplicateFacebookAccounts = (bool) $bool; } /** * Fetch whether or not we're allowing duplicate facebook accounts on this dataobject type. * * @return boolean **/ public function getAllowDuplicateFacebookAccounts() { return (bool) $this->allowDuplicateFacebookAccounts; } /** * Set whether or not we should overwrite existing records. * * @param $bool boolean **/ public function setOverwriteExistingFacebookAccount($bool) { $this->overwriteExistingFacebookAccount = (bool) $bool; } /** * Get whether or not we can overwrite existing facebook account data. * * @return boolean **/ public function getOverwriteExistingFacebookAccount() { return (bool) $this->overwriteExistingFacebookAccount; } /** * Validate writing of the Facebook Account * * @param $validation ValidationResult **/ public function validate(ValidationResult $validation) { if($this->owner->FacebookUserID && $this->owner->FacebookAccessToken) { // Check to see if the user is already connected to an account & whether it matters. if($this->getOverwriteExistingFacebookAccount() == false) { $changed = $this->owner->getChangedFields(); if($this->owner->isChanged("FacebookUserID") && trim($changed['FacebookUserID']['before']) != "") { $validation->error("You already have a Facebook account connected."); } } // Check to see if there are other types of this DataObject also connected to this Facebook account (if it matters) if($this->getAllowDuplicateFacebookAccounts() == false) { $duplicate = DataList::create($this->owner->ClassName) ->filter("FacebookUserID", $this->owner->FacebookUserID); // Exclude the current user from the search. if($this->owner->ID) $duplicate = $duplicate->exclude("ID", $this->owner->ID); if($duplicate->first()) $validation->error("Your Facebook account is already connected to another " . $this->owner->singular_name() . "."); } } } /** * This connects the given facebook account to the current DataObject * * @param $user array - data rutned by calling $facebook->api("/me"); * @param $access_token string - Facebook User Access Token * @param $required_fields array - fields that should exist within the array. * * @return ValidationResult **/ public function connectFacebookAccount($user, $access_token, $required_fields = array()) { $validation = new ValidationResult(); // Check required fields exist. $required = array_merge($required_fields, array("id")); foreach($required as $r) { if(!isset($user[$r])) { $validation->error("A required fields was missing: " . $r); return $validation; } } // Write our values to the DataObject $this->owner->FacebookUserID = $user['id']; // Required field. $this->owner->FacebookAccessToken = $access_token; if(isset($user['email']) && !$this->owner->Email && Email::validEmailAddress($user['email'])) $this->owner->Email = $user['email']; if(isset($user['first_name']) && !$this->owner->FirstName) $this->owner->FirstName = $user['first_name']; if(isset($user['last_name']) && !$this->owner->Surname) $this->owner->Surname = $user['last_name']; // Facebook hook $this->owner->extend("beforeConnectFacebookAccount", $validation, $user, $access_token); $memberValidation = $this->owner->validate(); if($memberValidation->valid()) { if(!$this->owner->write()) { $validation->error("Unable to create your account."); } } else { $this->owner->extend("invalidFacebookConnect", $memberValidation); return $memberValidation; } return $validation; } /** * This will disconnect a DataObject from its associated Facebook account. * * @return boolean **/ public function disconnectFacebookAccount() { // Write our values to the DataObject $this->owner->FacebookUserID = ""; $this->owner->FacebookAccessToken = ""; return (bool) $this->owner->write(); } /** * Clears out the facebook session keys. **/ public function memberLoggedOut() { $facebookApp = FacebookApp::get()->first(); if($facebookApp) { foreach(array('state', 'code', 'access_token', 'user_id') as $key) { Session::clear("fb_" . $facebookApp->FacebookConsumerKey . "_" . $key); } } } } <file_sep><?php /** * Facebook Application * * @package silverstripe-facebook * @subpackage model **/ class FacebookApp extends DataObject implements TemplateGlobalProvider { /** * Stores the current instance of Facebook * * @var Facebook **/ protected $facebook; static $db = array( "EnableFacebookLogin" => "Boolean", "EnableFacebookSignup" => "Boolean", "FacebookConsumerKey" => "Varchar(255)", "FacebookConsumerSecret" => "Varchar(255)", ); static $defaults = array( "EnableFacebookLogin" => true, "EnableFacebookSignup" => true, ); /** * A list of permissions that will be requested a user logs in. * {@link https://developers.facebook.com/docs/reference/login/#permissions} * * @var array **/ static $permissions = array(); /** * Retuired Fields for signup when querying $facebook->api("/me") * * @var array **/ static $required_user_fields = array(); /** * Return Global variables for use in templates. * * @return array **/ static public function get_template_global_variables() { return array ( "FacebookConnectURL" => "connect_url", "FacebookLoginURL" => "login_url", "FacebookDisconnectURL" => "disconnect_url" ); } /** * Returns a URL for logged in users to connect their Facebook accounts * * @return string URL **/ static public function connect_url() { return Controller::join_links("facebook", "connect"); } /** * Returns a URL for users to login with their facebook accounts. * * @return string URL or false when Login is disabled **/ static public function login_url() { $facebook = FacebookApp::get()->first(); if($facebook && $facebook->EnableFacebookLogin == 1) return Controller::join_links("facebook", "login"); return false; } /** * Return a URL to allow users to disassociate their Facebook accounts. * * @return string URL **/ static public function disconnect_url() { return Controller::join_links("facebook", "disconnect"); } public function getCMSFields() { $fields = new FieldList(); $fields->push( new TabSet("Root", new Tab("Main", HeaderField::create("Application Settings", 3), TextField::create("FacebookConsumerKey", "Consumer Key"), PasswordField::create("FacebookConsumerSecret", "Consumer Secret"), OptionsetField::create("EnableFacebookLogin", "Facebook Login", array( 0 => "Disabled", 1 => "Enabled" )), OptionsetField::create("EnableFacebookSignup", "Facebook Signup", array( 0 => "Disabled", 1 => "Enabled" )) ) ) ); $this->extend("updateCMSFields", $fields); return $fields; } /** * Setup a default Facebook app **/ public function requireDefaultRecords() { $facebook = FacebookApp::get()->count(); if(!$facebook) { $facebook = FacebookApp::create(); $facebook->write(); } } /** * Creates and returns an instance of Facebook if the Consumer key & secret are set. * * @return Facebook or false **/ public function getFacebook() { if($this->facebook) { return $this->facebook; } if($this->FacebookConsumerKey && $this->FacebookConsumerSecret) { return $this->facebook = new Facebook(array( "appId" => $this->FacebookConsumerKey, "secret" => $this->FacebookConsumerSecret )); } return false; } /** * Returns the parameters to pass to Facebook->getLoginUrl() * * @return string array **/ public function getLoginUrlParams() { return array( "scope" => array_values($this->config()->get("permissions")) ); } } <file_sep><?php /** * FacebookContoller provides the integration functionality for the front-end * * @package silverstripe-facebook * @subpackage control **/ class FacebookController extends ContentController { static $allowed_actions = array( "connect" => "->facebookLoginEnabled", "login" => "->facebookLoginEnabled", "disconnect", ); public function facebookLoginEnabled() { $facebookApp = FacebookApp::get()->first(); return $facebookApp->EnableFacebookLogin; } /** * Return a blank form to display front-end messages * * @return Form **/ public function Form() { $form = new Form($this, "Facebook", new FieldList(), new FieldList()); $this->extend("setupForm", $form); return $form; } /** * Prevent this request as it doesn't do anything. * * @return SS_HTTPResponse **/ public function index() { return $this->httpError(403, "Forbidden"); } /** * This will connect a facebook account to a logged in Member. * * @param $request SS_HTTPRequest * @return SS_HTTPResponse **/ public function connect($request) { $form = $this->Form(); $member = Member::currentUser(); if($this->request->getVar("error")) { $form->sessionMessage("Unable to obtain access to Facebook.", "bad"); return $this->renderWith(array("FacebookController", "Page", "Controller")); } $facebookApp = FacebookApp::get()->first(); if($member || $facebookApp->EnableFacebookLogin) { $facebook = $facebookApp->getFacebook(); if(!$facebook) { $form->sessionMessage("Unable to fetch Facebook Application", "bad"); return $this->renderWith(array("FacebookController", "Page", "Controller")); } $user = $facebook->getUser(); if(!$user) { $params = $facebookApp->getLoginUrlParams(); $url = $facebook->getLoginUrl($params); if($url) { return $this->redirect($url, 302); } else { $form->sessionMessage("Unable to login to Facebook.", "bad"); } } else { $user_profile = $facebook->api("/me"); if($user_profile) { // Check whether this is a new user (signup) $member = Member::get()->filter("FacebookUserID", $user_profile['id'])->first(); if($member) { return $this->redirect(Controller::join_links("facebook", "login")); } else { $member = new Member(); $access_token = Session::get("fb_" . $facebookApp->FacebookConsumerKey . "_access_token"); $valid = $member->connectFacebookAccount($user_profile, $access_token); if($valid->valid()) { $form->sessionMessage("You have signed up with Facebook.", "good"); $this->extend("onAfterFacebookSignup", $member); } else { $form->sessionMessage($valid->message(), "bad"); } } } else { $form->sessionmessage("Unable to retreive your Facebook account.", "bad"); } } } else { $form->sessionMessage("You must be logged in to connect your Facebook account.", "bad"); } return $this->renderWith(array("FacebookController", "Page", "Controller")); } /** * This will disconnect a members' Facebook account from their SS account. * * @param $request SS_HTTPRequest * @return SS_HTTPResponse **/ public function disconnect($request) { $form = $this->Form(); $member = Member::currentUser(); if($member) { $member->disconnectFacebookAccount(); $this->extend("onAfterFacebookDisconnect"); } $form->sessionMessage("You have disconnected your account.", "good"); return $this->renderWith(array("FacebookController", "Page", "Controller")); } /** * Log the user in via an existing Facebook account connection. * * @return SS_HTTPResponse **/ public function login() { $form = $this->Form(); if($this->request->getVar("error")) { $form->sessionMessage("Unable to obtain access to Facebook.", "bad"); return $this->renderWith(array("FacebookController", "Page", "Controller")); } $facebookApp = FacebookApp::get()->first(); if(!$facebookApp || !$facebookApp->EnableFacebookLogin) { $form->sessionMessage("Facebook Login is disabled.", "bad"); } else { if($member = Member::currentUser()) $member->logOut(); $facebook = $facebookApp->getFacebook(); $user = $facebook->getUser(); if($user) { $member = Member::get()->filter("FacebookUserID", $user)->first(); if($member) { $member->logIn(); $form->sessionMessage("You have logged in with your Facebook account.", "good"); $member->extend("onAfterMemberLogin"); } else if ($facebookApp->EnableFacebookSignup) { // Attempt to sign the user up. $member = new Member(); // Load the user from Faceook $user_profile = $facebook->api("/me"); if($user_profile) { // Fill in the required fields. $access_token = Session::get("fb_" . $facebookApp->FacebookConsumerKey . "_access_token"); $signup = $member->connectFacebookAccount($user_profile, $access_token, $facebookApp->config()->get("required_user_fields")); if($signup->valid()) { $member->logIn(); $form->sessionMessage("You have signed up with your Facbeook account.", "good"); // Facebook Hooks $this->extend("onAfterFacebookSignup", $member); } else { $form->sessionMessage($signup->message(), "bad"); } } else { $form->sessionMessage("Unable to load your Facbeook account.", "bad"); } } else { $form->sessionMessage("Unable to log in with Facebook.", "bad"); } } else { $params = $facebookApp->getLoginUrlParams(); $url = $facebook->getLoginUrl($params); if($url) { return $this->redirect($url, 302); } else { $form->sessionMessage("Unable to login to Facebook at this time.", "bad"); } } } // Extend Failed facebook login if(!Member::currentUser()) $this->extend("onAfterFailedFacebookLogin"); return $this->renderWith(array("FacebookController", "Page", "Controller")); } } <file_sep><?php /** * Admin interface to mange Facebook integration. * * @package silverstripe-facebook * @subpackage admin **/ class FacebookAdmin extends LeftAndMain { static $allowed_actions = array( "save", "EditForm", ); /** * CMS URL Segment * * @var string **/ static $url_segment = "facebook"; /** * CMS Menu Title * * @var string **/ static $menu_title = "Facebook Integration"; /** * CMS Menu icon. * * @var string - Path to image **/ static $menu_icon = "silverstripe-facebook/admin/images/menu-icons/facebook.png"; /** * Stores an instance of Facebook. * * @var Faceviij **/ protected $facebook; public function init() { parent::init(); // Load Facebook App $this->getFacebookApp(); } public function getEditForm($id = null, $field = null) { $form = parent::getEditForm($id, $field); $form->addExtraClass("center"); // Setup Fields $form->setFields($this->facebook->getCMSFields()); // Setup Actions $form->setActions($this->getCMSActions()); // Populate Form $form->loadDataFrom($this->facebook); return $form; } /** * Add actions to the EditForm * * @return FieldList **/ public function getCMSActions() { //Setup Actions $actions = new FieldList(); $actions->push( FormAction::create("save", "Save")->setUseButtonTag(true) ->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept') ); $this->extend("updateCMSActions", $actions); return $actions; } /** * Save the form in its current state. * * @param $data array - Form data * @param $form Form - Current Form * @return SS_HTTPResponse **/ public function save($data, $form) { $facebook = $this->getFacebookApp(); $form->saveInto($facebook, $this->request); if($facebook->write()) { $form->sessionMessage("Facebook Application saved.", "good"); } else { $form->sessionMessage("Unable to save Facebook Application", "bad"); } return $this->getResponseNegotiator()->respond($this->request); } /** * Returns the Facebook App for the current site. * * @return FacebookApp **/ public function getFacebookApp() { if($this->facebook) return $this->facebook; return $this->facebook = FacebookApp::get()->first(); } } ?> <file_sep>Silverstripe Facebook ============================ This module is to allow integration between Facebook and Silverstripe. Its based (and ported from) the [sstwitter module](http://www.github.com/micmania1/sstwitter). Features -------- * CMS interface to integrate Silverstripe with a Facebook application & connect an account to the website. * Connect/Disconnect Member's to Facebook accounts. * Facebook signup. * Enable/Disable Facebook login & signup through the CMS. * Developer Access to Facebook API through the official [Facebook PHP SDK](https://github.com/facebook/facebook-php-sdk). Usage -------- **$FacebookConnectURL** (FacebookApp::connect_url()) This displays a link where a logged in user will be taken through the Facebook authentication process to connect their Facebook account. **$FacebookDisconnectURL** (FacebookApp::disconnect_url()) This will disassociate the Facebook account from the Member. **$FacebookLoginURL** (FacebookApp::login_url()) This will return a url whereby the user can login to their Silverstripe account through Facebook. It will sign the user up if a Facebook account connect be found and Signup is enabled. <a href="$FacebookConnectURL">Connect</a><br /> <a href="$FacebookDisconnectURL">Disconnect</a><br /> <% if FacebookLoginURL %> <a href="$FacebookLoginURL">Login</a> <% else %> Facebook Login is disabled. <% end_if %> Extending --------- Silverstripe Facebook allows you to use the full power of Facebook's PHP SDK. You can access this by referencing FacebookApp->getFacebook(). <file_sep><?php /** * FacebookAdmin extension for user-specific actions. * * @package ssilverstripe-facebook * @subpackage extension **/ class FacebookUserAdmin extends DataExtension { public function onAfterInit() { Requirements::css("silverstripe-facebook/admin/css/screen.css"); Requirements::javascript("silverstripe-facebook/admin/javascript/FacebookAdmin.js"); } public function updateCMSActions(FieldList $fields) { $facebookApp = $this->getFacebookApp(); $facebook = $facebookApp->getFacebook(); if($facebook) { // Add the authorize action if consumer keys are set. if($facebookApp->FacebookConsumerKey && $facebookApp->FacebookConsumerSecret) { $user = $facebook->getUser(); if(!$user) { $params = $facebookApp->getLoginUrlParams(); if($url = $facebook->getLoginUrl($params)) { $fields->push( FormAction::create("authorize", "Authorize a Facebook Account") ->setUseButtonTag(true) ->addExtraClass("silverstripe-facebook-ui-action-facebook") ->setAttribute("data-icon", "facebook") ->setAttribute("data-role", "authorize") ->setAttribute("data-url", $url) ); } } } } return $fields; } /** * Fetches the sites Facebook Applications. * * @return FacebookApp **/ public function getFacebookApp() { return FacebookApp::get()->first(); } }
d557b5aef99ddf61b440378717b9c63d77e37d5d
[ "Markdown", "PHP" ]
6
PHP
micmania1/silverstripe-facebook
dfa83e38101b6fe6a818905ae31004dbce9971e0
4c86281a0e0edfe6383df99d19c45e573a94220d
refs/heads/master
<file_sep><?php class LoginController{ // database connection and table name private $db; private $table_name = "users"; // object properties public $email; public $password; public function __construct(){ include_once __DIR__."\..\config\dbconnecter.php"; $this->db =new DbConnecter(); } function login(){ // echo $_POST["email"]; $userRecord = $this->getUser($_POST["email"]); $loginPassword = 0; if (!empty($userRecord)) { if (!empty($_POST["password"])) { // $userpassword = $_POST["password"]; $userpassword = md5($_POST["password"]); } $hashedPassword = $userRecord[0]["password"]; var_dump($userpassword); var_dump($hashedPassword); $loginPassword = 0; if ($userpassword==$hashedPassword) { $loginPassword = 1; } } else { $loginPassword = 0; } if ($loginPassword == 1) { session_start(); $_SESSION["email"] = $userRecord[0]["email"]; session_write_close(); $url = "./dashboard.php"; header("Location: $url"); } else if ($loginPassword == 0) { $loginStatus = "Invalid username or password."; return $loginStatus; } } public function getUser($email) { $query = 'SELECT * FROM users where email = ?'; $paramType = 's'; $paramValue = array( $email ); $memberRecord = $this->db->select($query, $paramType, $paramValue); // var_dump($memberRecord); return $memberRecord; } public function registerMember() { echo $_POST["gender"]; $isEmailExists = $this->isEmailExists($_POST["email"]); if ($isEmailExists) { $response = array( "status" => "error", "message" => "Email already exists." ); } else { if (! empty($_POST["signup-password"])) { // $hashedPassword = password_hash($_POST["signup-password"], PASSWORD_DEFAULT); $hashedPassword = md5($_POST["signup-password"]); } $query = 'INSERT INTO users (name, email,password,gender ) VALUES (?, ?, ?, ?)'; $paramType = 'ssss'; $paramValue = array( $_POST["username"], $_POST["email"], $hashedPassword, $_POST["gender"], ); $memberId = $this->db->insert($query, $paramType, $paramValue); if (! empty($memberId)) { $response = array( "status" => "success", "message" => "You have registered successfully." ); } } return $response; } public function isEmailExists($email) { $query = 'SELECT * FROM users where email = ?'; $paramType = 's'; $paramValue = array( $email ); $resultArray = $this->db->select($query, $paramType, $paramValue); $count = 0; if (is_array($resultArray)) { $count = count($resultArray); } if ($count > 0) { $result = true; } else { $result = false; } echo $result; return $result; } }<file_sep><?php // set page headers $page_title = "Login"; include_once __DIR__."\libs\assets\layout_header.php"; include_once __DIR__."\controllers\loginController.php"; if($_POST){ $user = New LoginController(); $loginResult = $user->login(); } ?> <div class="login-container"> <div class="sign-up-container"> <div class="login-signup"> <a href="registration.php">Sign up</a> </div> <div class="signup-align"> <form name="login" action="" method="post" onsubmit="return loginValidation()"> <div class="signup-heading">Login</div> <?php if(!empty($loginResult)){?> <div class="error-msg"><?php echo $loginResult;?></div> <?php }?> <div class="row"> <div class="inline-block"> <div class="form-label"> Username<span class="required error" id="email-info"></span> </div> <input class="input-box-330" type="email" name="email" id="email"> </div> </div> <div class="row"> <div class="inline-block"> <div class="form-label"> Password <span class="required error" id="password-info"></span> </div> <input class="input-box-330" type="<PASSWORD>" name="password" id="password"> </div> </div> <div class="row"> <input class="btn" type="submit" name="login-btn" id="login-btn" value="Login"> </div> </form> </div> </div> </div> <script> function loginValidation() { var valid = true; $("#email").removeClass("error-field"); $("#password").removeClass("error-field"); var UserName = $("#email").val(); var Password = $('#password').val(); $("#email-info").html("").hide(); if (UserName.trim() == "") { $("#email-info").html("required.").css("color", "#ee0000").show(); $("#email").addClass("error-field"); valid = false; } if (Password.trim() == "") { $("#password-info").html("required.").css("color", "#ee0000").show(); $("#password").addClass("error-field"); valid = false; } if (valid == false) { $('.error-field').first().focus(); valid = false; } return valid; } </script> <?php // footer include_once __DIR__."\libs\assets\layout_footer.php"; ?><file_sep><?php session_start(); $page_title = "Dashboard"; include_once __DIR__."\libs\assets\layout_header.php"; if (isset($_SESSION["email"])) { include_once __DIR__."\controllers\loginController.php"; $user = New LoginController(); $loginResult = $user->getUser($_SESSION["email"]); $data["name"]=$loginResult[0]["name"]; $data["email"]=$loginResult[0]["email"]; $data["gender"]=$loginResult[0]["gender"]; session_write_close(); } else { session_write_close(); $url = "./index.php"; header("Location: $url"); } if($_POST){ session_start(); session_unset(); session_write_close(); $url = "./index.php"; header("Location: $url"); } ?> <div class="error-msg" id="error-msg"></div> <div class="row"> <div class="inline-block"> <div class="form-label"> Username </div> <input class="input-box-330" type="text" name="name" id="name" value="<?php echo $data["name"]?>" disabled> </div> </div> <div class="row"> <div class="inline-block"> <div class="form-label"> Email </div> <input class="input-box-330" type="text" name="email" id="email" value="<?php echo $data["email"]?>" disabled> </div> </div> <div class="row"> <div class="inline-block"> <div class="form-label"> Gender </div> <input class="input-box-330" type="text" name="gender" id="gender" value="<?php echo $data["gender"]?>" disabled> </div> </div> <div class="row"> <form name="sign-up" action="" method="post"> <input class="btn" type="submit" name="signup-btn" id="signup-btn" value="Logout"> </form> </div> </div> </div> </div> <?php // footer include_once __DIR__."\libs\assets\layout_footer.php"; ?>
78d84a0744fee3b3b6f1283f0c7d692fe10bd8e6
[ "PHP" ]
3
PHP
dasanIkmal/loginApp
2cb57033c31b359df7dadea6c9e0dbe86db7bd13
72c5cffbb062cdf3256b3a67f66e40d5972c3ebf
refs/heads/master
<repo_name>CUIPF1993/gpython<file_sep>/mesh-color.cs private void RunScript(Mesh mesh, List<Color> color, ref object A) { for (int i = 0 ;i < mesh.Vertices.Count ;i++) { if (color.Count > 1) { mesh.VertexColors.SetColor(i, color[i]); } else { mesh.VertexColors.SetColor(i, color[0]); } } A = mesh; }<file_sep>/最大最小值互换.py #_*_coding:utf_8 #这样就可以做中文注释了,哈哈哈哈 """ 这里是做的最大与最小值的互换,用到的sorted的方法, 采用的的字典的排序,利用多次转换。 """ def sort_Reverse(List): dic={} sort_List=sorted(List) for i in range(len(List)): dic[sort_List[i]]=List[i] dic2=sorted(dic.iteritems(), key=lambda d:d[1], reverse = True )#这是一个列表元组 dic3={} for i in range(len(List)): dic3[sort_List[i]]=dic2[i][0] dic3=sorted(dic3.iteritems(), key=lambda d:d[1], reverse = False ) List2=[] for i in range(len(List)): List2.append(dic3[i][0]) return List2 changeList=sort_Reverse(List) <file_sep>/递归描述曲线.py from Grasshopper.Kernel.Types import GH_LineCharge #_*_coding:utf-8 """ 制作人:盖房子的猫熊 用多条直线去描述一条曲线,采用的算法为二分法,和递归: accuracy 为直线的精确度。 """ import rhinoscriptsyntax as rs def curve_line(curve,accuracy): #定义了一个方法去判定曲线是否需要优化,利用的数学原理为两点之间直线最短 curve_length=rs.CurveLength(curve) end_point=rs.CurveEndPoint(curve) star_point=rs.CurveStartPoint(curve) line=rs.AddLine(end_point,star_point) line_length=rs.CurveLength(line) if curve_length == 0: #为防止曲线长度为零报错,提前捕获,也可采用try 语法。 line_curve = 1 else: line_curve=line_length/curve_length if line_curve>accuracy: return False #不需要优化返回False else: return True #需要优化返回True def divide_curve(L,accuracy,line_list): #定义了一个递归方法。L为递归的曲线,accuracy为精确度,line_list为返回的直线 L_curve=[] #定义一个空的列表,用于存放等分的曲线 bool=True #设定一个布尔值,用于判定是否返回直线,还是进入下一次递归 for i in range(len(L)): if curve_line(L[i],accuracy): bool = False if rs.IsCurve(L[i]): domain = rs.CurveDomain(L[i]) parameter = (domain[1]-domain[0]) / 2.0+domain[0] #求出曲线的中点,此处有陷阱,不可直接使用domain[1]/2 split_curve=rs.SplitCurve( L[i],parameter) L_curve.extend(split_curve) #列表方法将一个列表的内容追加给前一个列表 else: end_point=rs.CurveEndPoint(L[i]) star_point=rs.CurveStartPoint(L[i]) line=rs.AddLine(end_point,star_point) line_list.append(line) #求出精确描述的每一段直线 if bool == True: return line_list else: return divide_curve(L_curve,accuracy,line_list) if __name__ == "__main__": if accuracy>0.999: accuracy=0.999 elif accuracy is None: accuracy=0.9 line_list=[] lines=divide_curve(curve,accuracy,line_list)<file_sep>/八皇后.py import rhinoscriptsyntax as rs def queens(num=8,state=()): for pos in range(num): if not conflict(state,pos): if len(state)==num-1: yield (pos,) else : for result in queens(num,state+(pos,)): yield (pos,)+result def conflict(state,nextX): nextY=len(state) for i in range(nextY): if abs(state[i]-nextX) in (0,nextY-i): ''' 如果下一个皇后和正在考虑的前一个给皇后的水平距离为0, (列相同)或者等于垂直距离(在同一条对角线上)就返回True,否者返回False。 ''' return True return False a=queens(num) <file_sep>/磁场线模拟人流.py from Grasshopper.Kernel.Types import GH_LineCharge from Rhino.Geometry import Point3d from Rhino.Geometry import Vector3d from scriptcontext import sticky as st class Mover(object): def __init__(self,pos): self.pos=pos #定义基本类的位置属性。 L=[] V=[] for i in range(len(pos)): names='move%d'%i if names not in st: st[names]=Mover(pos[i]) gH_LineCharge = GH_LineCharge() #初始化墙体的磁场线 gH_LineCharge.Charge = 1 gH_LineCharge.Limits = box gH_LineCharge2 = GH_LineCharge() #初始化吸引的磁场线 gH_LineCharge2.Charge = -num gH_LineCharge2.Limits = box if Toogle: a=Point3d(0,0,0) for line in lines: gH_LineCharge.Segment = line b=gH_LineCharge.Force(st[names].pos) a=Point3d.Add(a,b) for line in line_field: gH_LineCharge2.Segment = line b=gH_LineCharge2.Force(st[names].pos) a=Point3d.Add(a,b) a=Vector3d(a.X,a.Y,0) a.Unitize() st[names].pos=Point3d.Add(st[names].pos,a) L.append(st[names].pos) else: del st[names] <file_sep>/多线程.py import ghpythonlib.components as ghcomp import ghpythonlib.parallel #custom function that is executed by parallel.run def slice_at_angle(plane): result = ghcomp.BrepXPlane(brep, plane) if result: return result.curves if parallel: slices = ghpythonlib.parallel.run(slice_at_angle, planes, True) else: slices = ghcomp.BrepXPlane(brep, planes).curves
f6bdc56686c3a0701171cddd2f25b1eacfde5e55
[ "C#", "Python" ]
6
C#
CUIPF1993/gpython
5a2c4d8c1dbfe0677e9885f6540c3a573e772c07
099bd8978ad604c188f236caa3e72c2759221688
refs/heads/master
<repo_name>laenNoCode/site-anciens-eleves<file_sep>/contact.php <div> <form method="post" action="index.php"> <fieldset> <p> <label for="ameliorer"> Avez vous des remarques, des questions à nous faire parvenir ?</label><br /> <textarea name="ameliorer" id="ameliorer" maxlength="300" rows="6" cols="50" required ></textarea> </p> <input type="submit" value="Envoyer" /> </fieldset> </form> </div> <?php function sizeFolder($Rep) { $Racine=opendir($Rep); $Taille=0; while($Dossier = readdir($Racine)) { if($Dossier != '..' And $Dossier !='.') { if(is_dir($Rep.'/'.$Dossier)) { $Taille += sizeFolder($Rep.'/'.$Dossier); //Ajoute la taille du sous dossier } else{ $Taille += filesize($Rep.'/'.$Dossier); //Ajoute la taille du fichier } } } closedir($Racine); return $Taille; } if ( isset($_POST['ameliorer'])) { $size_file = strlen($_POST['ameliorer']); $size_folder = sizeFolder("stockage"); if (($size_file + $size_folder)<100000){ $fichier = fopen("stockage/remarques.txt",'a+'); fputs($fichier, $_POST['ameliorer']. PHP_EOL); } } ?><file_sep>/connexion.php <?php $servername = "localhost"; $username = "ancien"; $password = "<PASSWORD>"; $dbname = "ancien"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = test_input($_POST["mail"]); $pass = test_input_pass($_POST["password"]); $sql = "SELECT id, hash, nom, prenom FROM Identifiants WHERE email=? ;"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $email); $stmt->execute(); $stmt->bind_result($id, $hash, $name, $surname); $stmt->fetch(); if (isset($id)){ if (password_verify($pass, $hash)) { session_start(); $_SESSION["user_id"] = $id; $_SESSION["user_name"] = $surname." ".$name; } else { $errID = "Mot de passe invalide"; } } else { $errID = "Mail non-enregistré $email"; } $stmt->close(); if (isset($errID)){ header("Location: index.php?tab=connexion&err='$errID'"); } else { //header("Location: index.php?tab=students&id=".$_SESSION["user_id"]); header("Location: index.php?tab=students"); } } function test_input_pass($data) { $data = trim($data); //$data = stripslashes($data); //$data = strip_tags($data); $data = htmlspecialchars($data); return $data; } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = strip_tags($data); $data = htmlspecialchars($data); return $data; }<file_sep>/functions.js function change_tab(name) { document.getElementById('tab_'+name).className = 'tab_1 tab'; document.getElementById('content_tab_'+name).style.display = 'block'; let old = data.old_tab; data.old_tab = name; if (old != name) { document.getElementById('tab_' + old).className = 'tab_0 tab'; document.getElementById('content_tab_'+ old).style.display = 'none'; } } if (typeof(data) == 'undefined') { data ={ old_tab : "home" } } <file_sep>/header.php <div id ="header" class="tabs"> <img src="images/logo2.png" id="logo" onclick = "change_tab('home');"><!-- --><span class="tab_1 tab" id="tab_home" onclick="change_tab('home');"> Accueil </span><!-- --><span class="tab_0 tab" id="tab_students" onclick="change_tab('students');"> Anciens élèves </span><!-- --><span class="tab_0 tab" id="tab_contact" onclick="change_tab('contact');"> Nous contacter </span><!-- --><?php if (isset($_SESSION["user_name"])){ ?> <span class='tab_0 tab' id='menu'> <?php echo htmlspecialchars($_SESSION['user_name']); ?> <ul class ="sous"> <li> <a > Test1</a> </li> <li> <a > Test2</a> </li> <li> <a > Test3</a> </li> <li> <a href="deconnexion.php" id = "deconnexion"> Deconnexion</a> </li> </ul> <?php } else { ?> <span class='tab_0 tab' id='tab_connexion' onclick="change_tab('connexion');"> Connexion </span><!-- --></div> <?php } ?> </div> <!-- <br> <a href = 'deconnexion.php' id = "deconnexion"> Deconnexion </a> </span> </div> --><file_sep>/inscription.php <?php $servername = "localhost"; $username = "ancien"; $password = "<PASSWORD>"; $dbname = "ancien"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //echo "<body>"; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["nom"]); $surname = test_input($_POST["prenom"]); $email = test_input($_POST["mail"]); $promo = test_input($_POST["promo"]); $pass = test_input_pass($_POST["password"]); //echo $email; $sql = "SELECT count(id) FROM Identifiants WHERE email=? ;"; $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $name, $surname, $email); $stmt->execute(); $stmt->bind_result($nb_row); $stmt->fetch(); //echo $nb_row . "<br>"; if($nb_row >= 1){ $errID = "nom et prénom ou email déjà utilisé"; $stmt->close(); // pseudo deja utilise } else { $stmt->close(); $sql = "INSERT INTO Identifiants (nom, prenom, hash, email, promo) VALUES (?, ?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $hash = password_hash($pass, PASSWORD_BCRYPT); $stmt->bind_param("ssssi", $name, $surname, $hash, $email, $promo); if ($stmt->execute()==TRUE){ $id = $stmt->insert_id; session_start(); $_SESSION["user_id"] = $id; $_SESSION["user_name"] = $surname." ".$name; } $stmt->close(); } //echo "success $name $id $email"; if (isset($errID)){ header("Location: index.php?tab=connexion&err='$errID'"); } else { header("Location: index.php?tab=students"); } } //echo "</body>"; function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = strip_tags($data); $data = htmlspecialchars($data); return $data; } function test_input_pass($data) { $data = trim($data); //$data = stripslashes($data); //$data = strip_tags($data); $data = htmlspecialchars($data); return $data; }
dceab6f4cad94ff1c4dd8e3d996ae9f0cc6d15fc
[ "JavaScript", "PHP" ]
5
PHP
laenNoCode/site-anciens-eleves
abf28adfde67b314405f994c90b0708672273527
f062ce774260d0155a83efccb3ac1f5678ab1680
refs/heads/master
<file_sep><?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* modules/contrib/ds/templates/ds-field-expert.html.twig */ class __TwigTemplate_046611005b43e9d0bc03292497473e24fa80eee421e7c59d62dba519ed6ad65e extends \Twig\Template { public function __construct(Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = [ ]; $this->sandbox = $this->env->getExtension('\Twig\Extension\SandboxExtension'); $tags = ["if" => 17, "macro" => 32, "set" => 35, "for" => 62]; $filters = ["raw" => 16, "escape" => 19, "clean_class" => 36, "default" => 40]; $functions = []; try { $this->sandbox->checkSecurity( ['if', 'macro', 'set', 'for'], ['raw', 'escape', 'clean_class', 'default'], [] ); } catch (SecurityError $e) { $e->setSourceContext($this->getSourceContext()); if ($e instanceof SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } } protected function doDisplay(array $context, array $blocks = []) { // line 16 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "prefix", [], "array"))); // line 17 if ($this->getAttribute(($context["settings"] ?? null), "ow", [])) { // line 18 echo " "; if ($this->getAttribute(($context["settings"] ?? null), "ow-def-at", [], "array")) { // line 19 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "ow-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["wrapper_attributes"] ?? null), "mergeAttributes", [0 => ($context["attributes"] ?? null)], "method")), "html", null, true); echo "> "; } elseif ($this->getAttribute( // line 20 ($context["settings"] ?? null), "ow-def-cl", [], "array")) { // line 21 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "ow-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["wrapper_attributes"] ?? null), "mergeAttributes", [0 => $this->getAttribute(($context["attribute_classes"] ?? null), "offsetGet", [0 => "class"], "method")], "method")), "html", null, true); echo "> "; } else { // line 23 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "ow-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["wrapper_attributes"] ?? null)), "html", null, true); echo "> "; } // line 25 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute($this, "field", [0 => ($context["items"] ?? null), 1 => ($context["settings"] ?? null), 2 => ($context["label"] ?? null), 3 => ($context["content_attributes"] ?? null), 4 => ($context["field_item_wrapper_attributes"] ?? null), 5 => ($context["field_wrapper_attributes"] ?? null), 6 => ($context["label_attributes"] ?? null), 7 => ($context["label_hidden"] ?? null), 8 => ($context["element"] ?? null)], "method"))); echo " </"; // line 26 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "ow-el", [], "array")), "html", null, true); echo "> "; } else { // line 28 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute($this, "field", [0 => ($context["items"] ?? null), 1 => ($context["settings"] ?? null), 2 => ($context["label"] ?? null), 3 => ($context["content_attributes"] ?? null), 4 => ($context["field_item_wrapper_attributes"] ?? null), 5 => ($context["field_wrapper_attributes"] ?? null), 6 => ($context["label_attributes"] ?? null), 7 => ($context["label_hidden"] ?? null), 8 => ($context["element"] ?? null)], "method"))); echo " "; } // line 30 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "suffix", [], "array"))); // line 60 echo " "; } // line 32 public function getfield($__items__ = null, $__settings__ = null, $__label__ = null, $__content_attributes__ = null, $__field_item_wrapper_attributes__ = null, $__field_wrapper_attributes__ = null, $__label_attributes__ = null, $__label_hidden__ = null, $__element__ = null, ...$__varargs__) { $context = $this->env->mergeGlobals([ "items" => $__items__, "settings" => $__settings__, "label" => $__label__, "content_attributes" => $__content_attributes__, "field_item_wrapper_attributes" => $__field_item_wrapper_attributes__, "field_wrapper_attributes" => $__field_wrapper_attributes__, "label_attributes" => $__label_attributes__, "label_hidden" => $__label_hidden__, "element" => $__element__, "varargs" => $__varargs__, ]); $blocks = []; ob_start(); try { // line 33 echo " "; if ( !($context["label_hidden"] ?? null)) { // line 34 echo " "; // line 35 $context["title_classes"] = [0 => ("field-label-" . \Drupal\Component\Utility\Html::getClass($this->sandbox->ensureToStringAllowed($this->getAttribute( // line 36 ($context["element"] ?? null), "#label_display", [], "array"))))]; // line 39 if ($this->getAttribute(($context["settings"] ?? null), "lbw-def-at", [], "array")) { // line 40 echo "<"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array", true, true)) ? (_twig_default_filter($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array")), "div")) : ("div")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($this->getAttribute(($context["label_attributes"] ?? null), "addClass", [0 => ($context["title_classes"] ?? null)], "method"), "mergeAttributes", [0 => ($context["title_attributes"] ?? null)], "method")), "html", null, true); echo ">"; } else { // line 42 echo "<"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array", true, true)) ? (_twig_default_filter($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array")), "div")) : ("div")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["label_attributes"] ?? null), "addClass", [0 => ($context["title_classes"] ?? null)], "method")), "html", null, true); echo ">"; } // line 44 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["label"] ?? null)), "html", null, true); if ($this->getAttribute(($context["settings"] ?? null), "lb-col", [], "array")) { echo ":"; } // line 45 echo "</"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array", true, true)) ? (_twig_default_filter($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "lbw-el", [], "array")), "div")) : ("div")), "html", null, true); echo "> "; } // line 47 echo " "; // line 48 if ($this->getAttribute(($context["settings"] ?? null), "fis", [])) { // line 49 echo " "; if ($this->getAttribute(($context["settings"] ?? null), "fis-def-at", [], "array")) { // line 50 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fis-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["field_wrapper_attributes"] ?? null), "mergeAttributes", [0 => ($context["content_attributes"] ?? null)], "method")), "html", null, true); echo "> "; } else { // line 52 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fis-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["field_wrapper_attributes"] ?? null)), "html", null, true); echo "> "; } // line 54 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute($this, "content", [0 => ($context["items"] ?? null), 1 => ($context["settings"] ?? null), 2 => ($context["field_item_wrapper_attributes"] ?? null), 3 => ($context["content_attributes"] ?? null)], "method"))); echo " </"; // line 55 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fis-el", [], "array")), "html", null, true); echo "> "; } else { // line 57 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar($this->sandbox->ensureToStringAllowed($this->getAttribute($this, "content", [0 => ($context["items"] ?? null), 1 => ($context["settings"] ?? null), 2 => ($context["field_item_wrapper_attributes"] ?? null)], "method"))); echo " "; } } catch (\Exception $e) { ob_end_clean(); throw $e; } catch (\Throwable $e) { ob_end_clean(); throw $e; } return ('' === $tmp = ob_get_clean()) ? '' : new Markup($tmp, $this->env->getCharset()); } // line 61 public function getcontent($__items__ = null, $__settings__ = null, $__field_item_wrapper_attributes__ = null, $__content_attributes__ = null, ...$__varargs__) { $context = $this->env->mergeGlobals([ "items" => $__items__, "settings" => $__settings__, "field_item_wrapper_attributes" => $__field_item_wrapper_attributes__, "content_attributes" => $__content_attributes__, "varargs" => $__varargs__, ]); $blocks = []; ob_start(); try { // line 62 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(($context["items"] ?? null)); foreach ($context['_seq'] as $context["_key"] => $context["item"]) { // line 63 echo " "; if ($this->getAttribute(($context["settings"] ?? null), "fi", [])) { // line 64 echo " "; if ($this->getAttribute(($context["settings"] ?? null), "fi-def-at", [], "array")) { // line 65 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fi-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["field_item_wrapper_attributes"] ?? null), "mergeAttributes", [0 => $this->getAttribute($context["item"], "attributes", [])], "method")), "html", null, true); echo " > "; } else { // line 67 echo " <"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fi-el", [], "array")), "html", null, true); echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["field_item_wrapper_attributes"] ?? null)), "html", null, true); echo " > "; } // line 69 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["item"], "content", [])), "html", null, true); // line 70 echo "</"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["settings"] ?? null), "fi-el", [], "array")), "html", null, true); echo "> "; } else { // line 72 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["item"], "content", [])), "html", null, true); echo " "; } // line 74 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } catch (\Exception $e) { ob_end_clean(); throw $e; } catch (\Throwable $e) { ob_end_clean(); throw $e; } return ('' === $tmp = ob_get_clean()) ? '' : new Markup($tmp, $this->env->getCharset()); } public function getTemplateName() { return "modules/contrib/ds/templates/ds-field-expert.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 274 => 74, 268 => 72, 262 => 70, 260 => 69, 252 => 67, 244 => 65, 241 => 64, 238 => 63, 233 => 62, 218 => 61, 199 => 57, 194 => 55, 189 => 54, 181 => 52, 173 => 50, 170 => 49, 168 => 48, 165 => 47, 159 => 45, 154 => 44, 147 => 42, 140 => 40, 138 => 39, 136 => 36, 135 => 35, 133 => 34, 130 => 33, 110 => 32, 105 => 60, 103 => 30, 97 => 28, 92 => 26, 87 => 25, 79 => 23, 71 => 21, 69 => 20, 62 => 19, 59 => 18, 57 => 17, 55 => 16,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Source("{# /** * @file * Template to provide expert HTML for the field. * * Available variables: * - element: The field element. * - label: The label of the field. * - settings: The settings for the field. * - items: List of all the field items. Each item contains: * - attributes: List of HTML attributes for each item. * - content: The field item's content. */ #} {{- settings['prefix']|raw -}} {% if settings.ow %} {% if settings['ow-def-at'] %} <{{ settings['ow-el'] }} {{ wrapper_attributes.mergeAttributes(attributes) }}> {% elseif settings['ow-def-cl'] %} <{{ settings['ow-el'] }} {{ wrapper_attributes.mergeAttributes(attribute_classes.offsetGet('class')) }}> {% else %} <{{ settings['ow-el'] }} {{ wrapper_attributes }}> {% endif %} {{ _self.field(items, settings, label, content_attributes, field_item_wrapper_attributes, field_wrapper_attributes, label_attributes, label_hidden, element) }} </{{ settings['ow-el'] }}> {% else %} {{ _self.field(items, settings, label, content_attributes, field_item_wrapper_attributes, field_wrapper_attributes, label_attributes, label_hidden, element) }} {% endif %} {{- settings['suffix']|raw -}} {% macro field(items, settings, label, content_attributes, field_item_wrapper_attributes, field_wrapper_attributes, label_attributes, label_hidden, element) %} {% if not label_hidden %} {% set title_classes = [ 'field-label-' ~ element['#label_display']|clean_class, ] %} {%- if settings['lbw-def-at'] -%} <{{ settings['lbw-el']|default('div') }} {{ label_attributes.addClass(title_classes).mergeAttributes(title_attributes) }}> {%- else -%} <{{ settings['lbw-el']|default('div') }} {{ label_attributes.addClass(title_classes) }}> {%- endif -%} {{- label -}}{%- if settings['lb-col'] -%}:{%- endif -%} </{{ settings['lbw-el']|default('div') }}> {% endif %} {% if settings.fis %} {% if settings['fis-def-at'] %} <{{ settings['fis-el'] }} {{ field_wrapper_attributes.mergeAttributes(content_attributes) }}> {% else %} <{{ settings['fis-el'] }} {{ field_wrapper_attributes }}> {% endif %} {{ _self.content(items, settings, field_item_wrapper_attributes, content_attributes) }} </{{ settings['fis-el'] }}> {% else %} {{ _self.content(items, settings, field_item_wrapper_attributes) }} {% endif %} {% endmacro %} {% macro content(items, settings, field_item_wrapper_attributes, content_attributes) %} {% for item in items %} {% if settings.fi %} {% if settings['fi-def-at'] %} <{{ settings['fi-el'] }} {{ field_item_wrapper_attributes.mergeAttributes(item.attributes) }} > {% else %} <{{ settings['fi-el'] }} {{ field_item_wrapper_attributes }} > {% endif %} {{- item.content -}} </{{ settings['fi-el'] }}> {% else %} {{ item.content }} {% endif %} {% endfor %} {% endmacro %} ", "modules/contrib/ds/templates/ds-field-expert.html.twig", "C:\\xampp\\htdocs\\eshopbw\\modules\\contrib\\ds\\templates\\ds-field-expert.html.twig"); } } <file_sep><?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* themes/contrib/bootstrap4/templates/layout/page.html.twig */ class __TwigTemplate_5ce5345677b917374b52081d28e873a5b0b25bad8e0f84c5abceb90ef5679ef4 extends \Twig\Template { public function __construct(Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = [ ]; $this->sandbox = $this->env->getExtension('\Twig\Extension\SandboxExtension'); $tags = ["set" => 46, "if" => 62]; $filters = ["escape" => 60]; $functions = []; try { $this->sandbox->checkSecurity( ['set', 'if'], ['escape'], [] ); } catch (SecurityError $e) { $e->setSourceContext($this->getSourceContext()); if ($e instanceof SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } } protected function doDisplay(array $context, array $blocks = []) { // line 46 $context["nav_classes"] = ((("navbar navbar-expand-lg" . ((( // line 47 ($context["b4_navbar_schema"] ?? null) != "none")) ? ((" navbar-" . $this->sandbox->ensureToStringAllowed(($context["b4_navbar_schema"] ?? null)))) : (" "))) . ((( // line 48 ($context["b4_navbar_schema"] ?? null) != "none")) ? ((((($context["b4_navbar_schema"] ?? null) == "dark")) ? (" text-light") : (" text-dark"))) : (" "))) . ((( // line 49 ($context["b4_navbar_bg_schema"] ?? null) != "none")) ? ((" bg-" . $this->sandbox->ensureToStringAllowed(($context["b4_navbar_bg_schema"] ?? null)))) : (" "))); // line 51 echo " "; // line 53 $context["footer_classes"] = (((" " . ((( // line 54 ($context["b4_footer_schema"] ?? null) != "none")) ? ((" footer-" . $this->sandbox->ensureToStringAllowed(($context["b4_footer_schema"] ?? null)))) : (" "))) . ((( // line 55 ($context["b4_footer_schema"] ?? null) != "none")) ? ((((($context["b4_footer_schema"] ?? null) == "dark")) ? (" text-light") : (" text-dark"))) : (" "))) . ((( // line 56 ($context["b4_footer_bg_schema"] ?? null) != "none")) ? ((" bg-" . $this->sandbox->ensureToStringAllowed(($context["b4_footer_bg_schema"] ?? null)))) : (" "))); // line 58 echo " <header> "; // line 60 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "header", [])), "html", null, true); echo " "; // line 62 if ((($this->getAttribute(($context["page"] ?? null), "nav_branding", []) || $this->getAttribute(($context["page"] ?? null), "nav_main", [])) || $this->getAttribute(($context["page"] ?? null), "nav_additional", []))) { echo " <nav class=\""; // line 63 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["nav_classes"] ?? null)), "html", null, true); echo "\"> <div class=\""; // line 64 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["b4_top_container"] ?? null)), "html", null, true); echo " row mx-auto\"> <div class=\"col-auto p-0\"> "; // line 66 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "nav_branding", [])), "html", null, true); echo " </div> <div class=\"col-3 col-md-auto p-0 text-right\"> <button class=\"navbar-toggler collapsed\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> </div> <div class=\"collapse navbar-collapse col-12 col-md-auto p-0 justify-content-end\" id=\"navbarSupportedContent\"> "; // line 78 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "nav_main", [])), "html", null, true); echo " "; // line 79 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "nav_additional", [])), "html", null, true); echo " </div> </div> </nav> "; } // line 84 echo " </header> <main role=\"main\"> <a id=\"main-content\" tabindex=\"-1\"></a>"; // line 89 echo " "; // line 91 $context["sidebar_first_classes"] = ((($this->getAttribute(($context["page"] ?? null), "sidebar_first", []) && $this->getAttribute(($context["page"] ?? null), "sidebar_second", []))) ? ("col-12 col-sm-6 col-lg-3") : ("col-12 col-lg-3")); // line 93 echo " "; // line 95 $context["sidebar_second_classes"] = ((($this->getAttribute(($context["page"] ?? null), "sidebar_first", []) && $this->getAttribute(($context["page"] ?? null), "sidebar_second", []))) ? ("col-12 col-sm-6 col-lg-3") : ("col-12 col-lg-3")); // line 97 echo " "; // line 99 $context["content_classes"] = ((($this->getAttribute(($context["page"] ?? null), "sidebar_first", []) && $this->getAttribute(($context["page"] ?? null), "sidebar_second", []))) ? ("col-12 col-lg-6") : (((($this->getAttribute(($context["page"] ?? null), "sidebar_first", []) || $this->getAttribute(($context["page"] ?? null), "sidebar_second", []))) ? ("col-12 col-lg-9") : ("col-12")))); // line 101 echo " <div class=\""; // line 103 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["b4_top_container"] ?? null)), "html", null, true); echo "\"> "; // line 104 if ($this->getAttribute(($context["page"] ?? null), "breadcrumb", [])) { // line 105 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "breadcrumb", [])), "html", null, true); echo " "; } // line 107 echo " <div class=\"row no-gutters\"> "; // line 108 if ($this->getAttribute(($context["page"] ?? null), "sidebar_first", [])) { // line 109 echo " <div class=\"order-2 order-lg-1 "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["sidebar_first_classes"] ?? null)), "html", null, true); echo "\"> "; // line 110 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "sidebar_first", [])), "html", null, true); echo " </div> "; } // line 113 echo " <div class=\"order-1 order-lg-2 "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["content_classes"] ?? null)), "html", null, true); echo "\"> "; // line 114 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "content", [])), "html", null, true); echo " </div> "; // line 116 if ($this->getAttribute(($context["page"] ?? null), "sidebar_second", [])) { // line 117 echo " <div class=\"order-3 "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["sidebar_second_classes"] ?? null)), "html", null, true); echo "\"> "; // line 118 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "sidebar_second", [])), "html", null, true); echo " </div> "; } // line 121 echo " </div> </div> </main> "; // line 126 if ($this->getAttribute(($context["page"] ?? null), "footer", [])) { // line 127 echo "<footer class=\"mt-auto "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["footer_classes"] ?? null)), "html", null, true); echo "\"> <div class=\""; // line 128 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["b4_top_container"] ?? null)), "html", null, true); echo "\"> "; // line 129 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["page"] ?? null), "footer", [])), "html", null, true); echo " </div> </footer> "; } } public function getTemplateName() { return "themes/contrib/bootstrap4/templates/layout/page.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 211 => 129, 207 => 128, 202 => 127, 200 => 126, 193 => 121, 187 => 118, 182 => 117, 180 => 116, 175 => 114, 170 => 113, 164 => 110, 159 => 109, 157 => 108, 154 => 107, 148 => 105, 146 => 104, 142 => 103, 138 => 101, 136 => 99, 133 => 97, 131 => 95, 128 => 93, 126 => 91, 123 => 89, 117 => 84, 109 => 79, 105 => 78, 90 => 66, 85 => 64, 81 => 63, 77 => 62, 72 => 60, 68 => 58, 66 => 56, 65 => 55, 64 => 54, 63 => 53, 60 => 51, 58 => 49, 57 => 48, 56 => 47, 55 => 46,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Source("{# /** * @file * Theme override to display a single page. * * The doctype, html, head and body tags are not in this template. Instead they * can be found in the html.html.twig template in this directory. * * Available variables: * * General utility variables: * - base_path: The base URL path of the Drupal installation. Will usually be * \"/\" unless you have installed Drupal in a sub-directory. * - is_front: A flag indicating if the current page is the front page. * - logged_in: A flag indicating if the user is registered and signed in. * - is_admin: A flag indicating if the user has permission to access * administration pages. * * Site identity: * - front_page: The URL of the front page. Use this instead of base_path when * linking to the front page. This includes the language domain or prefix. * * Page content (in order of occurrence in the default page.html.twig): * - node: Fully loaded node, if there is an automatically-loaded node * associated with the page and the node ID is the second argument in the * page's path (e.g. node/12345 and node/12345/revisions, but not * comment/reply/12345). * * Regions: * - page.header: Items for the header region. * - page.primary_menu: Items for the primary menu region. * - page.secondary_menu: Items for the secondary menu region. * - page.highlighted: Items for the highlighted content region. * - page.help: Dynamic help text, mostly for admin pages. * - page.content: The main content of the current page. * - page.sidebar_first: Items for the first sidebar. * - page.sidebar_second: Items for the second sidebar. * - page.footer: Items for the footer region. * - page.breadcrumb: Items for the breadcrumb region. * * @see template_preprocess_page() * @see html.html.twig */ #} {% set nav_classes = 'navbar navbar-expand-lg' ~ (b4_navbar_schema != 'none' ? \" navbar-#{b4_navbar_schema}\" : ' ') ~ (b4_navbar_schema != 'none' ? (b4_navbar_schema == 'dark' ? ' text-light' : ' text-dark' ) : ' ') ~ (b4_navbar_bg_schema != 'none' ? \" bg-#{b4_navbar_bg_schema}\" : ' ') %} {% set footer_classes = ' ' ~ (b4_footer_schema != 'none' ? \" footer-#{b4_footer_schema}\" : ' ') ~ (b4_footer_schema != 'none' ? (b4_footer_schema == 'dark' ? ' text-light' : ' text-dark' ) : ' ') ~ (b4_footer_bg_schema != 'none' ? \" bg-#{b4_footer_bg_schema}\" : ' ') %} <header> {{ page.header }} {% if page.nav_branding or page.nav_main or page.nav_additional %} <nav class=\"{{ nav_classes }}\"> <div class=\"{{ b4_top_container }} row mx-auto\"> <div class=\"col-auto p-0\"> {{ page.nav_branding }} </div> <div class=\"col-3 col-md-auto p-0 text-right\"> <button class=\"navbar-toggler collapsed\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> </div> <div class=\"collapse navbar-collapse col-12 col-md-auto p-0 justify-content-end\" id=\"navbarSupportedContent\"> {{ page.nav_main }} {{ page.nav_additional }} </div> </div> </nav> {% endif %} </header> <main role=\"main\"> <a id=\"main-content\" tabindex=\"-1\"></a>{# link is in html.html.twig #} {% set sidebar_first_classes = (page.sidebar_first and page.sidebar_second) ? 'col-12 col-sm-6 col-lg-3' : 'col-12 col-lg-3' %} {% set sidebar_second_classes = (page.sidebar_first and page.sidebar_second) ? 'col-12 col-sm-6 col-lg-3' : 'col-12 col-lg-3' %} {% set content_classes = (page.sidebar_first and page.sidebar_second) ? 'col-12 col-lg-6' : ((page.sidebar_first or page.sidebar_second) ? 'col-12 col-lg-9' : 'col-12' ) %} <div class=\"{{ b4_top_container }}\"> {% if page.breadcrumb %} {{ page.breadcrumb }} {% endif %} <div class=\"row no-gutters\"> {% if page.sidebar_first %} <div class=\"order-2 order-lg-1 {{ sidebar_first_classes }}\"> {{ page.sidebar_first }} </div> {% endif %} <div class=\"order-1 order-lg-2 {{ content_classes }}\"> {{ page.content }} </div> {% if page.sidebar_second %} <div class=\"order-3 {{ sidebar_second_classes }}\"> {{ page.sidebar_second }} </div> {% endif %} </div> </div> </main> {% if page.footer %} <footer class=\"mt-auto {{ footer_classes }}\"> <div class=\"{{ b4_top_container }}\"> {{ page.footer }} </div> </footer> {% endif %} ", "themes/contrib/bootstrap4/templates/layout/page.html.twig", "C:\\xampp\\htdocs\\eshopbw\\themes\\contrib\\bootstrap4\\templates\\layout\\page.html.twig"); } } <file_sep># Bootstrap 4 subtheme ## Instructions ### Create subtheme by following these steps: * Copy `_SUBTHEME` folder to the location of custom folder * Rename `SUBTHEME` instances to your theme, e.g. if your theme called `b4theme`: * Rename `SUBTHEME.info` to `b4theme.info.yml` and its content * Rename `SUBTHEME.libraries.yml` to `b4theme.libraries.yml` * Rename `SUBTHEME.theme` to `b4theme.theme` and its comments * Update import path in `SUBTHEME/scss/style.scss` to Bootstrap 4 theme path `@import "[DOCROOT]/themes/contrib/bootstrap4/scss/style";`, eg replace [DOCROOT] with the relative path to your docroot. Final should look like `@import "../../../../../../themes/contrib/bootstrap4/scss/style";`. * (Optional) Copy `style-guide` folder to your subtheme. The link will be available on `Manage theme` screen. ### Tools You may setup your front end development workflow with npm/yarn by creating package.json and adding scripts to speed up development: * Use [compiler](https://sass-lang.com/install) to compile SCSS to CSS. * Use `eslint` and `sass-lint` to lint-check your SCSS and JS * Use `browser-sync` to auto-reload pages when specified files have been updated (eg updates to js/css/twig) * Use `lighthouse` to automatically test your colour pallet for accessibility issues (npm v8+ only) <file_sep><?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* core/themes/seven/templates/classy/views/views-view-table.html.twig */ class __TwigTemplate_f7fcce1c025e4c5d779528be10a01079fa419cb1461d223d8dc1d861b2ceaa7b extends \Twig\Template { public function __construct(Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = [ ]; $this->sandbox = $this->env->getExtension('\Twig\Extension\SandboxExtension'); $tags = ["set" => 35, "if" => 44, "for" => 59]; $filters = ["length" => 38, "escape" => 43, "merge" => 100]; $functions = []; try { $this->sandbox->checkSecurity( ['set', 'if', 'for'], ['length', 'escape', 'merge'], [] ); } catch (SecurityError $e) { $e->setSourceContext($this->getSourceContext()); if ($e instanceof SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } } protected function doDisplay(array $context, array $blocks = []) { // line 35 $context["classes"] = [0 => "views-table", 1 => "views-view-table", 2 => ("cols-" . twig_length_filter($this->env, $this->sandbox->ensureToStringAllowed( // line 38 ($context["header"] ?? null)))), 3 => (( // line 39 ($context["responsive"] ?? null)) ? ("responsive-enabled") : ("")), 4 => (( // line 40 ($context["sticky"] ?? null)) ? ("sticky-enabled") : (""))]; // line 43 echo "<table"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute(($context["attributes"] ?? null), "addClass", [0 => ($context["classes"] ?? null)], "method")), "html", null, true); echo "> "; // line 44 if (($context["caption_needed"] ?? null)) { // line 45 echo " <caption> "; // line 46 if (($context["caption"] ?? null)) { // line 47 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["caption"] ?? null)), "html", null, true); echo " "; } else { // line 49 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["title"] ?? null)), "html", null, true); echo " "; } // line 51 echo " "; if ( !twig_test_empty(($context["summary_element"] ?? null))) { // line 52 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["summary_element"] ?? null)), "html", null, true); echo " "; } // line 54 echo " </caption> "; } // line 56 echo " "; if (($context["header"] ?? null)) { // line 57 echo " <thead> <tr> "; // line 59 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(($context["header"] ?? null)); foreach ($context['_seq'] as $context["key"] => $context["column"]) { // line 60 echo " "; if ($this->getAttribute($context["column"], "default_classes", [])) { // line 61 echo " "; // line 62 $context["column_classes"] = [0 => "views-field", 1 => ("views-field-" . $this->sandbox->ensureToStringAllowed($this->getAttribute( // line 64 ($context["fields"] ?? null), $context["key"], [], "array")))]; // line 67 echo " "; } // line 68 echo " <th"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($this->getAttribute($this->getAttribute($context["column"], "attributes", []), "addClass", [0 => ($context["column_classes"] ?? null)], "method"), "setAttribute", [0 => "scope", 1 => "col"], "method")), "html", null, true); echo ">"; // line 69 if ($this->getAttribute($context["column"], "wrapper_element", [])) { // line 70 echo "<"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "wrapper_element", [])), "html", null, true); echo ">"; // line 71 if ($this->getAttribute($context["column"], "url", [])) { // line 72 echo "<a href=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "url", [])), "html", null, true); echo "\" title=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "title", [])), "html", null, true); echo "\" rel=\"nofollow\">"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "content", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "sort_indicator", [])), "html", null, true); echo "</a>"; } else { // line 74 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "content", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "sort_indicator", [])), "html", null, true); } // line 76 echo "</"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "wrapper_element", [])), "html", null, true); echo ">"; } else { // line 78 if ($this->getAttribute($context["column"], "url", [])) { // line 79 echo "<a href=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "url", [])), "html", null, true); echo "\" title=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "title", [])), "html", null, true); echo "\" rel=\"nofollow\">"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "content", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "sort_indicator", [])), "html", null, true); echo "</a>"; } else { // line 81 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "content", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "sort_indicator", [])), "html", null, true); } } // line 84 echo "</th> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['key'], $context['column'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 86 echo " </tr> </thead> "; } // line 89 echo " <tbody> "; // line 90 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(($context["rows"] ?? null)); foreach ($context['_seq'] as $context["_key"] => $context["row"]) { // line 91 echo " <tr"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["row"], "attributes", [])), "html", null, true); echo "> "; // line 92 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "columns", [])); foreach ($context['_seq'] as $context["key"] => $context["column"]) { // line 93 echo " "; if ($this->getAttribute($context["column"], "default_classes", [])) { // line 94 echo " "; // line 95 $context["column_classes"] = [0 => "views-field"]; // line 99 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "fields", [])); foreach ($context['_seq'] as $context["_key"] => $context["field"]) { // line 100 echo " "; $context["column_classes"] = twig_array_merge($this->sandbox->ensureToStringAllowed(($context["column_classes"] ?? null)), [0 => ("views-field-" . $this->sandbox->ensureToStringAllowed($context["field"]))]); // line 101 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['field'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 102 echo " "; } // line 103 echo " <td"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($this->getAttribute($context["column"], "attributes", []), "addClass", [0 => ($context["column_classes"] ?? null)], "method")), "html", null, true); echo ">"; // line 104 if ($this->getAttribute($context["column"], "wrapper_element", [])) { // line 105 echo "<"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "wrapper_element", [])), "html", null, true); echo "> "; // line 106 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "content", [])); foreach ($context['_seq'] as $context["_key"] => $context["content"]) { // line 107 echo " "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["content"], "separator", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["content"], "field_output", [])), "html", null, true); echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['content'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 109 echo " </"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["column"], "wrapper_element", [])), "html", null, true); echo ">"; } else { // line 111 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "content", [])); foreach ($context['_seq'] as $context["_key"] => $context["content"]) { // line 112 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["content"], "separator", [])), "html", null, true); echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["content"], "field_output", [])), "html", null, true); } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['content'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } // line 115 echo " </td> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['key'], $context['column'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 117 echo " </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 119 echo " </tbody> </table> "; } public function getTemplateName() { return "core/themes/seven/templates/classy/views/views-view-table.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 275 => 119, 268 => 117, 261 => 115, 253 => 112, 249 => 111, 244 => 109, 234 => 107, 230 => 106, 225 => 105, 223 => 104, 219 => 103, 216 => 102, 210 => 101, 207 => 100, 202 => 99, 200 => 95, 198 => 94, 195 => 93, 191 => 92, 186 => 91, 182 => 90, 179 => 89, 174 => 86, 167 => 84, 162 => 81, 152 => 79, 150 => 78, 145 => 76, 141 => 74, 131 => 72, 129 => 71, 125 => 70, 123 => 69, 119 => 68, 116 => 67, 114 => 64, 113 => 62, 111 => 61, 108 => 60, 104 => 59, 100 => 57, 97 => 56, 93 => 54, 87 => 52, 84 => 51, 78 => 49, 72 => 47, 70 => 46, 67 => 45, 65 => 44, 60 => 43, 58 => 40, 57 => 39, 56 => 38, 55 => 35,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Source("{# /** * @file * Theme override for displaying a view as a table. * * Available variables: * - attributes: Remaining HTML attributes for the element. * - class: HTML classes that can be used to style contextually through CSS. * - title : The title of this group of rows. * - header: The table header columns. * - attributes: Remaining HTML attributes for the element. * - content: HTML classes to apply to each header cell, indexed by * the header's key. * - default_classes: A flag indicating whether default classes should be * used. * - caption_needed: Is the caption tag needed. * - caption: The caption for this table. * - accessibility_description: Extended description for the table details. * - accessibility_summary: Summary for the table details. * - rows: Table row items. Rows are keyed by row number. * - attributes: HTML classes to apply to each row. * - columns: Row column items. Columns are keyed by column number. * - attributes: HTML classes to apply to each column. * - content: The column content. * - default_classes: A flag indicating whether default classes should be * used. * - responsive: A flag indicating whether table is responsive. * - sticky: A flag indicating whether table header is sticky. * - summary_element: A render array with table summary information (if any). * * @see template_preprocess_views_view_table() */ #} {% set classes = [ 'views-table', 'views-view-table', 'cols-' ~ header|length, responsive ? 'responsive-enabled', sticky ? 'sticky-enabled', ] %} <table{{ attributes.addClass(classes) }}> {% if caption_needed %} <caption> {% if caption %} {{ caption }} {% else %} {{ title }} {% endif %} {% if (summary_element is not empty) %} {{ summary_element }} {% endif %} </caption> {% endif %} {% if header %} <thead> <tr> {% for key, column in header %} {% if column.default_classes %} {% set column_classes = [ 'views-field', 'views-field-' ~ fields[key], ] %} {% endif %} <th{{ column.attributes.addClass(column_classes).setAttribute('scope', 'col') }}> {%- if column.wrapper_element -%} <{{ column.wrapper_element }}> {%- if column.url -%} <a href=\"{{ column.url }}\" title=\"{{ column.title }}\" rel=\"nofollow\">{{ column.content }}{{ column.sort_indicator }}</a> {%- else -%} {{ column.content }}{{ column.sort_indicator }} {%- endif -%} </{{ column.wrapper_element }}> {%- else -%} {%- if column.url -%} <a href=\"{{ column.url }}\" title=\"{{ column.title }}\" rel=\"nofollow\">{{ column.content }}{{ column.sort_indicator }}</a> {%- else -%} {{- column.content }}{{ column.sort_indicator }} {%- endif -%} {%- endif -%} </th> {% endfor %} </tr> </thead> {% endif %} <tbody> {% for row in rows %} <tr{{ row.attributes }}> {% for key, column in row.columns %} {% if column.default_classes %} {% set column_classes = [ 'views-field' ] %} {% for field in column.fields %} {% set column_classes = column_classes|merge(['views-field-' ~ field]) %} {% endfor %} {% endif %} <td{{ column.attributes.addClass(column_classes) }}> {%- if column.wrapper_element -%} <{{ column.wrapper_element }}> {% for content in column.content %} {{ content.separator }}{{ content.field_output }} {% endfor %} </{{ column.wrapper_element }}> {%- else -%} {% for content in column.content %} {{- content.separator }}{{ content.field_output -}} {% endfor %} {%- endif %} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> ", "core/themes/seven/templates/classy/views/views-view-table.html.twig", "C:\\xampp\\htdocs\\eshopbw\\core\\themes\\seven\\templates\\classy\\views\\views-view-table.html.twig"); } } <file_sep><?php namespace Drupal\ww_bootstrap4_layouts\Plugin\Layout; use Drupal\layout_builder\Plugin\Layout\MultiWidthLayoutBase; /** * Configurable Bootstrap4 row layout plugin class. * * @internal * Plugin classes are internal. */ class BsRowLayout extends MultiWidthLayoutBase { /** * {@inheritdoc} */ protected function getWidthOptions() { return [ '1-col' => '1 column', '2-col' => '2 column', '3-col' => '3 column', '4-col' => '4 column', ]; } /** * {@inheritdoc} */ public function build(array $regions) { foreach ($this->getPluginDefinition()->getRegionNames() as $region_name) { if (array_key_exists($region_name, $regions)) { foreach ($regions[$region_name] as $uuid => $block) { $regions[$region_name][$uuid]['#attributes']['class'][] = $this->getColumnWidth(); } } } return parent::build($regions); } /** * Get the Bootstrap classes by the selected column width. * * @return string * Bootstrap classes. */ protected function getColumnWidth() { $col = [ '1-col' => 'col-lg-12 mb-4', '2-col' => 'col-lg-6 mb-4', '3-col' => 'col-lg-4 mb-4', '4-col' => 'col-lg-3 mb-4', ]; return $col[$this->configuration['column_widths']]; } } <file_sep><?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* modules/custom/ww_bootstrap4_layouts/layouts/bs_carousel/layout--bs-carousel.html.twig */ class __TwigTemplate_11ac1f485836ec1198085362a59bfc3e75a9e5519a7cfbf4ad72c91c622ac154 extends \Twig\Template { public function __construct(Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = [ ]; $this->sandbox = $this->env->getExtension('\Twig\Extension\SandboxExtension'); $tags = ["if" => 13, "for" => 20]; $filters = ["escape" => 14, "without" => 40]; $functions = []; try { $this->sandbox->checkSecurity( ['if', 'for'], ['escape', 'without'], [] ); } catch (SecurityError $e) { $e->setSourceContext($this->getSourceContext()); if ($e instanceof SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } } protected function doDisplay(array $context, array $blocks = []) { // line 13 if (($context["content"] ?? null)) { // line 14 echo " <div"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["attributes"] ?? null)), "html", null, true); echo "> "; // line 16 if ($this->getAttribute(($context["content"] ?? null), "content", [])) { // line 17 echo " <div "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($this->getAttribute(($context["region_attributes"] ?? null), "content", []), "addClass", [0 => "layout__region", 1 => "layout__region--content"], "method")), "html", null, true); echo "> <div id=\"carousel--"; // line 18 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["carousel_id"] ?? null)), "html", null, true); echo "\" class=\"carousel slide\" data-ride=\"carousel\"> <ol class=\"carousel-indicators\"> "; // line 20 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(($context["items"] ?? null)); $context['loop'] = [ 'parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true, ]; if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof \Countable)) { $length = count($context['_seq']); $context['loop']['revindex0'] = $length - 1; $context['loop']['revindex'] = $length; $context['loop']['length'] = $length; $context['loop']['last'] = 1 === $length; } foreach ($context['_seq'] as $context["_key"] => $context["item"]) { // line 21 echo " <li data-target=\"#carousel--"; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["carousel_id"] ?? null)), "html", null, true); echo "\" data-slide-to=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($this->getAttribute($context["loop"], "index0", [])), "html", null, true); echo "\" class=\""; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar((($this->getAttribute($context["loop"], "first", [])) ? ("active") : (""))); echo "\"></li> "; ++$context['loop']['index0']; ++$context['loop']['index']; $context['loop']['first'] = false; if (isset($context['loop']['length'])) { --$context['loop']['revindex0']; --$context['loop']['revindex']; $context['loop']['last'] = 0 === $context['loop']['revindex0']; } } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 23 echo " </ol> <div class=\"carousel-inner\"> "; // line 25 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(($context["items"] ?? null)); $context['loop'] = [ 'parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true, ]; if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof \Countable)) { $length = count($context['_seq']); $context['loop']['revindex0'] = $length - 1; $context['loop']['revindex'] = $length; $context['loop']['length'] = $length; $context['loop']['last'] = 1 === $length; } foreach ($context['_seq'] as $context["_key"] => $context["item"]) { // line 26 echo " <div class=\"carousel-item "; echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar((($this->getAttribute($context["loop"], "first", [])) ? ("active") : (""))); echo "\"> "; // line 27 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed($context["item"]), "html", null, true); echo " </div> "; ++$context['loop']['index0']; ++$context['loop']['index']; $context['loop']['first'] = false; if (isset($context['loop']['length'])) { --$context['loop']['revindex0']; --$context['loop']['revindex']; $context['loop']['last'] = 0 === $context['loop']['revindex0']; } } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 30 echo " </div> <a class=\"carousel-control-prev\" href=\"#carousel--"; // line 31 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["carousel_id"] ?? null)), "html", null, true); echo "\" role=\"button\" data-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Previous</span> </a> <a class=\"carousel-control-next\" href=\"#carousel--"; // line 35 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->sandbox->ensureToStringAllowed(($context["carousel_id"] ?? null)), "html", null, true); echo "\" role=\"button\" data-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Next</span> </a> </div> "; // line 40 echo $this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->env->getExtension('Drupal\Core\Template\TwigExtension')->withoutFilter($this->sandbox->ensureToStringAllowed($this->getAttribute(($context["content"] ?? null), "content", [])), "field_carousel_items"), "html", null, true); echo " </div> "; } // line 43 echo " </div> "; } } public function getTemplateName() { return "modules/custom/ww_bootstrap4_layouts/layouts/bs_carousel/layout--bs-carousel.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 180 => 43, 174 => 40, 166 => 35, 159 => 31, 156 => 30, 139 => 27, 134 => 26, 117 => 25, 113 => 23, 92 => 21, 75 => 20, 70 => 18, 65 => 17, 63 => 16, 57 => 14, 55 => 13,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Source("{# /** * @file * Default theme implementation to display a two-column layout. * * Available variables: * - content: The content for this layout. * - attributes: HTML attributes for the layout <div>. * * @ingroup themeable */ #} {% if content %} <div{{ attributes }}> {% if content.content %} <div {{ region_attributes.content.addClass('layout__region', 'layout__region--content') }}> <div id=\"carousel--{{ carousel_id }}\" class=\"carousel slide\" data-ride=\"carousel\"> <ol class=\"carousel-indicators\"> {% for item in items %} <li data-target=\"#carousel--{{ carousel_id }}\" data-slide-to=\"{{ loop.index0 }}\" class=\"{{ loop.first ? 'active' }}\"></li> {% endfor %} </ol> <div class=\"carousel-inner\"> {% for item in items %} <div class=\"carousel-item {{ loop.first ? 'active' }}\"> {{ item }} </div> {% endfor %} </div> <a class=\"carousel-control-prev\" href=\"#carousel--{{ carousel_id }}\" role=\"button\" data-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Previous</span> </a> <a class=\"carousel-control-next\" href=\"#carousel--{{ carousel_id }}\" role=\"button\" data-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Next</span> </a> </div> {{ content.content|without('field_carousel_items') }} </div> {% endif %} </div> {% endif %} ", "modules/custom/ww_bootstrap4_layouts/layouts/bs_carousel/layout--bs-carousel.html.twig", "C:\\xampp\\htdocs\\eshopbw\\modules\\custom\\ww_bootstrap4_layouts\\layouts\\bs_carousel\\layout--bs-carousel.html.twig"); } }
a1ae919942ceddd0d009f4fa7a4ab3062fa34972
[ "Markdown", "PHP" ]
6
PHP
MMokhure/eshopbw
fe14cdb5036c0606e6de24441fd88dc472b7f673
ac907b6c9f1d125587c8bb449d6b99e564820ade
refs/heads/master
<file_sep>// Invoice.cpp // class member-function definitions. #include <iostream> using namespace std;Invoice #include "Invoice.h" // Invoice class definition Invoice::Invoice(string number,string style ,int sell ,int price ) { setInvoiceNumber(number); setInvoiceStyle(style); setInvoiceSell(sell); setInvoicePrice(price); } //Number void Invoice::setInvoiceNumber(string Number) { number=Number; } string Invoice::getInvoiceNumber() { return number; } //style void Invoice::setInvoiceStyle(string Style) { style=Style; } string Invoice::getInvoiceStyle() { return style; } //Sell void Invoice::setInvoiceSell(int Sell) { if(Sell<=0) sell=0; else sell=Sell; } int Invoice::getInvoiceSell() { return sell; } //price void Invoice::setInvoicePrice(int Price) { if(Price<=0) price=0; else price=Price; } int Invoice::getInvoicePrice() { return price; } //Ammount int Invoice::getInvoiceAmmount() { return sell*price; } <file_sep> // Create Date objects. #include <iostream> using namespace std; #include "Date.h" // include definition of class Date // function main begins program execution int main() { int Month; int Day; int Year; cout <<"plese input your number"<<endl; cout <<"Month(1~12)"<<endl; cin >>Month; cout <<"Day"<<endl; cin >>Day; cout <<"Year"<<endl; cin >>Year; Date date(Month,Day,Year); cout <<"检验数据:"<<endl; cout<<"Month:"<<date.getDateMonth()<<" "<<"Day:"<<date.getDateDay()<<" "<<"Year:"<<date.getDateYear()<<endl; cout <<"输出数据:"; date.getdisplayDate(); return 0; } // end main <file_sep> // Date class member-function definitions. #include <iostream> using namespace std; #include "Date.h" // Date class definition Date::Date(int month,int day,int year) { setDateMonth(month); setDateDay(day); setDateYear(year); } //Year void Date::setDateYear(int Year) { year=Year; } int Date::getDateYear() { return year; } //Month void Date::setDateMonth(int Month) { if(Month>=13) month=1; else month=Month; } int Date::getDateMonth() { return month; } //Day void Date::setDateDay(int Day) { day=Day; } int Date::getDateDay() { return day; } void Date::getdisplayDate( ) { cout<<"month/day/year:"<<month<<"/"<<day<<"/"<<year<<endl; } <file_sep>// github 3.13 // Invoice class definition. #include <iostream> using namespace std; #include "Invoice.h" // include definition of class Invoice // function main begins program execution int main() { string Number; string Style; int Sell; int Price; cout <<"零件号:"<<endl; cin >>Number; cout <<"零件描述:"<<endl; cin >>Style; cout <<"销售总量:"<<endl; cin >>Sell; cout <<"单价:"<<endl; cin >>Price; Invoice invoice(Number,Style,Sell,Price); cout <<"验证数据:"<<invoice.getInvoiceNumber()<<" "<<invoice.getInvoiceStyle()<<" "<<invoice.getInvoiceSell()<<" "<<invoice.getInvoicePrice()<<endl; cout <<"计算数据:"<<invoice.getInvoiceAmmount(); return 0; } // end main <file_sep>// github 3.13 // Invoice class definition. #include <string> // program uses C++ standard string class using namespace std; // Invoice class definition class Invoice { public: Invoice(string number ,string style ,int sell ,int price ); void setInvoiceNumber(string Number); string getInvoiceNumber(); void setInvoiceStyle(string Style); string getInvoiceStyle(); void setInvoiceSell(int Sell); int getInvoiceSell(); void setInvoicePrice(int Price); int getInvoicePrice(); int getInvoiceAmmount(); private: string number; string style; int sell ; int price; }; // end class Invoice <file_sep>// gitub——3.15 // Date class definition. #include <string> // program uses C++ standard string class using namespace std; // Date class definition class Date { public: Date(int year,int month,int day); void setDateYear(int Year); int getDateYear(); void setDateMonth(int Month); int getDateMonth(); void setDateDay(int Day); int getDateDay(); void getdisplayDate( ); private: int year; int month; int day; }; // end class Employee
bfe7e02195cdf922fb1649707e1c9ae135bd6005
[ "C++" ]
6
C++
zhouyuxaing/Assignment_03
20d560165640f10bbd5cc31f127d3286e7386a01
0094d5d6217753d2229d92aa98d48e830f8bd96e
refs/heads/master
<repo_name>binsom/Gzwx-vue<file_sep>/src/store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import axios from 'axios' import router from '../router' Vue.use(Vuex) const store = new Vuex.Store({ state: { // url:'http://192.168.3.11:9009/sgjbid',//测试环境 // url:'http://192.168.0.214:33333',//开发者环境 url:'https://jy.gzebid.cn/bid/',//生产环境 token: '', userInfo: {}, isLogin: false, todoTabType: ''// 待办详情页回退时,待办页tab切换到之前状态 }, mutations: { login (state, payload) { axios({ url: state.url+'/appLogin', method: 'post', transformRequest: [ function (data) { let ret = ''; for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret; } ], headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, data:{ username: payload.username, password: <PASSWORD> } }).then((response) => { console.log(response,'---------response'); if(response.data){ if(response.data.success === true){ state.isLogin = true; state.userInfo.name = response.data.data.name; state.userInfo.sessionId=response.data.data.sessionId; state.token = response.data.data.sessionId; //登录时获取的信息存起来 let userInfo={ 'token':state.token, 'isLogin':state.isLogin, 'name':state.userInfo.name } console.log(userInfo,'---------userInfo'); localStorage.setItem('userInfo',JSON.stringify(userInfo)); router.push({ name: "todo" }); }else if(response.data.success === false){ state.isLogin = false; } } Vue.$vux.alert.show({ title: response.data.message }); setTimeout(() => { Vue.$vux.alert.hide(); }, 2000); }).catch((response) => { console.log(response); }); }, // 退出 logout (state) { axios({ url: state.url+'/appLogout', method: 'get', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } }).then((response) => { state.isLogin = false; state.userInfo = {}; state.token = ''; //退出时置空 localStorage.setItem('userInfo',''); Vue.$vux.alert.show({title: response.data.message}); setTimeout(() => { Vue.$vux.alert.hide(); window.location.reload(); }, 1000); }).catch((response) => { console.log(response); }); }, //界面刷新后赋值 refresh(state){ //获取本地存储的登录信息 let userInfo=localStorage.getItem('userInfo'); if(userInfo){ userInfo=JSON.parse(userInfo); state.isLogin = userInfo.isLogin; state.userInfo.name = userInfo.name; state.token = userInfo.token; } } } }); export default store; // http response 服务器响应拦截器,这里拦截登录过期,并重新跳入登页重新获取token axios.interceptors.response.use( response => { if(response.data.message=='no_login'){ console.log('111'); //退出时置空 localStorage.setItem('userInfo',''); store.state.isLogin = false; store.state.userInfo = {}; store.state.token = ''; router.replace({ path: '/login', query: {redirect: router.currentRoute.fullPath} }) } return response; }, error => { return Promise.reject(error.response.data) // 返回接口返回的错误信息 }); //http request 请求前拦截 axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); }); <file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import VueRouter from 'vue-router' import axios from 'axios' import { LoadingPlugin } from 'vux' import store from './store/index' import { AlertPlugin } from 'vux' axios.defaults.withCredentials = true; Vue.prototype.axios = axios; Vue.config.productionTip = false Vue.use(AlertPlugin); Vue.use(VueRouter); Vue.use(LoadingPlugin); /* eslint-disable no-new */ new Vue({ router, store, render: h => h(App) }).$mount('#app-box'); router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { console.log(111); if (store.state.token.length > 0) { // 通过store获取当前的token是否存在 next(); }else { next({ path: '/login', query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由 }) } } else { next(); } }); router.afterEach((to,from,next) => { window.scrollTo(0,0); });
2846cf659647836fef34715ffda03764fbf83f96
[ "JavaScript" ]
2
JavaScript
binsom/Gzwx-vue
bdc62cdbca5dc3630180ef1cab74bfa7ca0ec181
6d4eeb9a1139123b83938262ab8a1897592168f4
refs/heads/master
<repo_name>sophiecheav/eligibilite-vote<file_sep>/elections.js function saluer(bipbip) { alert(`Bonjour ${bipbip} !`); } // Juste pour le bouton qui exécute Bonjour Pierre // document.querySelector('.hello-btn').addEventListener('click', function(){ // saluer('Pierre'); // }); document.querySelector('.hello-btn').addEventListener('click', function(){ var bipbip = document.querySelector('.prenom1').value; saluer(bipbip); }); function validerAge() { let x = document.querySelector('.age').value; if (x >= 18) { alert('Inscrivez-vous !');} else { alert('Vous êtes trop jeune...');} } document.querySelector('.age-btn').addEventListener('click', function() { validerAge(); });
1447e6c2a877f4c29311079a0f5d8b1461d5de92
[ "JavaScript" ]
1
JavaScript
sophiecheav/eligibilite-vote
d6e5226f53133dd265d0da64f053257bbb27a301
8abf93d5fcd36b790d2885eb49f398316de7399e
refs/heads/master
<file_sep>public function showTarget() { if (Auth::user()->hasRole('admin')) { $data['Area'] = Area::get(); $data['Regional'] = Regional::where('ID_AREA',3)->get(); $data['Branch'] = Branch::get(); $data['Cluster'] = Cluster::get(); $data['Service'] = Service::get(); return view('admin.showTarget', $data); } else { return redirect('/home'); } } public function inputTarget(Request $req) { $result = $this->calculatedTarget($req); $idarea = 3; $idregional = $req->input('INPUTREGIONAL'); $idbranch = $req->input('INPUTBRANCH'); $idcluster = $req->input('INPUTCLUSTER'); if ($idcluster == 'all') { $sasaran = Target::with('cluster') ->whereHas('cluster',function ($a) use ($idbranch) { $a->where('ID_BRANCH', $idbranch); })->get(); } else { $sasaran = Target::with('cluster') ->whereHas('cluster', function ($a) use ($idbranch) { $a->where('ID_BRANCH', $idbranch); })->where('ID_CLUSTER', $idcluster)->get(); } $data['area'] = $idarea; $data['regional'] = $idregional; $data['cluster'] = $idcluster; $data['result'] = $sasaran; $data['branch'] = $idbranch; $data['target'] = $result; return view('admin.inputTarget', $data); }<file_sep>public function findType(Request $req) { switch($req->nexttarget) { case 'regional': $data = Regional::where('ID_AREA',3)->get(); break; case 'branch': $data = Branch::where('ID_REGIONAL',$req->id)->get(); break; case 'cluster': $data = Cluster::where('ID_BRANCH',$req->id)->get(); break; } return json_encode($data); } public function reportGET() { return view('manager.report'); } <file_sep>private function getTarget($type, $target){ $sasaran = Target::whereHas('cluster', function($a) use($target, $type){ if($type == 'cluster') $a->where('ID', $target); else $a->whereHas('branch', function($b) use($target, $type){ if($type == 'branch') $b->where('ID', $target); else $b->whereHas('regional', function($c) use($target, $type){ if($type == 'regional') $c->where('ID', $target); else $c->whereHas('area', function($d) use($target, $type){ $d->where('ID', $target); }); }); }); })->get(); $target = $sasaran->sum('TARGET'); $target = floatval($target/1000000000); return $target; }<file_sep>public function uploadGET(Request $req) { if (Auth::user() - > hasRole('admin')) { $data['Area'] = Area::get(); $data['Regional'] = Regional::where('ID_AREA', 3)->get(); $data['Branch'] = Branch::get(); $data['Cluster'] = Cluster::get(); return view('admin.input', $data); } else { return back() ->withMessage('message','NoAccess!'); } } public function uploadPOST(Request $req) { $idarea = 3; $idregional = $req->input('INPUTREGIONAL'); $idbranch = $req->input('INPUTBRANCH'); $idcluster = $req->input('INPUTCLUSTER'); $file = $req->input('fileToUpload'); $detail = array( "area" => $idarea, "regional" => $idregional, "branch" => $idbranch, "cluster" => $idcluster); $startdate = $req->input('UPLOADDATE'); $finishdate = $req->input('FINISHDATE'); $terakhirdatedb = Revenue::where('ID_CLUSTER', $idcluster) ->orderBy('date', 'desc')->first(); $awal = strtotime($startdate); $akhir = strtotime($finishdate); if ($terakhirdatedb != null) { $terakhirdb = strtotime($terakhirdatedb['DATE']); $range = $awal - $terakhirdb; $range = intval($range/(60*60*24)); if ($range > 1) { dd("WrongDate"); } } $rangedate = $akhir - $awal; $rangedate = intval($rangedate/(60*60*24))+1; $date = DateTime::createFromFormat('D-M-d-Y', $startdate); $date_format = $date->format("Y-m-d"); $date_formated = explode("-", $date_format); $filepath = $this ->saveCSV($req, $date_formated, $date); return $this ->readCSV($filepath, $detail, $date_format, $rangedate); }
c1a4e62b9c41a43926f11ef41e34abdb6c294b74
[ "PHP" ]
4
PHP
rohanaq/Buku-KPku
a1835c98d974fa1ef60ea9176fd784198807751d
3b254bb96029305834e7a7e1d9771ac7a8ad8895
refs/heads/master
<repo_name>4rtemi5/ESP_Notify-DEPRECATED-<file_sep>/src/ESP_Notify.h #ifndef ESP_Notify_h #define ESP_Notify_h #include "ESP8266WiFi.h" class ESP_Notify { public: ESP_Notify(); ~ESP_Notify(); void sendNotification(String deviceId, String title, String message); void sendNotificationToTopic(String topic, String title, String message); }; #endif <file_sep>/examples/pir_alarm/pir_alarm.ino #include <ESP8266WiFi.h> #include <ESP_Notify.h> // define your values here //############################################################ #define WIFI_SSID "YOUR_WIFI_SSID" #define WIFI_PASSWORD "<PASSWORD>" #define DEVICE_ID "YOUR_DEVICE_ID" //############################################################ ESP_Notify notifier; int LED = 2; int PIR = D2; int interval = 5000; int previous_millis = millis(); boolean state = LOW; boolean newState = LOW; void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); pinMode(PIR, INPUT); //calling the connectToWifi() function connectToWifi(); } void loop() { if(WiFi.status() != WL_CONNECTED){ connectToWifi(); //reconnect in case of connection loss } update(); } void connectToWifi(){ // funtion to connect to WiFi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("\n\nconnecting"); while (WiFi.status() != WL_CONNECTED) { digitalWrite(LED, !digitalRead(LED)); // blink internal LED Serial.print("."); delay(500); } Serial.print("\nconnected: "); Serial.println(WiFi.localIP()); digitalWrite(LED, HIGH); } void update(){ newState = digitalRead(PIR); if (newState != state) { if(newState){ // sending Notification Serial.println("Movement started!"); notifier.sendNotification(DEVICE_ID, "Alarm!", "Movement in the room!"); digitalWrite(LED, LOW); }else{ // sending Notification Serial.println("Movement stopped!"); notifier.sendNotification(DEVICE_ID, "Alarm!", "Movement hast stopped!"); digitalWrite(LED, HIGH); } state = newState; } } <file_sep>/src/ESP_Notify.cpp #include "ESP_Notify.h" #include "ESP8266HTTPClient.h" ESP_Notify::ESP_Notify(){} ESP_Notify::~ESP_Notify(){} HTTPClient http; HTTPClient httpTOPIK; String SERVER_ID = "AAAAt9OorV0:<KEY>"; void ESP_Notify::sendNotification(String deviceId, String title, String message) { String data = "{"; data = data + "\"data\": {"; data = data + "\"body\" : \"" + message + "\","; data = data + "\"title\" : \"" + title + "\""; data = data + "},"; data = data + "\"registration_ids\": [\"" + deviceId + "\"]"; data = data + "}"; http.begin("http://fcm.googleapis.com/fcm/send"); http.addHeader("Authorization", "key=" + SERVER_ID); http.addHeader("Content-Type", "application/json"); http.addHeader("Host", "fcm.googleapis.com"); http.addHeader("Content-Length", String(message.length())); http.POST(data); http.writeToStream(&Serial); http.end(); Serial.println(); } void ESP_Notify::sendNotificationToTopic( String topic, String title, String message) { String data ="{"; data = data + "\"to\": \"/topics/" + topic + "\","; data = data + "\"data\": {"; data = data + "\"body\" : \"" + message +"\","; data = data + "\"title\" : \"" + title + "\""; data = data + "} }"; String key = "key=" + SERVER_ID; httpTOPIK.begin("http://fcm.googleapis.com/fcm/send"); httpTOPIK.addHeader("Authorization", key); httpTOPIK.addHeader("Content-Type", "application/json"); httpTOPIK.addHeader("Host", "fcm.googleapis.com"); httpTOPIK.addHeader("Content-Length", String(message.length())); httpTOPIK.POST(data); httpTOPIK.writeToStream(&Serial); httpTOPIK.end(); Serial.println(); }<file_sep>/library.properties name=ESP_Notify version=0.0.1 author=<NAME> maintainer=<NAME> sentence=Library for the <a href="https://www.play.goolge.com">ESP Notify App</a>. paragraph=Allows you to send Notifications to your phone easily. category=Device Control url=https://www.play.google.com architectures=esp8266 <file_sep>/examples/send_notification/send_notification.ino #include <ESP8266WiFi.h> #include <ESP_Notify.h> // input your values here //############################################################ #define WIFI_SSID "YOUR_WiFi_SSID" #define WIFI_PASSWORD "<PASSWORD>" #define DEVICE_ID "YOUR_DEVICE_ID" //############################################################ // define a notifier ESP_Notify notifier; void setup() { Serial.begin(115200); // connect to wifi. WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("\n\nconnecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.print("\nconnected: "); Serial.println(WiFi.localIP()); // Send notification notifier.sendNotification(DEVICE_ID, "Hello World!", "Stuff, Stuff!"); } void loop() { //empty loop }<file_sep>/README.md # ESP_Notify (DEPRECATED) This Arduino library can send Notifications to your phone from every ESP8266 platform. It does so via the ESP_Notify Android app, that can be downloaded [here](https://play.google.com/store/apps/details?id=com.espnotify.rpi.android.espnotify). Simply download and intall the library, install the App on your Android phone, send yoursel the Token from the app and insert it into an example sketch and start sending yourself notifications whenever there is something interesting happening on your device. You can find an Instructable [here](https://www.instructables.com/id/Send-Notifications-to-Your-Phone-From-an-ESP8266-1).
9341d35093a69d2156af9728068494ee611898c8
[ "Markdown", "C++", "INI" ]
6
C++
4rtemi5/ESP_Notify-DEPRECATED-
e9a5b700b9f4882c1b460cbf32f627156fe8adfd
84ed8b698262f63148f31ae87304e29c3ef51703
refs/heads/master
<repo_name>TurboPtys/PDC<file_sep>/main.cpp #include "curses.h" #include <iostream> #include <Windows.h> #include <thread> #include <cstdlib> #include <semaphore.h> #include <pthread.h> #define NUMBER_OF_PHILOSOPHERS 5 bool sztucce[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; char sztucceC[10] = { 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W' }; float progres[10] = { 5, 7, 6, 9, 2, 8, 2, 5, 6, 4 }; int stan[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; float glod[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; char kolor[10] = { 'R', 'Y', 'G', 'B', 'C', 'R', 'Y', 'G', 'B', 'C' }; bool fin = false; using namespace std; sem_t waiter; sem_t fork[NUMBER_OF_PHILOSOPHERS]; pthread_t philosophers[NUMBER_OF_PHILOSOPHERS]; class FILOZOF{ public: FILOZOF(); FILOZOF(int a); int index; void *life(void){ while (true){ if (fin){ break; } // //myślenie // stan[index] = 0; while (progres[index] != 0){ Sleep(250); progres[index] = progres[index] - 0.25; } // //czekanie na kelenra // stan[index] = 1; progres[index] = 1; while (progres[index]) { Sleep(250); progres[index] = progres[index] - 0.25; } sem_wait(&waiter); // //siedzi przy stole // stan[index] = 2; int right = (index + 1) % NUMBER_OF_PHILOSOPHERS; int left = (index) % NUMBER_OF_PHILOSOPHERS; progres[index] = 1; while (progres[index]) { Sleep(250); progres[index] = progres[index] - 0.25; } sem_wait(&fork[right]); sem_wait(&fork[left]); sztucce[right] = true; sztucce[left] = true; sztucceC[right] = kolor[index]; sztucceC[left] = kolor[index]; // //jedzenie // progres[index] = (rand() % 5) + 5; stan[index] = 3; while (progres[index] != 0){ Sleep(250); progres[index] = progres[index] - 0.25; } // //odkladanie sztuccy // stan[index] = 4; progres[index] = 0.5; while (progres[index] != 0){ Sleep(250); progres[index] = progres[index] - 0.25; } sztucce[right] = false; sztucce[left] = false; sztucceC[right] = 'W'; sztucceC[left] = 'W'; sem_post(&fork[left]); sem_post(&fork[right]); sem_post(&waiter); stan[index] = 0; progres[index] = (rand() % 5) + 5; } } static void *exe(void *context){ return ((FILOZOF *)context)->life(); } }; FILOZOF::FILOZOF(int a){ index = a; } FILOZOF::FILOZOF(){ index = NULL; } char p='a'; bool elo = false; void* check(void *){ do{ p = getch(); } while (p != 'q'); fin = true; return NULL; } int main(){ srand(time(NULL)); FILOZOF filo[NUMBER_OF_PHILOSOPHERS]; for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++){ filo[i] = FILOZOF(i); } sem_init(&waiter, 0, NUMBER_OF_PHILOSOPHERS - 1); for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) { sem_init(&fork[i], 0, 1); } pthread_t cyk; pthread_create(&cyk, NULL, check, NULL); for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) { pthread_create(&philosophers[i], NULL, &FILOZOF::exe, &filo[i]); } //try{ int i = 0; initscr(); //Start if (has_colors() == TRUE) //1 { while (true){ start_color(); //2 init_pair(1, COLOR_WHITE, COLOR_BLACK); //3 attron(COLOR_PAIR(1)); //4 printw("SO2 PROJEKT - FILZOFOWIE \t"); attron(A_BOLD); printw("Czas: %.2f s", (float)i / 4); attroff(A_BOLD); printw("\n\nSZTUCCE: "); for (int j = 0; j < NUMBER_OF_PHILOSOPHERS; j++){ if (sztucceC[j] == 'R'){ attroff(COLOR_PAIR(1)); init_pair(2, COLOR_RED, COLOR_BLACK); attron(COLOR_PAIR(2)); printw(" %d ", j); attroff(COLOR_PAIR(2)); } else if (sztucceC[j] == 'Y'){ attroff(COLOR_PAIR(1)); init_pair(3, COLOR_YELLOW, COLOR_BLACK); attron(COLOR_PAIR(3)); printw(" %d ", j); attroff(COLOR_PAIR(3)); } else if (sztucceC[j] == 'G'){ attroff(COLOR_PAIR(1)); init_pair(4, COLOR_GREEN, COLOR_BLACK); attron(COLOR_PAIR(4)); printw(" %d ", j); attroff(COLOR_PAIR(4)); } else if (sztucceC[j] == 'B'){ attroff(COLOR_PAIR(1)); init_pair(5, COLOR_BLUE, COLOR_BLACK); attron(COLOR_PAIR(5)); printw(" %d ", j); attroff(COLOR_PAIR(5)); } else if (sztucceC[j] == 'C'){ attroff(COLOR_PAIR(1)); init_pair(6, COLOR_CYAN, COLOR_BLACK); attron(COLOR_PAIR(6)); printw(" %d ", j); attroff(COLOR_PAIR(6)); } else if (sztucceC[j] == 'W'){ printw(" %d ", j); } } init_pair(1, COLOR_WHITE, COLOR_BLACK); attron(COLOR_PAIR(1)); printw("\n\n\nFILOZOFOWIE: \tCZYNNOSC\t\t\tPROGRES\tGLOD"); attroff(COLOR_PAIR(1)); //SOKRATES init_pair(2, COLOR_RED, COLOR_BLACK); attron(COLOR_PAIR(2)); printw("\n\nSOKRATES: \t"); if (stan[0] == 0){ printw("medytuje\t"); } else if (stan[0] == 1){ printw("czeka na kelnera"); } else if (stan[0]==2) { printw("siedzi przy stole"); } else if (stan[0]==3){ printw("je\t\t"); } else if (stan[0] == 4){ printw("oddklada sztucce"); } printw("\t\t%.2f s",progres[0]); printw("\t %.2f s", glod[0]); attroff(COLOR_PAIR(2)); //PLATON init_pair(3, COLOR_YELLOW, COLOR_BLACK); attron(COLOR_PAIR(3)); printw("\n\nPLATON: \t"); if (stan[1] == 0){ printw("medytuje\t"); } else if (stan[1] == 1){ printw("czeka na kelnera"); } else if (stan[1] == 2) { printw("siedzi przy stole"); } else if (stan[1] == 3){ printw("je\t\t"); } else if (stan[1] == 4){ printw("oddklada sztucce"); } printw("\t\t%.2f s", progres[1]); printw("\t %.2f s",glod[1]); attroff(COLOR_PAIR(3)); //ARYSTOTELES init_pair(4, COLOR_GREEN, COLOR_BLACK); attron(COLOR_PAIR(4)); printw("\n\nARYSTOTELES: "); if (stan[2] == 0){ printw("\tmedytuje\t"); } else if (stan[2] == 1){ printw("\tczeka na kelnera"); } else if (stan[2] == 2) { printw("\tsiedzi przy stole"); } else if (stan[2] == 3){ printw("\tje\t\t"); } else if (stan[2] == 4){ printw("\toddklada sztucce"); } printw("\t\t%.2f s", progres[2]); printw("\t %.2f s", glod[2]); attroff(COLOR_PAIR(4)); //EPIKUR init_pair(5, COLOR_BLUE, COLOR_BLACK); attron(COLOR_PAIR(5)); printw("\n\nEPIKUR: "); if (stan[3] == 0){ printw("\tmedytuje\t"); } else if (stan[3] == 1){ printw("\tczeka na kelnera"); } else if (stan[3] == 2) { printw("\tsiedzi przy stole"); } else if (stan[3] == 3){ printw("\tje\t\t"); } else if (stan[3] == 4){ printw("\toddklada sztucce"); } printw("\t\t%.2f s", progres[3]); printw("\t %.2f s", glod[3]); attroff(COLOR_PAIR(5)); //ZENON init_pair(6, COLOR_CYAN, COLOR_BLACK); attron(COLOR_PAIR(6)); printw("\n\nZENON: \t"); if (stan[4] == 0){ printw("\tmedytuje\t"); } else if (stan[4] == 1){ printw("\tczeka na kelnera"); } else if (stan[4] == 2) { printw("\tsiedzi przy stole"); } else if (stan[4] == 3){ printw("\tje\t\t"); } else if (stan[4] == 4){ printw("\toddklada sztucce"); } printw("\t\t%.2f s", progres[4]); printw("\t %.2f s", glod[4]); attroff(COLOR_PAIR(6)); //Wyłączenie koloru tekstu //attroff(COLOR_PAIR(2)); //1 if (NUMBER_OF_PHILOSOPHERS > 5){ for (int u = 5; u < NUMBER_OF_PHILOSOPHERS; u++){ init_pair(2, COLOR_RED, COLOR_BLACK); attron(COLOR_PAIR(2)); printw("\n\%d %c: \t\t", u,kolor[u]); if (stan[u] == 0){ printw("medytuje\t"); } else if (stan[u] == 1){ printw("czeka na kelnera"); } else if (stan[u] == 2) { printw("siedzi przy stole"); } else if (stan[u] == 3){ printw("je\t\t"); } else if (stan[u] == 4){ printw("oddklada sztucce"); } printw("\t\t%.2f s", progres[u]); printw("\t %.2f s", glod[u]); attroff(COLOR_PAIR(2)); } } Sleep(250); refresh(); clear(); i++; for (int j = 0; j < NUMBER_OF_PHILOSOPHERS; j++){ if (stan[j] != 3){ glod[j] = glod[j] + 0.25; } else { glod[j] = 0; } } if (fin){ break; } } refresh(); clear(); endwin(); printf("Trwa zamykanie watkow ..."); pthread_join(cyk, NULL); for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) { pthread_join(philosophers[i], NULL); } sem_destroy(&waiter); for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) { sem_destroy(&fork[i]); } //int a; //a = getchar(); } else { printw("Twoja Konsolka nie obsluguje kolorow. :/ "); } return 0; }<file_sep>/README.md # PDC Problem ucztujących filozofów
f5873b4f68a35ed490a6a89d52d12f94a049b6e3
[ "Markdown", "C++" ]
2
C++
TurboPtys/PDC
eb127d67b28a97b322406c12ff046f41a11c93dc
9574705bcc6351b632416260346aabe7b06091da
refs/heads/master
<file_sep>module.exports.get = (req, res, next) => req.mongo.collection('compras') .find( { 'pizzas.puntos': { $gt: 2 } } // query ) .toArray((err, result) => res.send(result))<file_sep>module.exports.get = (req, res, next) => req.mongo.collection('compras') .updateOne( { ciudad: "Capital" }, { ciudad: "Ourense" } ) .toArray((err, result) => res.send(result))<file_sep>module.exports.get = (req, res, next) => { let map = function() { this.pizzas.map(p => { emit(`${this.pais}`, p.pizza) emit(`${this.pais}-${this.ciudad}`, p.pizza) }) } let reduce = function(key, values) { let sumaDePizasPorSabor = {} values.map(k => { sumaDePizasPorSabor[k] ? sumaDePizasPorSabor[k]++ : sumaDePizasPorSabor[k] = 1 }) return sumaDePizasPorSabor } let options = { out: {inline: 1} } req.mongo.collection('compras').mapReduce(map, reduce, options) .then(r => res.send(r)) }<file_sep>module.exports.post = (req, res, next) => { req.mongo.collection('inventory').insertMany([ { _id : 1, sku : 'almonds', description: 'product 1', instock : 120 }, { _id : 2, sku : 'bread', description: 'product 2', instock : 80 }, { _id : 3, sku : 'cashews', description: 'product 3', instock : 60 }, { _id : 4, sku : 'pecans', description: 'product 4', instock : 70 }, { _id : 5, sku: null, description: 'Incomplete' }, { _id : 6 } ]) req.mongo.collection('orders').insertMany([ { _id : 1, item : 'almonds', price : 12, quantity : 2 }, { _id : 2, item : 'pecans', price : 20, quantity : 1 }, { _id : 3 } ]) res.send('ok') } module.exports.get = (req, res, next) => { req.mongo.collection('orders').aggregate([ { $lookup: { from: 'inventory', localField: 'item', foreignField: 'sku', as: 'inventory_docs' } } ]) .toArray((error, resultado) => res.send(resultado)) }<file_sep>/** * Cargar módulos */ const fs = require('fs'), app = require('express')(), MongoClient = require('mongodb').MongoClient /** * Saludar */ app.get('/', (req, res) => res.send('🦄 funciona!')) /** * Programa principal */ MongoClient.connect(process.env.MONGO_URL, { // Conectar a MongoDB useNewUrlParser: true }) .then((client) => { // Exponer la base de datos a las rutas de express app.use((req, res, next) => {req.mongo = client.db('js_ourense'); next() }) // Cargar las rutas de Express de forma dinámica fs.readdir(`${__dirname}/rutas`, (err, files) => { files.map(file => { const controller = require(`${__dirname}/rutas/${file}`) const endpoint = `/${file.replace('.js', '')}` if (controller.get) app.get(endpoint, controller.get) if (controller.post) app.post(endpoint, controller.post) }) }) // Escuchar peticiones al servidor app.listen(process.env.PORT || 3000) })<file_sep>const listas = require('../listas') module.exports.post = (req, res, next) => req.mongo.collection('compras') .insertMany(listas.nombres.map(nombreCliente => { return { pais: listas.random('paises')[0], ciudad: listas.random('ciudades')[0], nombreCliente, pizzas: listas.random('pizzas').slice(0,3).map(pizza => { return { pizza, puntos: Math.floor(Math.random() * 10) } }), precio: Math.floor(Math.random() * 100), fecha: new Date() } })) .then(result => res.send(result))<file_sep>module.exports.get = (req, res, next) => req.mongo.collection('compras') .find({ pizzas: { $elemMatch: { pizza: 'Napolitana', puntos: { $gte: 5 } } } }) .toArray((err, result) => res.send(result))<file_sep># My talks and presentations - [Virtual worlds. Uses and technologies.](https://github.com/joseconstela/talks-and-presentations/raw/master/1-Virtual_Worlds_-_Uses_and_possibilities/160409-usos-y-posibilidades-secondlife-uvigo-esei-joseramoncidconstela.pdf) for [ESEI, University of Vigo](http://www.esei.uvigo.es/) - 2009 - [Web applications development, basic introduction for junior students](https://github.com/joseconstela/talks-and-presentations/raw/master/2-Web_Applications_development_-_Introduction_for_development_students/100311-web-applications-development-intro-joseramoncidconstela.pdf) for [CIF A Carballeira](http://www.cifpcarballeira.es/) - 2011 - [Web applications development, technologies and browsers, basic introduction for university students](https://github.com/joseconstela/talks-and-presentations/raw/master/3-Web_Applications_development_-_Tech_and_browsers/050611-web-applications-development-uvigo-esei-presentation.pdf) for [ESEI, University of Vigo](http://www.esei.uvigo.es/) - 2011 - “Passion, what moves us to make a difference”. IES A Carballeira. - [Introduction to MeteorJS](https://github.com/JavaScriptGalicia/JSGalicia-170718-meteorjs) for [JavaScript Galicia meetup](https://www.meetup.com/es-ES/JavaScriptGalicia) - 2017 - [MongoDB](https://www.youtube.com/watch?v=qf-XTg2RYmA) for [JavaScript Ourense Meetup](https://www.meetup.com/es-ES/jsourense/events/256998888/) - 2018 - [190627 # MQTT: comunicando tus dispositivos IoT (+ NodeJS)](https://www.youtube.com/watch?v=dlpPiYQvnGo) for [JavaScript Ourense Meetup](https://www.meetup.com/es-ES/jsourense/events/262390313/) - 2019 Generic presentations ===================== - [MongoDB basic introduction](https://github.com/joseconstela/talks-and-presentations/raw/master/Generic/MongoDB_introduction.pdf) - made for coworkers - 2013
bcb08dc52d38eb51089094e08d08f7a7e554a71a
[ "JavaScript", "Markdown" ]
8
JavaScript
joseconstela/talks-and-presentations
3fc350c970b1f363ce31df573cc9de0b1263b0eb
5e49af9279281bb8ceac055024ef844262af234c
refs/heads/master
<file_sep>KLADR API JS client for Rails Asset Pipeline ============================================ [JS client for KLADR API servise as jQuery plugin] [plugin] by [@garakh] [author] packaged for Ruby on Rails asset pipeline. [![Gem Version](https://badge.fury.io/rb/jquery-kladr-rails.png)](http://badge.fury.io/rb/jquery-kladr-rails) **THIS GEM IS NO MORE MAINTAINED!** Using [Rails Assets] to install this library instead is _strongly_ encouraged and recommended! Rails Assets is much better in publishing JS libraries as gems for rails asset pipeline and keeping them up to date than me. So use it and be happy! Installation of plugin from [Bower] via [Rails Assets] ------------------------------------------------------ Just do the three simple steps: 1. Add this to your `Gemfile` ```ruby source 'https://rails-assets.org' do gem 'rails-assets-jquery.kladr' end ``` 2. Add this line to `app/assets/stylesheets/application.css`: *= require jquery.kladr/jquery.kladr.min And this line to `app/assets/javascripts/application.js`: //= require jquery.kladr 3. Enjoy with the original [plugin] README and official [examples] Upgrading from Rubygems gem release to Rails Assets gem release --------------------------------------------------------------- 1. Remove from `Gemfile` string `gem 'jquery-kladr-rails'` 2. Remove `require jquery.kladr` from your asset manifests. 3. Follow installation instructions above. Installation of this gem from RubyGems (discouraged) ---------------------------------------------------- **THIS GEM IS NO MORE MAINTAINED!** E.g. no updates from upstream. Add this line to your application's Gemfile: gem 'jquery-kladr-rails' And then execute: $ bundle Add this line to `app/assets/stylesheets/application.css`: *= require jquery.kladr Add this line to `app/assets/javascripts/application.js`: //= require jquery.kladr Usage ----- See the original [plugin] README and official [examples]. Contributing ------------ 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request ### Version policy This gem version number is in form of **X.Y.Z.P**, where **X.Y.Z** is a version of original [plugin] and **P** is a gem-specific patch level. [plugin]: https://github.com/garakh/kladrapi-jsclient [author]: https://github.com/garakh [examples]: http://kladr-api.ru/examples/ "Official site examples" [Rails Assets]: https://rails-assets.org/ [Bower]: http://bower.io/ <file_sep>require "jquery/kladr/rails/version" module Jquery module Kladr module Rails class Engine < ::Rails::Engine end end end end <file_sep>module Jquery module Kladr module Rails VERSION = '1.4.1.0' end end end <file_sep>source 'https://rubygems.org' # Specify your gem's dependencies in jquery-kladr-rails.gemspec gemspec
c670cf2974cece6b25bf11844d44f9131622e26c
[ "Markdown", "Ruby" ]
4
Markdown
Envek/jquery-kladr-rails
3a46d6ea61b0a396c68c0e31837be22612df2d47
c44779695d63bd69db89aac55ae2010d3c718468
refs/heads/master
<repo_name>ba6a-yaga/webappcars<file_sep>/src/components/carousel/carousel.js import React, { Component } from 'react' import Row from "../grid/grRow" import Col from "../grid/grCol" import './carousel.scss' import Button from "../button/button" import Radium from 'radium' import arrow from "../../static/arrow.svg"; import Carousel from 'nuka-carousel'; class MainBlock extends Component { state = { current: this.props.current } updateStyle = () => { } nextCarouselSlide = () => { if (this.state.current === 2) { this.carouselRef.goToSlide(this.handleCurrentSlide(this.state.current+1)) } this.carouselRef.nextSlide() } prevCarouselSlide = () => { if (this.state.current === 0) { this.carouselRef.goToSlide(this.handleCurrentSlide(this.state.current-1)) } this.carouselRef.previousSlide() } // handleCurrentSlide = (n) => { if (n < 0) { return this.props.title.length-1 } else if (n > (this.props.title.length-1)) { return 0 } else { return n } } componentDidMount() { if (this.props.title.length > 0) { setTimeout(() => { var leftTextPreview = document.getElementById('leftTextPreview') var rightTextPreview = document.getElementById('rightTextPreview') leftTextPreview.classList.add("animationShowWithoutOpacity") rightTextPreview.classList.add("animationShowWithoutOpacity") }, 1000) } } componentWillUnmount() { } render() { if (typeof this.props.title !== 'undefined') { const current = this.state.current return ( <Row> <Col hd={1} dt={0}/> <Col styleProperties={{justifyContent: 'flex-end'}} hd={1} dt={1} tb={0} mb={0}> <p id={'leftTextPreview'} className={'textPreview'}>{this.props.title[this.handleCurrentSlide(current - 1)]}</p> </Col> <Col hd={8} dt={10} tb={12} mb={12}> <div id={'titleCarousel'} className={'titleCarousel'}> {this.props.title[current]} </div> <div className={'centralBlock-wrapper'}> <Carousel className={'imgCarousel-block'} afterSlide={a => this.setState({ current: a }) } ref={carouselRef => { this.carouselRef = carouselRef }} heightMode={'first'} initialSlideHeight={500} withoutControls={true}> {this.props.img.map((img, k) => { return ( <img key={k} src={img} alt={""} /> ) })} </Carousel> <Button onClick={this.prevCarouselSlide} id={'btnPrev'} className={'buttonNavPrev'}> <img src={arrow} alt=""/> </Button> <Button onClick={this.nextCarouselSlide} id={'btnNext'} className={'buttonNavNext'}> <img src={arrow} alt=""/> </Button> <Button onClick={this.props.handleClickBtn} text={"Оставить заявку"} className={'centralBlock-btn'}> <img className={'imgArrow'} alt=""/> </Button> </div> </Col> <Col styleProperties={{justifyContent: 'flex-start', backgroundColor: '#FF1F27'}} hd={1} dt={1} tb={0} mb={0}> <p id={'rightTextPreview'} className={'textPreview'}>{this.props.title[this.handleCurrentSlide(current + 1)]}</p> </Col> <Col hd={1} dt={0}/> </Row> ) } return null } } export default Radium(MainBlock); <file_sep>/src/components/grid/grCol.js import React from 'react' class Col extends React.Component { constructor(props) { super(props) this.state = { style: { } } } updateStyle = () => { const resolution = { mb:800, tb:1024, dt:1366, hd:1920, } const width = window.innerWidth; switch(true) { case width <= resolution.mb: this.setState({ style:{ // position:'relative', display: (this.props.mb === 0) ? 'none':'flex', flexGrow: this.props.mb, flexBasis: '0px', } }) break case width <= resolution.tb: // console.log() this.setState({ style:{ // position:'relative', display: (this.props.tb === 0) ? 'none':'flex', flexGrow: this.props.tb, flexBasis: '0px', } }) break case width <= resolution.dt: this.setState({ style:{ // position:'relative', display: (this.props.dt === 0) ? 'none':'flex', flexGrow: this.props.dt, flexBasis: '0px', } }) break default: this.setState({ style:{ // position:'relative', display: (this.props.hd === 0) ? 'none':'flex', flexGrow: this.props.hd, flexBasis: '0px', } }) break } } componentWillMount() { this.updateStyle() } componentDidMount() { window.addEventListener("resize", this.updateStyle) } componentWillUnmount() { window.removeEventListener("resize", this.updateStyle) } render() { return ( <div className={this.props.className} id={this.props.id} style={{...this.state.style,...this.props.styleProperties}}> {this.props.children} </div> ) } } export default Col<file_sep>/src/components/menu/menu.js import React from 'react' import logo from '../../static/logo.svg' import MenuList from './menuList' import Row from '../grid/grRow' import Col from '../grid/grCol' import './menu.scss' class Menu extends React.Component { render() { const style = { rowMenu: { height: 80 }, leftMenu: { alignItems: 'center', justifyContent: 'flex-start' }, rightMenu: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#FF1F27', }, leftPreviewImg: { height: 470, backgroundColor: '#fff', }, rightPreviewImg: { height: 470, backgroundColor: '#FF1F27', } } return ( <React.Fragment> <Row styleProperties={style.rowMenu} className={'row-menu'}> <Col hd={1} /> <Col hd={1} dt={1} tb={0} mb={0}/> <Col styleProperties={style.leftMenu} hd={4} dt={5} tb={6} mb={5}> <img className={'logo'} src={logo} alt={''}/> </Col> <Col styleProperties={style.rightMenu} hd={4} mb={0} tb={6} dt={5}> <MenuList position={'bottom'} size={100} elements={this.props.elements}/> </Col> <Col hd={0} dt={0} tb={0} mb={5}/> <Col hd={1} dt={1} tb={0} mb={0} styleProperties={{backgroundColor: '#FF1F27'}}></Col> <Col hd={1} /> </Row> </React.Fragment> ) } } export default Menu<file_sep>/src/components/partners/partners.js import React from 'react' import Row from "../grid/grRow"; import Col from "../grid/grCol"; const Partners = (props) => { return ( <React.Fragment> <div id="partners" className={'titlePartners'}>{props.title}</div> <Row> <Col hd={1} dt={1} tb={1} mb={1} styleProperties={{height:50}}> </Col> </Row> <Row> <Col hd={4} dt={3} tb={3} mb={0}></Col> <Col hd={4} dt={6} tb={6} mb={12} styleProperties={{justifyContent:'center'}}> <div className={'blockPartners-wrapper'}> {props.tile.map((tile,k)=>{ return ( <div key={k} className={'blockPartners-tile'}> <div className={'tileIcon'}> <img alt="" src={tile.icon} /> </div> <div className={'tileTitle'}>{tile.title}</div> <div className={'tileDesc'}>{tile.desc}</div> </div> ) })} </div> </Col> <Col hd={4} dt={3} tb={3} mb={0}></Col> </Row> </React.Fragment> ) } export default Partners<file_sep>/src/components/footer/footer.js import React from 'react' import Col from "../grid/grCol"; import logo from "../../static/logo3.svg"; import MenuList from "../menu/menuList"; import Row from "../grid/grRow"; import { Map, Marker } from 'yandex-map-react'; class Footer extends React.Component { render() { return ( <Row styleProperties={{flexWrap:'wrap'}}> <Col hd={2} dt={1} tb={0} mb={0} styleProperties={{backgroundColor:'#FF1F27'}}/> <Col styleProperties={{minWidth:'375px'}} hd={4} dt={5} tb={6} mb={12}> <div id="footer" className={'blockLeftFooter-wrapper'}> <div className={'blockFooter-cntr'}> <div className={'logo'}> <img alt={''} src={logo} /> </div> <div className={'infoBlock'}> <p className={'tileDesc'}>{this.props.desc}</p> <p className={'tileTitle'}>{this.props.title}</p> </div> <div className={'contactsBlock'}> <p className={'tileTitle'}>{this.props.phone}</p> <p className={'tileDesc'}>{this.props.email}</p> </div> <a href={'#footer'} className={'blockFooter-btn'}>{this.props.titleBtn}</a> <div className={'empty'}></div> <div className={'hr'}></div> <div className={'menu'}> <MenuList position={'top'} size={90} elements={this.props.elements}/> </div> </div> </div> </Col> <Col styleProperties={{minWidth:'375px'}} hd={6} dt={6} tb={6} mb={12}> <div className={'blockRightFooter-wrapper'}> <Map onAPIAvailable={function () { console.log('API loaded'); }} center={[55.76, 37.64]} zoom={10} width={'100%'} height={'100%'}> <Marker lat={55.694843} lon={37.435023} /> </Map> </div> </Col> </Row> ) } } export default Footer<file_sep>/src/components/menu/menuList.js import React from 'react' import {MdArrowDropDown,MdArrowDropUp} from 'react-icons/md' class MenuList extends React.Component { scrollTo = (id) => { if (id !== "") { console.log("id", id) let element = document.getElementById(id) element.scrollIntoView({block: "start", behavior: "smooth"}) } } render() { if (typeof this.props.elements !== 'undefined') { const position = this.props.position return ( <div className={'menuList-wrapper'} style={Boolean(this.props.size) ? {gridTemplateColumns: 'repeat(4, minmax(' + this.props.size + 'px, 1fr))'} : null}> {this.props.elements.map((e, i) => { return ( <div className={'menuList'} key={i}> {Boolean(e.isElementSelect) ? <button id={'isElementSelect'} onClick={e.handleClick} className={Boolean(e.active) ? 'active' : 'simple'}>{e.name} </button> : <button onClick={()=>{this.scrollTo(e.link)}} className={Boolean(e.active) ? 'active' : 'withoutSelect'}>{e.name} </button> } {e.active ? <React.Fragment> <div className={'popuperTitle'}></div> <div className={position === 'bottom' ? 'popuperBodyBottom' : 'popuperBodyTop'}> <div className={'subMenuList'}> {e.subElements.map((s, k) => { return ( <button key={k} onClick={()=>this.scrollTo(s.link)}> {s.name} </button> ) })} </div> </div> <MdArrowDropUp className={'arrowDrop-active'} size={22}/> </React.Fragment> : e.isElementSelect ? <MdArrowDropDown size={22} className={'arrowDrop'}/> : null } </div> ) })} </div> ) } else return null } } export default MenuList<file_sep>/src/firebase.js import firebase from 'firebase' var config = { apiKey: "<KEY>", authDomain: "cars-d572a.firebaseapp.com", databaseURL: "https://cars-d572a.firebaseio.com", projectId: "cars-d572a", storageBucket: "cars-d572a.appspot.com", messagingSenderId: "405494411865" } firebase.initializeApp(config) export default firebase<file_sep>/src/components/grid/grRow.js import React from 'react' import Radium from 'radium' const Row = (props) => { let style = { grRow: { display: 'flex', flexDirection: 'row', } } if (props.styleProperties !== null) { style.grRow = Object.assign({}, style.grRow, props.styleProperties) } return ( <div onClick={props.onClick} className={props.className} id={props.id} style={style.grRow}> {props.children} </div> ) } export default Radium(Row)<file_sep>/src/store/actions/application.js import { FETCH_MENU_SUCCESS, FETCH_MENU_ERROR, FETCH_SERVICE_SUCCESS, FETCH_APP_SUCCESS, FETCH_SLIDER_SUCCESS, FETCH_SECOND_SLIDER_SUCCESS } from './actionType' import firebase from '../../firebase' export function fetchSlider(props) { return dispatch => { try { let carousel = {} const db = firebase.firestore(); const settings = {timestampsInSnapshots: true}; db.settings(settings); db.collection('slider').get() .then((querySnapshot)=>{ querySnapshot.forEach((doc) => { carousel = doc.data() }) dispatch(fetchSliderSuccess(carousel)) }) .catch((e)=>{ console.log("error(fetchSlider): ",e) carousel = { current:0, title: [ "АРЕНДА АВТОМОБИЛЕЙ", "АРЕНДА СПЕЦТЕХНИКИ", "АРЕНДА СНЕГОПЛАВЕЛЬНЫХ ПУНКТОВ" ], img: [ "https://firebasestorage.googleapis.com/v0/b/cars-d572a.appspot.com/o/%D0%9A%D0%B0%D1%80%D1%83%D1%81%D0%B5%D0%BB%D1%8C%2F%D0%A0%D0%B5%D1%81%D1%83%D1%80%D1%81%203.png?alt=media&token=<PASSWORD>", "https://firebasestorage.googleapis.com/v0/b/cars-d572a.appspot.com/o/%D0%9A%D0%B0%D1%80%D1%83%D1%81%D0%B5%D0%BB%D1%8C%2Fcar_02.jpg?alt=media&token=<PASSWORD>", "https://firebasestorage.googleapis.com/v0/b/cars-d572a.appspot.com/o/%D0%9A%D0%B0%D1%80%D1%83%D1%81%D0%B5%D0%BB%D1%8C%2F%D0%A0%D0%B5%D1%81%D1%83%D1%80%D1%81%203.png?alt=media&token=<PASSWORD>" ] } dispatch(fetchSliderSuccess(carousel)) }) } catch(e) { console.log("dispatch error - fetchSlider:",e) } } } export function fetchSliderSuccess(carousel) { return { type: FETCH_SLIDER_SUCCESS, carousel } } export function fetchSecondSlider(props) { return dispatch => { try { let service = {} const db = firebase.firestore(); const settings = {timestampsInSnapshots: true}; db.settings(settings); db.collection('second_slider').get() .then((querySnapshot)=>{ querySnapshot.forEach((doc) => { service = doc.data() }) dispatch(fetchSecondSliderSuccess(service)) }) .catch((e)=>{ console.log("error(fetchSlider): ",e) }) } catch(e) { console.log("dispatch error - fetchSecondSlider:",e) } } } export function fetchSecondSliderSuccess(service) { return { type: FETCH_SECOND_SLIDER_SUCCESS, service } } export function fetchApp(props) { return dispatch => { try { let app = {} const db = firebase.firestore(); const settings = {timestampsInSnapshots: true}; db.settings(settings); db.collection('app').get() .then((querySnapshot)=>{ querySnapshot.forEach((doc) => { app = { about: doc.data().about, contacts: { titleBtn: doc.data().contacts.title_button, ...doc.data().contacts, }, partners: doc.data().partners } }) dispatch(fetchAppSuccess(app)) }) .catch((e)=>{ console.log("error(fetchApp)",e) app = { about: { title:'О компании', desc:`С 2013 года компания ООО "Сити ЖКХ" работает в сфере благоустройства<br /> в ЦАО г.Москвы. Основными видами деятельности компании являются`, services:[ {icon:'',title:'Уборка снега',desc:`с улиц ЦАО г. Москвы<br /> собственным автопарком<br /> спецтехники`}, {icon:'',title:'Утилизация снега',desc:'на собственных мобильных снегоплавильных пунктах'}, {icon:'',title:'Выполнение работ по озеленению и благоустройству городских территорий',desc:'ООО «Сити ЖКХ» является одним из подрядчиков Префектуры ЦАО города Москвы.'}, {icon:'',title:'Изготовление металлоконструкций ',desc:'Наличие собственного производства позволяет выполнять заказы любой сложности, как в рамках государственного заказа, так и для коммерческих организаций.'}, ] }, partners: { title:'Партнеры', tile:[ {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, {icon:'',title:'Название',desc:'Город'}, ], }, contacts: { title:'"СитиПлюс"', desc:'Общество с ограниченной ответственностью', phone:'+7 (905) 123-45-67', email:'<EMAIL>', otherInfo:'', titleBtn:'Загрузить реквизиты', address:{ desc:'', lat:'', lon:'' }, }, } dispatch(fetchAppSuccess(app)) }) } catch(e) { } } } export function fetchAppSuccess(app) { return { type: FETCH_APP_SUCCESS, app } } export function fetchMenu(props) { return dispatch => { try { let elements = [] const db = firebase.firestore(); const settings = {timestampsInSnapshots: true}; db.settings(settings); db.collection('menu').get() .then((querySnapshot)=>{ querySnapshot.forEach((doc) => { doc.data().elements.map(menu => { return ( Boolean(menu.isElementSelect) ? elements.push({ name: menu.name, link: menu.link, isElementSelect: menu.isElementSelect, active: false, handleClick: props.handleSelectedMenuItem, subElements:menu.subElements, }) : elements.push({ name: menu.name, link: menu.link, }) ) }) }) dispatch(fetchMenuSuccess(elements)) }) .catch((e)=>{ console.log("error(fetchMenu): ",e) elements = [ { name: "Аренда", link: "", isElementSelect:true, active:false, handleClick:props.handleSelectedMenuItem, subElements: [ { name: "Прием и утилизация снега", link: "subSlider", handleClick:null, }, { name: "Аренда спецтехники", link: "block1", handleClick:null, }, { name: "Аренда премиальных автомобилей", link: "block2", handleClick:null, }, ], }, {name: "О компании", link: "about"}, {name: "Партнеры", link: "partners"}, {name: "Контакты", link: "footer"}, ] dispatch(fetchMenuError(elements)) }) } catch(e) { } } } export function fetchMenuSuccess(elements) { return { type: FETCH_MENU_SUCCESS, elements } } export function fetchMenuError(elements) { return { type: FETCH_MENU_ERROR, elements } } export function activatedMenuList(props) { return dispatch => { try { const els = props.props.elements const elements = [ { name: els[0].name, link: els[0].link, isElementSelect:els[0].isElementSelect, active:!els[0].active, handleClick:props.handleSelectedMenuItem, subElements: els[0].subElements, }, {...els[1]}, {...els[2]}, {...els[3]}, ] dispatch(fetchMenuSuccess(elements)) } catch(e) { } } } export function fetchService() { return dispatch => { try { let services = [] const db = firebase.firestore(); const settings = {timestampsInSnapshots: true}; db.settings(settings); db.collection('services').get() .then((querySnapshot)=>{ querySnapshot.forEach((doc,i) => { let service = { title: doc.data().title, cardHor: [], cardVer: [] } doc.data().card.map((c,key) => { if (key <= 7) { service.cardHor.push({ name: doc.data().card[key].name, img: doc.data().card[key].img, desc: doc.data().card[key].desc, cost: doc.data().card[key].cost }) } else if (key <= 10) { service.cardVer.push({ name: doc.data().card[key].name, img: doc.data().card[key].img, desc: doc.data().card[key].desc, cost: doc.data().card[key].cost }) } return null }) services.push(service) }) dispatch(fetchServiceSuccess(services)) }) .catch((e)=>{ // handle error }) } catch(e) { } } } export function fetchServiceSuccess(services) { return { type: FETCH_SERVICE_SUCCESS, services } }<file_sep>/src/store/reducers/application.js import { FETCH_MENU_SUCCESS, FETCH_SERVICE_SUCCESS, FETCH_APP_SUCCESS, FETCH_SLIDER_SUCCESS, FETCH_MENU_ERROR, FETCH_SECOND_SLIDER_SUCCESS } from '../actions/actionType' let initialState = { elements: [], services: [], secondSlider:{ title:'', desc:"", cost:"", images:[], }, about: { title:'', desc:'', services:[] }, partners: { title:'', tile:[], }, contacts: { title:'', phone:'', email:'', otherInfo:'', address:{ desc:'', lat:'', lon:'' }, }, carousel: { current:0, title: [], img: [] } } export default function appReducer(state = initialState, action) { switch(action.type) { case FETCH_MENU_SUCCESS: return { ...state, elements: action.elements } case FETCH_MENU_ERROR: return { ...state, elements: action.elements } case FETCH_SERVICE_SUCCESS: return { ...state, services: action.services } case FETCH_APP_SUCCESS: return { ...state, ...action.app } case FETCH_SLIDER_SUCCESS: return { ...state, carousel: action.carousel } case FETCH_SECOND_SLIDER_SUCCESS: return { ...state, secondSlider: action.service } default: return state } }<file_sep>/src/components/about/about.js import React from 'react' import Col from "../grid/grCol"; import Row from "../grid/grRow"; import icon1 from "../../static/icon1.svg"; import icon2 from "../../static/icon2.svg"; import icon3 from "../../static/icon3.svg"; import icon4 from "../../static/icon4.svg"; import mov from "../../static/cars.mov"; const About = (props) => { let ico1 = icon1, ico2 = icon2, ico3 = icon3, ico4 = icon4; return( <React.Fragment> <Row styleProperties={{ width: '100%', }}> <Col hd={2} dt={1} tb={0} mb={0} styleProperties={{backgroundColor: '#F3F1F3'}}></Col> <Col hd={8} dt={10} tb={12} mb={12}> <div id="about" className={'blockAbout-wrapper'}> <div className={'leftBlockAbout-wrapper'}> <div className={'blockAbout-cntr'}> <div className={'blockAbout-title'}>{props.title}</div> <div className={'blockAbout-desc'} dangerouslySetInnerHTML={{__html:props.desc}} /> {props.services.map((service,k)=>{ return ( <div key={k} className={'blockAbout-tile'}> <div className={'tileIcon'} > <img src={eval('ico'+(k+1))} alt=""/> </div> <div className={'tileTitle'}>{service.title}</div> <div className={'tileDesc'} dangerouslySetInnerHTML={{__html:service.desc}} /> </div> ) })} </div> </div> <div className={'rightBlockAbout-wrapper'}> <div className={'blockAbout-cntr'}> <video className={'blockAbout-video'} controls autoPlay={true} muted={true} > <source src={mov}/> </video> </div> </div> </div> </Col> <Col hd={2} dt={1} tb={0} mb={0} styleProperties={{backgroundColor: '#FF1F27'}}></Col> </Row> </React.Fragment> ) } export default About<file_sep>/src/store/actions/actionType.js export const FETCH_MENU_SUCCESS = 'FETCH_MENU_SUCCESS' export const FETCH_MENU_ERROR = 'FETCH_MENU_ERROR' export const FETCH_SERVICE_SUCCESS = 'FETCH_SERVICE_SUCCESS' export const FETCH_SERVICE_ERROR = 'FETCH_SERVICE_ERROR' export const FETCH_APP_SUCCESS = 'FETCH_APP_SUCCESS' export const FETCH_APP_ERROR = 'FETCH_APP_ERROR' export const FETCH_SLIDER_SUCCESS = 'FETCH_SLIDER_SUCCESS' export const FETCH_SLIDER_ERROR = 'FETCH_SLIDER_ERROR' export const FETCH_SECOND_SLIDER_SUCCESS = 'FETCH_SECOND_SLIDER_SUCCESS'
114f584de0a57c4ca7fbd0e2c81e157b212a0a40
[ "JavaScript" ]
12
JavaScript
ba6a-yaga/webappcars
93be431912676e2d026b8a830a1924d2acec4729
317c6e09b5acaf5976f122530eab7ca79cf2581e
refs/heads/master
<file_sep>$(document).ready(function () { $(".nav ul li a").on("click", function () { $(".nav ul li a").removeClass("active"); $(this).addClass("active"); }); $(".menu").on("click", function () { $(this).toggleClass("active"); $(".overlay").toggleClass("open-menu"); }); $(".nav").on("click", function () { $(".menu").removeClass("active"); $(".overlay").removeClass("open-menu"); }); });
11e0cccc3e01beb972fdafff0c6529fd3cfb4171
[ "JavaScript" ]
1
JavaScript
golnazvalizade/Delisiouc-food-website
c5cf9a1df27b05f505dd439c147eea69afaf5e47
acb18fb9f848addd6a860045021b39b4637fb1bb
refs/heads/master
<repo_name>krrg/gnomon2<file_sep>/backend/src/routes/Clock.ts import * as path from 'path'; import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import IRouter from "./IRouter"; import IGossip from "../gossip/IGossip"; import UserSettingsController from "../usersettings/UserSettingsController" import IUserSettingsFormat from "../usersettings/IUserSettingsFormat"; import {IMessage} from "../gossip/IGossip"; import Guid from "../utils/Guid" import IClockFormat from "../clock/IClockFormat" export default class Clock implements IRouter { private gossipImpl: IGossip; private userSettings: UserSettingsController; constructor(gossipImpl: IGossip) { this.gossipImpl = gossipImpl; this.userSettings = new UserSettingsController(this.gossipImpl); } routes(): express.Router { let router = express.Router(); router.get("/timestamps/:senderId", (req, res) => { this.gossipImpl.filterMessages(req.params.senderId).then((clockMessages:ReadonlyArray<string>) =>{ return res.send(clockMessages.map((msg) => {return JSON.parse(msg)})); }); }) router.post("/timestamps/:workerId", (req, res) => { let email = req.body["email"], timestamp = req.body["timestamp"], workerId=req.params["workerId"]; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } if (!timestamp) { timestamp = Date.now(); } else { timestamp = parseInt(timestamp) if(isNaN(timestamp)) { return res.status(400).send(`The timestamp provided is not a number.`); } } this.userSettings.getSettings(email).then((userSettingsString:string) =>{ let myUserSettings:IUserSettingsFormat, jobsString:string myUserSettings = JSON.parse(userSettingsString); if (!workerId) { if(myUserSettings.jobs.length !== 0) { //default to first job workerId = myUserSettings.jobs[0] } else{ return res.status(400).send(`You have no jobs to clock in from.`); } } else { if(myUserSettings.jobs.indexOf(workerId) === -1) { return res.status(400).send(`You have do not have a job with that id.`); } } //workerId is valid let clockMessage:IMessage; clockMessage = this.createClockMessage(workerId, timestamp); this.gossipImpl.sendMessage(clockMessage).then((indexOfMessage) =>{ return res.send(`The clock event was sent successfully.`); }); }) }); router.post("/timestamps/:messageId/sign", (req, res) => { let email = req.body["email"], messageId = req.params.messageId, senderId = req.body["senderId"]; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } if (!messageId) { return res.status(400).send(`You need to provide a messageId to sign.`); } if (!senderId) { return res.status(400).send(`You need to provide a senderId (the owner of the message, or previous signer).`); } this.userSettings.getSettings(email).then((userSettingsString:string) =>{ let myUserSettings:IUserSettingsFormat, signingId:string; myUserSettings = JSON.parse(userSettingsString); signingId = myUserSettings.signing_id; this.gossipImpl.filterMessages(senderId).then((clockMessages:ReadonlyArray<string>) =>{ let clockMessage:IMessage, clockDataToSign:IClockFormat; clockDataToSign = this.findClockMessageWithId(clockMessages, messageId) if(clockDataToSign === null) { return res.status(400).send(`The clock event specified does not exist.`); } else{ clockMessage = {senderId:signingId, text:JSON.stringify(clockDataToSign)}; this.gossipImpl.sendMessage(clockMessage).then((indexOfMessage) =>{ return res.send(`The clock event was signed successfully.`); }); } }); }); }); router.get("/timestamps/:messageId/isSigned", (req, res) => { let email = req.query.email, messageId = req.params.messageId; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(); } if (!messageId) { return res.status(400).send(`You need to provide a messageId to sign.`); } this.userSettings.getSettings(email).then((userSettingsString:string) =>{ let myUserSettings:IUserSettingsFormat, signingId:string; myUserSettings = JSON.parse(userSettingsString); signingId = myUserSettings.signing_id; this.gossipImpl.filterMessages(signingId).then((signedMessages:ReadonlyArray<string>) =>{ let signedMessage:IMessage, clockDataThatIsSigned:IClockFormat; clockDataThatIsSigned = this.findClockMessageWithId(signedMessages, messageId) if(clockDataThatIsSigned === null) { return res.send({signed: false}); } else{ return res.send({signed: true}); } }); }); }); return router; } private createClockMessage(workerId:string, timestamp:number):IMessage { let clockMessage:IMessage, clockInData:IClockFormat, message_id:string; message_id = this.createRandomId(); clockInData = {worker_id:workerId, timestamp: timestamp, message_id:message_id}; clockMessage = {senderId:workerId, text:JSON.stringify(clockInData)}; return clockMessage; } private findClockMessageWithId(clockMessages:ReadonlyArray<string>, messageId:string):IClockFormat { let myClockInData:IClockFormat = null; clockMessages.forEach(clockMessage => { if(myClockInData != null) { return; } let clockInData:IClockFormat; clockInData = JSON.parse(clockMessage); if(clockInData.message_id == messageId) { myClockInData = clockInData; } }); return myClockInData; } private createRandomId():string { return Guid.newGuid() } } <file_sep>/frontend/src/index.js /* This is the entrypoint for the application */ import React from "react"; import ReactDOM from "react-dom"; import Routes from "./Routes"; document.body.innerHTML += '<div id="ReactAppEntry"></div>'; ReactDOM.render( <Routes />, document.getElementById('ReactAppEntry') )<file_sep>/backend/src/routes/Email.ts import {Router} from "express"; import IRouter from "./IRouter"; import IGossip from "../gossip/IGossip"; const debug = require('debug')('gnomon'); import RedisGossip from "../gossip/RedisGossip"; const nodemailer = require('nodemailer'); import Settings from "../Settings"; export default class Email implements IRouter { private gossipImpl: IGossip; private subscriptions: {}; private cachedMessages: {}; private redis: any; private transporter: any; constructor(gossip: IGossip) { this.gossipImpl = gossip; this.subscriptions = {}; this.cachedMessages = {}; this.redis = new RedisGossip(); let cachedTransporter = null; this.transporter = () => { if (cachedTransporter) { return cachedTransporter; } cachedTransporter = nodemailer.createTransport({ service: 'gmail', auth: { user: Settings["Email"].username, pass: Settings["Email"].password } }); return cachedTransporter; } //Uncomment below to test emailer... but don't send emails to me // this.sendEmail("<EMAIL>", "You got and email", "Here is a message"); } sendEmail(to_email: string, subject: string, message: string): void { let mailOptions = { from: 'Time Service <<EMAIL>>', to: to_email, subject: subject, text: message }; this.transporter().sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); }); } subscribe(email: string, senderId: string, workerId): void { if(!(senderId in this.subscriptions)) { this.subscriptions[senderId] = {} } if(!(workerId in this.subscriptions[senderId])){ this.subscriptions[senderId][workerId] = {}; } this.subscriptions[senderId][workerId][email] = []; this.redis.subscribeToSender(senderId, this.handleMessage); } unsubscribe(email: string, senderId: string, workerId: string): void { // if(senderId in this.subscriptions) { // delete this.subscriptions[senderId][workerId]; // // if(Object.keys(this.subscriptions[senderId]).length == 0) { // delete this.subscriptions[senderId]; // //TODO: Add unsubscribe option // } // } } sendMessage(email, senderId, workerId): void { const msgs = this.subscriptions[senderId][workerId][email]; let buildString = ""; buildString += "Time Report\n"; buildString += "\n"; buildString += `Approval Id: ${senderId}\n`; buildString += `Worker Id: ${workerId}\n`; buildString += "Time Events:\n" for (let msg of msgs) { buildString += msg+"\n"; } this.sendEmail(email, "Time Report", buildString); } // handleMessage(msg): void { handleMessage = (msg) => { const senderId = msg.senderId; const workerIds = this.subscriptions[senderId]; const msg_text = JSON.parse(msg.text) const workerId = msg_text['worker_id'] if(!workerIds || !(workerId in workerIds)) { return; } const emails = workerIds[workerId] for (let email in emails) { if (emails.hasOwnProperty(email)) { const cnt = emails[email].length; if(cnt >= 10) { this.sendMessage(email, senderId, workerId); emails[email] = []; } else { emails[email].push(msg_text['timestamp']) } } } } routes(): Router { const router = Router(); router.post("/subscriptions", (req, res) => { let body = req.body; console.log("Here is the body: ", JSON.stringify(body)); let email = req.query.email; if (!email) { email = req.cookies["sessionEmail"] } if (!email) { email = body["email"]; } if(!email) { return res.status(401).send(`You are not logged in.`); } const subscribe = body["subscribe"] const senderId = body["senderId"]; const workerId = body["workerId"]; this.subscribe(email, senderId, workerId) let return_obj = { "msg": `Emails will be sent to: ${email}` } res.send(return_obj); }) router.get("/subscriptions", (req, res) => { let keys = []; let email = req.query.email; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } for (let senderId in this.subscriptions) { if (this.subscriptions.hasOwnProperty(senderId)) { for (let workerId in this.subscriptions[senderId]) { if (this.subscriptions[senderId].hasOwnProperty(workerId)) { if (email in this.subscriptions[senderId][workerId]) { keys.push({ "workerId": workerId, "senderId": senderId }) } } } } } res.send(keys); }) return router; } } <file_sep>/backend/src/routes/UserSubscription.ts import * as path from 'path'; import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import IRouter from "./IRouter"; import IGossip from "../gossip/IGossip"; import UserSettingsController from "../usersettings/UserSettingsController" import IUserSettingsFormat from "../usersettings/IUserSettingsFormat"; export default class UserSubscriptionRouter implements IRouter { private gossipImpl: IGossip; private userSettings: UserSettingsController; constructor(gossipImpl: IGossip) { this.gossipImpl = gossipImpl; this.userSettings = new UserSettingsController(this.gossipImpl); } routes(): express.Router { let router = express.Router(); router.get("/userSubscriptions", (req, res) => { let email = req.query.email; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } this.userSettings.getSettings(email).then((userSettingsString:string) =>{ let myUserSettings:IUserSettingsFormat, subscriptionsString:string myUserSettings = JSON.parse(userSettingsString); subscriptionsString = JSON.stringify(myUserSettings.subscriptions); return res.send(`${subscriptionsString}`); }) }) router.post("/userSubscriptions", (req, res) => { let email = req.body["email"], subscriptionId = req.body["subscriptionId"]; if (!email) { email = req.cookies["sessionEmail"] } if(!email){ return res.status(401).send(`You are not logged in.`); } if (!subscriptionId) { return res.status(400).send(`You need to provide a subscriptionId.`); } this.userSettings.insertNewSubscriptionId(email,subscriptionId).then((result:string) =>{ return res.send(`${result}`); }); }); return router; } } <file_sep>/backend/test/RedisGossip.test.ts import RedisGossip from "../src/gossip/RedisGossip"; import * as _ from "lodash"; describe("Redis Gossip implementation", () => { it("should push messages onto the list", async () => { const redis = new RedisGossip(); const index = await redis.sendMessage({ senderId: `test-key${Math.random()}`, text: "This is the message" }); console.log("I am completing, further my index was: " + index); }) it("can read back a list of messages", async () => { const redis = new RedisGossip(); await _.times(10, async () => { await redis.sendMessage({ senderId: `Ken!`, text: `This is test message ${Math.random()}` }); }); // TODO: Turn this into a legit test. console.log(await redis.filterMessages('Ken!')) }) it("retrieves the last message", async () => { const redis = new RedisGossip(); await _.times(10, async () => { await redis.sendMessage({ senderId: "Glummy", text: `This is a test ${Math.random()}` }) }); console.log(await redis.filterLastMessage("Glummy")) }) it("publishes a message on the sender's channel", (done) => { const redis = new RedisGossip(); /* This wrapper is just so we can avoid returning a promise from the unit test and confusing mocha. */ (async () => { /* we have to await because it takes a round trip to the server to subscribe */ await redis.subscribeToSender("<EMAIL>", (msg) => { console.log(msg); done(); }); redis.sendMessage({ senderId: "<EMAIL>", text: "Hello World" }) })(); }) })<file_sep>/backend/src/routes/Login.ts import * as express from "express"; import IRouter from "./IRouter"; import Settings from "../Settings"; var request = require('request'); export default class LoginRouter implements IRouter { // "OAUTH2_CALLBACK": "https://[YOUR_PROJECT_ID].appspot.com/auth/google/callback" // https://accounts.google.com/o/oauth2/auth // https://accounts.google.com/o/oauth2/token private oauth2: () => any; private authorization_uri: () => string; constructor() { let cachedOauth2 = null; this.oauth2 = () => { /* This is a function so that we can lazily evaluate the Settings file */ if (cachedOauth2) { return cachedOauth2; } const credentials = { client: { id: Settings["Login"].client_id, secret: Settings["Login"].client_secret, }, auth: { tokenHost: 'https://accounts.google.com', tokenPath: '/o/oauth2/token', authorizePath: '/o/oauth2/auth' } }; cachedOauth2 = require('simple-oauth2').create(credentials) return cachedOauth2; } this.authorization_uri = () => this.oauth2().authorizationCode.authorizeURL({ redirect_uri: Settings["Login"].auth_return_url, scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile' }); } routes(): express.Router { const router = express.Router() router.get('/login', (req, res) => { if (req.query.email === undefined) { return res.redirect(this.authorization_uri()); } else { const email = req.query.email; if(!email) { return res.status(400).send(`The email parameter is missing`); } /* Dump a completely insecure garbage cookie over */ res.cookie("sessionEmail", email); return res.redirect("/"); } }); router.get('/auth', (req, res) => { res.redirect(this.authorization_uri()); }); router.get('/login/return', (req, res) => { // Handle Google coming back to us with stuff. let code = req.query.code; const tokenConfig = { code: code, redirect_uri: Settings["Login"].auth_return_url }; let self = this; this.oauth2().authorizationCode.getToken(tokenConfig, (error, result) => { if (error) { return console.log('Access Token Error', error.message); } const token = self.oauth2().accessToken.create(result); const options = { url: 'https://www.googleapis.com/oauth2/v1/userinfo', headers: { 'Content-Type': 'application/json', 'Authorization': "Bearer "+token.token.access_token } }; request(options, function (error, response, body) { if (error) { return console.log('userinfo error', error.message); } let email = JSON.parse(body)['email'] res.redirect(`/api/login?email=${email}`); }); }); }) router.get('/logout', (req, res) => { res.clearCookie("sessionEmail"); return res.redirect("/"); }) return router; } } <file_sep>/README.md # gnomon2 A distributed time tracker using Redis Clusters # Disclaimer This code was quite experimental. Don't use it for a real time clock system :) <file_sep>/backend/src/Settings.example.ts const Settings = { /* This will get passed directly to the Redis constructor */ Redis: { port: 6379, host: '127.0.0.1' }, Login: { client_id: 'XXXXXXXXXXXXXXXXXXXXXXXXX', client_secret: '<KEY>', auth_return_url: 'XXXXXXXXXXXXXXXXXXXXXXXXX' }, Email: { username: 'XXXXXXXXXXXXXXXXXXXXXXXXX', password: '<KEY>' } } export default Settings;<file_sep>/backend/src/routes/Job.ts import * as path from 'path'; import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import IRouter from "./IRouter"; import IGossip from "../gossip/IGossip"; import UserSettingsController from "../usersettings/UserSettingsController" import IUserSettingsFormat from "../usersettings/IUserSettingsFormat"; export default class JobRouter implements IRouter { private gossipImpl: IGossip; private userSettings: UserSettingsController; constructor(gossipImpl: IGossip) { this.gossipImpl = gossipImpl; this.userSettings = new UserSettingsController(this.gossipImpl); } routes(): express.Router { let router = express.Router(); router.get("/jobs", (req, res) => { let email = req.query.email; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } this.userSettings.getSettings(email).then((userSettingsString:string) =>{ let myUserSettings:IUserSettingsFormat, jobsString:string myUserSettings = JSON.parse(userSettingsString); jobsString = JSON.stringify(myUserSettings.jobs); return res.send(`${jobsString}`); }) }) router.post("/jobs", (req, res) => { let email = req.body["email"]; if (!email) { email = req.cookies["sessionEmail"] } if(!email) { return res.status(401).send(`You are not logged in.`); } this.userSettings.insertNewJobId(email).then((result:string) =>{ return res.send(`${result}`); }); }); return router; } } <file_sep>/backend/src/App.ts import * as path from 'path'; import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import IGossip from "./gossip/IGossip"; import RedisGossip from "./gossip/RedisGossip"; import Clock from "./routes/Clock"; import Login from "./routes/Login"; import Email from "./routes/Email"; import UserSettings from "./routes/UserSettings"; import Job from "./routes/Job"; import UserSubscription from "./routes/UserSubscription"; class App { public app: express.Application; private gossipImpl: IGossip; constructor() { this.app = express(); this.gossipImpl = new RedisGossip(); this.middleware(); this.initRoutes(); } private middleware(): void { this.app.use(cookieParser()); this.app.use(bodyParser.json()); this.app.use(bodyParser.urlencoded({ extended: false })); } private initRoutes(): void { let router = express.Router(); router.get('/', (req, res) => { return res.send("Here is the API!"); }); router.use(new Clock(this.gossipImpl).routes()); router.use(new Login().routes()); router.use(new Email(this.gossipImpl).routes()); router.use(new UserSettings(this.gossipImpl).routes()); router.use(new Job(this.gossipImpl).routes()); router.use(new UserSubscription(this.gossipImpl).routes()); this.app.use('/api', router); } } export default new App().app;<file_sep>/frontend/src/NavigationBar/index.js import React from "react"; import {NavLink} from "react-router-dom"; import "./NavigationBar.scss"; export default class NavigationBar extends React.Component { render() { return ( <div className="NavigationBar"> <ul> <li><NavLink to="/login">Login</NavLink></li> <li><NavLink to="/timesheet">Timesheet</NavLink></li> <li><NavLink to="/approvals">Approvals</NavLink></li> <li><NavLink to="/emails">Email</NavLink></li> </ul> </div> ) } }<file_sep>/backend/src/usersettings/IUserSettingsFormat.ts export interface IUserSettingsFormat { readonly email:string, readonly signing_id: string, readonly jobs: Array<string>, readonly subscriptions: Array<string> } export default IUserSettingsFormat;<file_sep>/backend/src/Settings.ts const Settings = { /* This will get passed directly to the Redis constructor */ Redis: { port: 6379, host: '127.0.0.1' }, Login: { /* Note: These are not actually working anymore */ client_id: '<Google Client ID>', client_secret: '<Google Client Secret>', auth_return_url: 'http://localhost:4000/api/login/return' }, Email: { username: '<<EMAIL>>', password: '<<PASSWORD>>' } } export default Settings; <file_sep>/frontend/src/Timesheet/index.js import React from "react"; import axios from "axios"; import ClockEventsTable from "./ClockEventsTable"; export default class Timesheet extends React.Component { constructor() { super(); this.state = { timestamps: {} } } componentDidMount() { this.getJobIds().forEach(this.reloadTimestampsFor); } getJobIds = () => { if (this.props.userSettings) { return this.props.userSettings.jobs || []; } else { return []; } } reloadTimestampsFor = (workerId) => { axios.get(`/api/timestamps/${workerId}`) .then((resp) => { const currentState = this.state; currentState.timestamps[workerId] = resp.data; this.setState(currentState); }); } renderClockButton = (jobid) => { const handleClick = () => { axios.post(`/api/timestamps/${jobid}`) .then((resp) => { this.reloadTimestampsFor(jobid); }) } return ( <button onClick={handleClick}>Clock in/out</button> ) } renderWorkerIds = () => { const jobIds = this.getJobIds(); if (jobIds.length > 0) { return this.props.userSettings["jobs"].map((jobid) => { return ( <div key={jobid}> <p> JOB: {jobid} &nbsp; {this.renderClockButton(jobid)} </p> <ClockEventsTable jobid={jobid} timestamps={this.state.timestamps[jobid]} /> <hr /> </div> ); }); } else { return (<p>You have no jobs</p>); } } handleCreateNewJob = () => { console.log("Creating new job"); axios.post("/api/jobs").then((resp) => { console.log("here it is"); this.props.userSettings.requestReload(); }); } render() { return ( <div className="gn-container"> <h1>Your Timesheet</h1> <div> <h2>Jobs</h2> {this.renderWorkerIds()} <button onClick={this.handleCreateNewJob}>Create new Job</button> </div> </div> ) } }<file_sep>/backend/README.md # gnomon2 A distributed time tracker using Redis Clusters # Haphazard Warning This code is not intended at all for production use. It is merely a demonstration that you could use Redis Clusters to do a distributed time clock. **This is not even close to productionable code**. <file_sep>/backend/src/gossip/RedisGossip.ts import {IGossip, IMessage} from "./IGossip"; import Settings from "../Settings"; import * as Redis from "ioredis" export default class RedisGossip implements IGossip { redis: Redis.Redis; subRedis: Redis.Redis; constructor() { this.redis = new Redis(Settings.Redis); this.subRedis = new Redis(Settings.Redis); // Must use a second connection for subscriptions } async sendMessage(message: IMessage): Promise<number> { this.redis.publish(message.senderId, message.text); return await this.redis.rpush(message.senderId, message.text); } async filterMessages(senderId: string): Promise<ReadonlyArray<string>> { return await this.redis.lrange(senderId, 0, -1); } async filterLastMessage(senderId: string): Promise<string> { const arrayResult = await this.redis.lrange(senderId, -1, -1); if (arrayResult.length === 0) { return null; } else { return arrayResult[0]; } } async subscribeToSender(senderId: string, callback: (msg: IMessage) => any): Promise<void> { await this.subRedis.subscribe(senderId); this.subRedis.on('message', function(channel, message) { callback({ senderId: channel, text: message }); }) } }<file_sep>/backend/src/routes/IRouter.ts import * as express from "express"; interface IRouter { routes(): express.Router; } export default IRouter;<file_sep>/backend/src/usersettings/UserSettingsController.ts import IGossip from "../gossip/IGossip"; import {IMessage} from "../gossip/IGossip"; import IUserSettingsFormat from "./IUserSettingsFormat"; import Guid from "../utils/Guid" import * as Redis from "ioredis" export default class UserSettingsController { private gossipImpl: IGossip; constructor(gossipImpl: IGossip) { this.gossipImpl = gossipImpl; } async getSettings(email: string): Promise<string> { let currentSettings:string; currentSettings = await this.gossipImpl.filterLastMessage(email); if(currentSettings === null) { let newUserSettings:IUserSettingsFormat, indexOfMessage:number; newUserSettings = this.createInitialSettings(email); indexOfMessage = await this.UpdateSettingsObject(email,newUserSettings); return this.getSettings(email) } return currentSettings; } async insertNewJobId(email:string):Promise<string> { let jobId:string, indexOfMessage:number, userSettingsString:string, userSettings:IUserSettingsFormat; jobId = this.createRandomId(); userSettingsString = await this.getSettings(email); userSettings = JSON.parse(userSettingsString); if(userSettings.jobs.indexOf(jobId) === -1){ userSettings.jobs.push(jobId); indexOfMessage = await this.UpdateSettingsObject(email,userSettings); return jobId; } else { await this.insertNewJobId(email); } } async insertNewSubscriptionId(email:string, subscriptionId:string):Promise<string> { let indexOfMessage:number, userSettingsString:string, userSettings:IUserSettingsFormat; userSettingsString = await this.getSettings(email); userSettings = JSON.parse(userSettingsString); if(userSettings.subscriptions.indexOf(subscriptionId) === -1){ userSettings.subscriptions.push(subscriptionId); indexOfMessage = await this.UpdateSettingsObject(email,userSettings); return subscriptionId; } else { return `This subscriptionId is already subscribed: ${subscriptionId}`; } } private async UpdateSettingsObject(email:string, userSettings: IUserSettingsFormat): Promise<number> { let settingsMessage:IMessage; settingsMessage = {senderId:email, text:JSON.stringify(userSettings)}; return await this.gossipImpl.sendMessage(settingsMessage); } private createInitialSettings(userEmail:string): IUserSettingsFormat{ let defaultSettings:IUserSettingsFormat, newSenderId:string; newSenderId = this.createRandomId(); defaultSettings = {email:userEmail, signing_id:newSenderId, jobs: new Array<string>(), subscriptions:new Array<string>()}; return defaultSettings; } private createRandomId():string { return Guid.newGuid() } } <file_sep>/backend/src/clock/IClockFormat.ts export interface IClockFormat { readonly worker_id: string, readonly timestamp: number, readonly message_id: string } export default IClockFormat;<file_sep>/frontend/src/Approvals/index.js import React from "react"; import axios from "axios"; import ClockEventsTable from "../Timesheet/ClockEventsTable"; export default class Approvals extends React.Component { constructor() { super(); this.state = { timestamps: {}, approvedMessageIds: {} } } renderClockEventRow() { } componentDidMount() { this.getSubscriptions().forEach(this.reloadTimestampsFor) } reloadTimestampsFor = (workerId) => { const timestampsPromise = axios.get(`/api/timestamps/${workerId}`) timestampsPromise.then((resp) => { const currentState = this.state; currentState.timestamps[workerId] = resp.data; this.setState(currentState); resp.data.forEach((stamp) => { this.reloadApprovalFor(stamp.message_id); }) }) timestampsPromise.catch((resp) => { const currentState = this.state; currentState.timestamps[workerId] = []; this.setState(currentState); }) } reloadApprovalFor = (messageId) => { axios.get(`/api/timestamps/${messageId}/isSigned`) .then((resp) => { const currentState = this.state; currentState.approvedMessageIds[messageId] = resp.data.signed; this.setState(currentState); }) } getSubscriptions = () => { return this.props.userSettings.isLoggedIn ? this.props.userSettings.subscriptions : []; } handleNewSubscription = (e) => { e.preventDefault(); if (! this.refs.workerId.value) { return; } axios.post('/api/userSubscriptions', { subscriptionId: this.refs.workerId.value }).then((resp) => { this.props.userSettings.requestReload(); }); } isApproved = (messageId) => { return this.state.approvedMessageIds[messageId]; } approveTimestamp = (messageId, workerId) => { return axios.post(`/api/timestamps/${messageId}/sign`, { "senderId": workerId }) .then((stamp) => { this.reloadApprovalFor(messageId); // We can't rely on the error codes coming back }) } customRenderTimestampRow = (workerId, clockIn, clockOut) => { console.log(this.state); const clockInDate = clockIn ? new Date(clockIn.timestamp).toTimeString() : null; const clockOutDate = clockOut ? new Date(clockOut.timestamp).toTimeString() : null; const approved = clockIn && clockOut && this.isApproved(clockIn.message_id) && this.isApproved(clockOut.message_id); const handleRowApproval = () => { this.approveTimestamp(clockIn.message_id, workerId); this.approveTimestamp(clockOut.message_id, workerId); } const renderApprovalData = () => { if (approved) { return (<i>Approved</i>); } else { return (<span><b>Needs Approval</b>&nbsp;<button onClick={handleRowApproval}>Approve</button></span>) } } /* Or default to a minimal output */ return ( <tr key={`${clockIn.message_id}`}> <td>{clockInDate}</td> <td>{clockOutDate}</td> <td>{clockOut ? renderApprovalData(): <i>Pending worker clock out</i>}</td> </tr> ); } renderSubscriptions = (subscriptionIds) => { return subscriptionIds.map((sid) => { return ( <div key={sid}> <h3>Subscription ID: {sid}</h3> {/*{JSON.stringify(this.state.timestamps[sid])}*/} <ClockEventsTable jobid={sid} timestamps={this.state.timestamps[sid]} renderClockEventRow={this.customRenderTimestampRow} /> </div> ) }) } render() { console.log(this.props.userSettings); return ( <div className="gn-container"> <h1>Timesheet Approvals</h1> <p>You are currently subscribed to {this.getSubscriptions().length} workers.</p> <p>Your signing ID is: <b>{this.props.userSettings.signing_id}</b></p> <form> <input ref='workerId' placeholder='<NAME>' /> <button onClick={this.handleNewSubscription}>Subscribe to Worker</button> </form> <hr /> {this.renderSubscriptions(this.getSubscriptions())} </div> ) } }<file_sep>/backend/package.json { "name": "gnomon2", "version": "1.0.0", "description": "", "main": "dist/index.js", "scripts": { "start": "gulp scripts && node dist/index.js", "test": "mocha --reporter spec --compilers ts:ts-node/register 'test/**/*.test.ts'" }, "author": "<NAME>, <NAME>, <NAME>", "license": "MIT", "devDependencies": { "gulp": "^3.9.1", "gulp-typescript": "^3.1.6", "mocha": "^3.2.0", "typescript": "^2.2.2" }, "dependencies": { "@types/chalk": "^0.4.31", "@types/cookie-parser": "^1.3.30", "@types/debug": "0.0.29", "@types/express": "^4.0.35", "@types/ioredis": "0.0.22", "@types/lodash": "^4.14.61", "@types/mocha": "^2.2.40", "body-parser": "^1.17.1", "chalk": "^1.1.3", "cookie-parser": "^1.4.3", "debug": "^2.6.3", "express": "^4.15.2", "ioredis": "^2.5.0", "lodash": "^4.17.4", "mocha": "^3.2.0", "nodemailer": "^4.0.0", "request": "^2.81.0", "simple-oauth2": "^1.1.0", "ts-node": "^3.0.2" } } <file_sep>/backend/run_redis.sh #!/usr/bin/bash sudo docker run -t -i -p 127.0.0.1:6379:6379 redis<file_sep>/backend/src/gossip/IGossip.ts export interface IMessage { readonly senderId: string, readonly text: string } export interface IGossip { sendMessage(message: IMessage): any; filterMessages(senderId: string): Promise<Array<string>>; filterLastMessage(senderId: string): Promise<string>; subscribeToSender(senderId: string, callback: (msg: IMessage) => any): any; } export default IGossip;<file_sep>/frontend/src/Emails/index.js import React from "react"; import axios from "axios"; export default class Emails extends React.Component { constructor() { super(); this.state = { subscriptions: [] } } componentDidMount() { axios.get(`/api/subscriptions`) .then((resp) => { this.setState({ subscriptions: resp.data }) }) } handleNewSubscription = () => { axios.post(`/api/subscriptions`, { 'senderId': this.refs.senderId.value, 'workerId': this.refs.workerId.value }) } renderSubscriptionForm = () => { return ( <div> <form> <input type='text' ref='senderId' placeholder='senderId' /> <input type='text' ref='workerId' placeholder='workerId' /> <button onClick={this.handleNewSubscription}>Send me email updates!</button> </form> </div> ) } renderSubscriptionList = () => { return this.state.subscriptions.map((subscription) => { return ( <div> Worker ID: {subscription.workerId} &nbsp; Sender ID: {subscription.senderId} </div> ) }) } render() { return ( <div className="gn-container"> <h1>Email Notifications</h1> <p>This node is configured to send emails for: </p> {this.renderSubscriptionForm()} <hr /> {this.renderSubscriptionList()} </div> ) } }
22a1076b8b6989aae7f9cf81f08722a38f24cb33
[ "JSON", "JavaScript", "Markdown", "TypeScript", "Shell" ]
24
TypeScript
krrg/gnomon2
43f5326608bab4bf86e0040f628b23c4a944c47f
be948e109cf8f5de14a3d7b52df1a0c9a79a0f22
refs/heads/main
<repo_name>sensoham21/Van_Order<file_sep>/Question3.sql SELECT requestor_client_id AS Client, COUNT(requestor_client_id) AS Total_Orders_Completed, SUM(total_price) AS Total_Money_Spent FROM vanorder WHERE order_status = 2 GROUP BY requestor_client_id ORDER BY Total_Money_Spent DESC, Total_Orders_Completed DESC;<file_sep>/Question1.sql SELECT DATE_FORMAT(order_datetime, '%H') AS Hour_of_day, COUNT(idvanOrder) AS Count_of_order FROM vanorder GROUP BY Hour_of_day ORDER BY Hour_of_day;<file_sep>/Question2.sql SELECT price_group.Order_Complete_Group, (SUM(price_group.price)/(SELECT SUM(total_price) FROM vanorder WHERE order_status = 2))*100 AS Percentage_Price FROM (SELECT SUM(total_price) AS price, requestor_client_id, CASE WHEN COUNT(requestor_client_id) = 1 THEN 'One' ELSE 'More Than One' END AS Order_Complete_Group FROM vanorder WHERE order_status = 2 GROUP BY requestor_client_id) AS price_group GROUP BY price_group.Order_Complete_Group;<file_sep>/Question5.sql SELECT Driver_ID FROM (SELECT Total.Driver_ID AS Driver_ID, Orders.Total_Orders_Completed AS Total_Orders_Completed, Total.Total_Income AS Total_Income FROM (SELECT vanI.servicer_auth AS Driver_ID, SUM(vanO.total_price) AS Total_Income FROM vaninterest AS vanI LEFT JOIN vanorder AS vanO ON vanI.idvanOrder = vanO.idvanOrder AND vanI.order_subset_assigned = vanO.order_subset AND vanI.servicer_auth = vanO.servicer_auth GROUP BY Driver_ID ORDER BY Driver_ID) AS Total LEFT JOIN (SELECT COUNT(*) AS Total_Orders_Completed, servicer_auth AS Driver_ID FROM vanorder WHERE order_status = 2 GROUP BY Driver_ID ORDER BY Driver_ID) AS Orders ON Total.Driver_ID = Orders.Driver_ID ORDER BY Total_Income DESC, Total_Orders_Completed) AS last_table WHERE Total_Orders_Completed IS NULL ORDER BY Driver_ID;
ecf86683762eb2551b99385cc5cfbdd708ff784f
[ "SQL" ]
4
SQL
sensoham21/Van_Order
a31ea7941b6c2bb4fa995292beb23b766aa9d5c8
75833d519da604200699465307719556aecc24df
refs/heads/master
<repo_name>led-spb/motion<file_sep>/backup.sh #!/bin/sh . $(dirname $0)/config # Creating file for last day TARGET_FILE=$MEDIA_PATH/$(date --date="-$MTIME day" "+%Y-%m-%d.mp4") TMP_VIDEO=$MEDIA_PATH/files.lst echo Checking data for last day find -H $MEDIA_PATH -maxdepth 1 -daystart -type f -name "$MEDIA_MASK" -mtime $MTIME -printf "file '%p'\n" | sort >$TMP_VIDEO if [ -s "$TMP_VIDEO" ] then echo Encoding $TARGET_FILE $FFMPEG -f concat -safe 0 -i $TMP_VIDEO -c:v $CODEC -b:v $BACKUP_BITRATE -an -y -f mp4 $TARGET_FILE && ( #echo Sending $TARGET_FILE #mosquitto_pub $MQTT -t $TOPIC_VIDEOM -f "$TARGET_FILE" echo Cleaning source files find -H $MEDIA_PATH -maxdepth 1 -daystart -type f -name "$MEDIA_MASK" -mtime $MTIME -delete ) else echo No data for last day fi echo Backup files find -H $MEDIA_PATH -type f -name "*.mp4" -mtime +1 | xargs -I {} mv {} $BACKUP_PATH/ # Remove jpeg files #find -H $MEDIA_PATH -type f -name "*.jpg" -delete echo Removing old archives # remove old archives #find -H $BACKUP_PATH -type f -name "*.mp4" -mtime +$RETAIN_DAYS -delete find -H $MEDIA_PATH -type f -name "*.mp4" -mtime +$RETAIN_DAYS -delete echo Finished exit <file_sep>/event.sh #!/bin/sh cd $(dirname $0) . ./config echo $(date -Is): $* >>event.log case "$1" in # this event will be occured when motion is detected motion_on) curl -s http://127.0.0.1:8092/camera/snapshot | mosquitto_pub $MQTT -t $TOPIC_PHOTO -s -r mosquitto_pub $MQTT -t $TOPIC_MOTION -m "{\"status\": 1, \"changed\": $(date +%s)}" -r ;; # this event will be occured when motion is ended motion_off) mosquitto_pub $MQTT -t $TOPIC_MOTION -m "{\"status\": 0, \"changed\": $(date +%s)}" -r ;; # external action for make snapshot snapshot) # send photo to MQTT with retain option curl -s http://127.0.0.1:8092/camera/snapshot | mosquitto_pub $MQTT -t $TOPIC_PHOTO -s -r ;; # deprecated events from motion process motion) curl -s http://127.0.0.1:8092/camera/motion/start >/dev/null ;; motion_end) curl -s http://127.0.0.1:8092/camera/motion/stop >/dev/null #mosquitto_pub $MQTT -t $TOPIC_MOTION -m 0 -r ;; esac <file_sep>/hicamera.py #!/usr/bin/python import io import sys import os import logging import argparse import subprocess import socket import time import json import picamera import picamera.array from datetime import datetime import numpy as np from tornado import web, httpserver, ioloop, gen, websocket, iostream from threading import Lock import shlex class MotionHandler(object): def motion_event(self, value): pass class FileOutputStream(object): def __init__(self, fp): self.fp = fp self.lock = Lock() def write(self, data): with self.lock: self.fp.write(data) return len(data) @property def closed(self): return self.fp.closed def close(self): with self.lock: self.fp.close() class VideoBuffer(object): def __init__(self, camera, pre_seconds): self.camera = camera self.ioloop = ioloop.IOLoop.current() self.circular = picamera.PiCameraCircularIO(self.camera, size=1*1024*1024) self.out_fd = [] self.write_to_circular = False pass def write(self, b): try: if True or self.write_to_circular: self.circular.write(b) for stream in list(self.out_fd): if stream.closed: self.out_fd.remove(stream) else: stream.write(b) except: logging.exception('VideoBuffer exception') pass def copy_circular(self, output, seconds): buffer = self.circular with buffer.lock: save_pos = buffer.tell() try: # find position of SPS frame at least last N seconds pos = None last = None curr = None seconds = int(seconds * 1000000) for frame in reversed(buffer.frames): if frame.timestamp is not None: curr = frame.timestamp if last is None: last = frame.timestamp if frame.frame_type == 2 and last is not None: pos = frame.position if last - curr >= seconds: break logging.debug('found %d secs in curcular buffer (size: %d)', (last-curr)/1000000, save_pos-pos) # write to output stream from finded position if pos is not None: buffer.seek(pos) while True: buf = buffer.read1() if not buf: break #yield output.write(buf) output.write(buf) finally: buffer.seek(save_pos) pass pass def write_to_stream(self, stream, b): if not stream.closed(): stream.write(b) pass def flush(self): pass def attach_stream(self, stream): self.out_fd.append(stream) def remove_stream(self, stream): if stream in self.out_fd: self.out_fd.remove(stream) class MotionDetector(picamera.array.PiMotionAnalysis): def __init__(self, camera, handler): """ :type camera: picamera.PiCamera :type handler: MotionHandler """ super(MotionDetector, self).__init__(camera) self.handler = handler self.motion_treshold_value = 0 self.motion_treshold_count = 5 self.motion_treshold_sad = 300 self.motion_frames = 3 self.motion_cnt = 0 def analyse(self, a): try: b = ( np.square(a['x'].astype(np.uint16)) + np.square(a['y'].astype(np.uint16)) ).astype(np.uint16) b = np.logical_and( (b > self.motion_treshold_value) , (a['sad'] < self.motion_treshold_sad) ) n = b.sum() if n > self.handler.motion_factor: self.handler.motion_factor = n if n > self.motion_treshold_count: self.motion_cnt = self.motion_cnt + 1 else: self.motion_cnt = 0 if self.motion_cnt >= self.motion_frames: self.handler.motion_event(n) except: logging.exception('motion detection error') pass class Recorder(MotionHandler): def __init__(self, camera, params): self.params = params self.camera = camera self.record_flag = False self.motion_detector = MotionDetector(camera, self) self.motion_factor = 0 self.video_buffer = VideoBuffer(self.camera, self.params.buffer) self.last_motion = time.time() self.ioloop = ioloop.IOLoop.current() self.motion_timeout = None self.snapshot = io.BytesIO() self.snapshot_time = time.time()*1000 def start_process(self, command_line, debug=False): cmd = command_line.format(**vars(self.params)) logging.debug("spawn process %s", cmd) subprocess.Popen(shlex.split(cmd)) pass def motion_event(self, value): now = time.time() if now - self.last_motion > self.params.event_gap: logging.info('motion event started (factor %d)', value) try: self.start_record() self.start_process(self.params.on_motion_begin) except: logging.exception('start motion error') self.ioloop.add_callback(self.schedule_motion_end) self.last_motion = time.time() pass def schedule_motion_end(self): if self.motion_timeout is not None: self.ioloop.remove_timeout(self.motion_timeout) self.motion_timeout = self.ioloop.call_later(self.params.event_gap, self.end_motion) pass def end_motion(self): logging.info('motion event finished') try: self.stop_record() self.start_process(self.params.on_motion_end) except: logging.exception('end motion error') pass def take_snapshot(self, expire=0): now = time.time()*1000 if now-self.snapshot_time >= expire: self.snapshot_time = now self.snapshot.seek(0) self.snapshot.truncate() self.camera.capture(self.snapshot, format='jpeg', use_video_port=True) return self.snapshot def start_record(self): if self.record_flag: return self.record_flag = True self.params.timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') logging.info('start recording') self.record_stream = FileOutputStream(open(self.params.motion_file.format(**vars(self.params)), 'wb')) self.video_buffer.attach_stream(self.record_stream) buffer_stream = open(self.params.pre_motion_file.format(**vars(self.params)), 'wb') self.video_buffer.copy_circular(buffer_stream, self.params.buffer) buffer_stream.close() pass def stop_record(self): if not self.record_flag: return logging.info('stop recording') self.video_buffer.remove_stream(self.record_stream) self.record_stream.close() post_process_cmd = self.params.post_process.format(**vars(self.params)) if post_process_cmd != '': logging.debug('start post process command: %s', post_process_cmd) subprocess.Popen(post_process_cmd, shell=True, stdout=io.open(os.devnull, 'wb'), stderr=subprocess.STDOUT) self.record_flag = False pass def time_marker(self): now = datetime.now() #motion_mark = 'M' if now - self.last_motion < self.params.event_gap else ' ' now_str = now.strftime('%Y-%m-%d %H:%M:%S') self.camera.annotate_text = "%s.%01d" % (now_str, int(now.microsecond/100000)) #+ "\n[%d %s]" % (self.motion_factor, motion_mark) self.motion_factor = 0 def start(self): self.marker_callback = ioloop.PeriodicCallback(self.time_marker, callback_time=100) self.camera.start_recording( self.video_buffer, format='h264', #format='mjpeg', inline_headers=True, motion_output=self.motion_detector ) self.marker_callback.start() pass class SnapshotHandler(web.RequestHandler): def initialize(self, recorder): self.recorder = recorder @gen.coroutine def get(self): self.set_header('Content-Type', 'image/jpeg') buffer = self.recorder.take_snapshot() yield self.write(buffer.getvalue()) pass class StreamHandler(web.RequestHandler): def initialize(self, recorder): self.recorder = recorder self.boundary = 'MJPEGFRAME' @web.asynchronous def get(self): self.set_header('Content-Type', 'multipart/x-mixed-replace;boundary=%s' % self.boundary) self.flush() try: self.rate = int(self.get_argument('rate', '1000')) logging.info('start streaming with rate %d', self.rate) self.task = ioloop.PeriodicCallback(self.write_frame, self.rate) self.write_frame() self.task.start() logging.info('streaming finished') except: logging.exception('streaming error') self.finish() pass def on_connection_close(self): self.task.stop() pass def write_frame(self): try: frame = self.recorder.take_snapshot(self.rate/2).getvalue() header = '\r\n'.join( [ '--%s' % self.boundary, 'Content-Type: image/jpeg', 'Content-Length: %d' % len(frame), '', ''] ) self.write(header) self.write(frame) self.flush() except: logging.exception('write_frame error') self.finish() pass class WSStreamHandler(websocket.WebSocketHandler): def initialize(self, recorder): self.recorder = recorder self.task = None def check_origin(self, origin): return True def on_close(self): self.stop_stream() pass def on_message(self, message): try: command = json.loads(message) logging.debug('got command %s', message) if command['cmd'] == 'start': rate = command.get('rate', 1000) self.start_stream(rate) if command['cmd'] == 'stop': self.stop_stream() except: logging.exception('on_message error') pass def stop_stream(self): if self.task is not None: logging.info('stop streaming') self.task.stop() self.task = None def start_stream(self, rate): self.stop_stream() self.rate = rate logging.info('start streaming with rate %d', self.rate) self.write_frame() self.task = ioloop.PeriodicCallback(self.write_frame, self.rate) ioloop.IOLoop.current().add_callback(self.task.start) pass def write_frame(self): try: frame = self.recorder.take_snapshot(self.rate/2).getvalue() self.write_message(frame, True) except: self.task.stop() pass class ControlHandler(web.RequestHandler): def initialize(self, recorder): self.recorder = recorder def get(self, context, action): if context == 'record': if action == 'start': self.recorder.start_record() elif action == 'stop': self.recorder.stop_record() if context == 'motion': if action == 'start': self.recorder.motion_event(0) elif action == 'stop': self.recorder.end_motion() pass class BufferHandler(web.RequestHandler): def initialize(self, recorder): self.recorder = recorder def get(self): seconds = int(self.get_argument('sec', '3')) logging.info("get last %d seconds", seconds) self.set_header('Content-Type', 'video/mp4') buffer = self.recorder.video_buffer buffer.copy_circular(self, seconds) self.flush() pass def main(): class LoadFromFile(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): with values as f: parser.parse_args(f.read().split(), namespace) parser = argparse.ArgumentParser(fromfile_prefix_chars='@') parser.add_argument("-c", "--config", type=open, action=LoadFromFile, help="Load config from file") parser.add_argument("-v", action="store_true", default=False, help="Verbose logging", dest="verbose") parser.add_argument("-p", '--buffer', type=int, default=3) parser.add_argument("--width", type=int, default=1296) parser.add_argument("--height", type=int, default=972) parser.add_argument("--rot", "-r", type=int, default=0) parser.add_argument("--bright", "-b", type=int, default=50) parser.add_argument("--fps", "-f", type=int, default=30) parser.add_argument("--gap", "-g", type=int, default=5, dest="event_gap") parser.add_argument("--listen", type=int, default=8092) parser.add_argument("--pre-motion-file", default="storage/{timestamp}_pre.h264") parser.add_argument("--motion-file", default="storage/{timestamp}_mov.h264") parser.add_argument("--post-process", default="") parser.add_argument("--on-motion-begin", default="") parser.add_argument("--on-motion-end", default="") parser.add_argument("--logfile", help="Logging into file") params = parser.parse_args() # configure logging logging.basicConfig(format="[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s", level=logging.DEBUG if params.verbose else logging.INFO, filename=params.logfile) camera = picamera.PiCamera( resolution=(params.width, params.height), framerate=params.fps ) camera.rotation = params.rot camera.brightness = params.bright recorder = Recorder(camera, params) recorder.start() arguments = {"recorder": recorder} webapp = web.Application([ (r"/camera/snapshot", SnapshotHandler, arguments), (r"/camera/stream", StreamHandler, arguments), (r"/camera/stream/ws", WSStreamHandler, arguments), (r"/camera/buffer", BufferHandler, arguments), (r"/camera/(record|motion)/(start|stop)", ControlHandler, arguments), ]) server = httpserver.HTTPServer(webapp, xheaders=True) server.listen(params.listen) logging.info("started camera recorder") logging.info("listen on port %d", params.listen) # Main loop start ioloop.IOLoop.instance().start() if __name__ == '__main__': main()
752c126579ac11308343a33eeb1269cb7fe2179c
[ "Python", "Shell" ]
3
Shell
led-spb/motion
14fcf86c43b328ed7fa68529c71aaf85aa3bb115
bab60aa20232e9fda2fc8fb2c82e14670cb0301d
refs/heads/master
<repo_name>tanelj/skinhead<file_sep>/README.markdown Shortcomings of most current template engines (e.g. Liquid, Smarty): * Authors must learn yet another syntax * Needs custom parser to parse template code and therefore do not produce correct HTML output when viewed in browser as static files. Design goals of this engine: * Templates are pure and valid HTML5 files * Template specific control flow is declared with element classes and "data-" attributes * Can be written and tested 100% using normal static HTML authoring tools (Dreamweaver, Notepad etc) * Does not need any parsers or renderers to see end-result in browser during template authoring * To render templates on server-side, existing html parsing and dom-manipulating components can be used * Template syntax has minimal footprint and is intuitive, does not need cheatsheet at hand to code ## Example <!doctype html> <html> <head> <title data-tpl-content="page.title"></title> </head> <body> <header> <nav data-tpl-for="menuitems"> <a href="" data-tpl-attrs="{href: menuitem.href}" data-tpl-content="menuitem.title">Foo</a> <a href="" data-tpl-remove="true">Bar</a> <a href="" data-tpl-remove="true">Baz</a> </nav> </header> <div id="main" data-tpl-content="page.body"> Body example that will be replaced with "page.body" assigned variable contents when rendering. </div> <div class="template-comment" data-tpl-remove="true"> This is Template comment that will be removed during rendering thanks to its data-tpl-remove attribute. </div> </body> </html> ## Control flow functions ### if <div data-tpl-if="page.published"> This div element will be shown only if page.published evaluates to true </div> <div data-tpl-contents-if="page.published"> The contents of this div element will be shown only if page.published evaluates to true </div> Evaluations would suck just a little bit <div data-tpl-if="3 == 3">True</div> # => <div>True</div> <div data-tpl-if="2 < 3">True</div> # => <div>True</div> <div data-tpl-if="2 > 3">False</div> # => <div>False</div> <div data-tpl-if="true || false">Dunno</div> # => <div>Dunno</div> Think of more complex equations like "page.published or page.published > Date.today" ### for Let things = ['Foo', 'Bar', 'Baz'] Template to render them in LI elements: <ul data-tpl-for="things"> <li data-tpl-content="thing"></li> </ul> # => <ul><li>Foo</li><li>Bar</li><li>Baz</li></ul> When variable assigned to for cycle is an array and named in plural form, it will automatically make variable available inside for scope with that name in singular form. ### case ### cycle ### include <div data-tpl-include="other.html"></div> File other.html could be included over AJAX with javascript (and evaluated, if necessary). ### unless Works the same way as if, only negates the evaluation ### assign Assign "page.title" to variable "myvariable". <div data-tpl-assign-var="myvariable" data-tpl-assign-value="page.title"></div> "data-tpl-remove" attribute can be used to remove current div tag (and all it's descendants) from rendering. ### capture <div data-tpl-capture="tovariable"> Whatever evaluates out from this element, it will be stored in variable named "tovariable" </div> <!-- do some stuff and release capture in next element: --> <div data-tpl-content="tovariable"></div> Again, "data-tpl-remove" tag could do some clean-up. ### comments Use normal HTML comments. OR: <div data-tpl-remove="true"> This is a comment too. </div> ## Filters data-filter-attribute can be used ### truncate <div data-tpl-filter-truncate="15">This text is longer than 15 characters</div> # => <div>This text is...</div> ### replace <div data-tpl-filter-find="Foo" data-tpl-filter-replace="Bar">Foo Bar</div> # => <div>Bar bar</div> "data-tpl-filter-ireplace" could be case-insensitive replace filter. These are just examples of filters, more of them could be developed easily. ## Javascript The example above can be easily rendered to full page even with javascript. Consider adding this script to the end of page: <script src="http://myhost.com/fantastic.template.renderer.js" /> <script> var data = { menuitems = [ {title: 'Home page', href: '/'}, {title: 'Blog', href: '/blog'}, {title: 'Contacts', href: '/contacts'} ], page = { title: 'Awesome page', body: 'Page body' } } TemplateRenderer.renderWith(data); </script> Then this html file renders as <!doctype html> <html> <head> <title>Awesome page</title> </head> <body> <header> <nav> <a href="/">Home page</a> <a href="/blog">Blog</a> <a href="/contacts">Contacts</a> </nav> </header> <div id="main">Page body</div> </body> </html> ## Unresolved questions and shortcomings Render attribute only under certain conditions: <a href="" data-tpl-attr-class-if="page.published" data-tpl-attr-class-val-if="published">Page link</a> # => <div class="published"></div> Render part of attribute onlu under certain conditions: <a href="" class="menuitem" data-tpl-append-class-if="page.published" data-tpl-attr-append-class-val-if="published">Page link</a> # => <a href="" class="menuitem published">Page link</a> <file_sep>/spec/lib/tpl_spec.rb require 'spec_helper' require 'benchmark' describe Skinhead do describe 'data-tpl-content' do it 'should work' do tpl = <<-EOF <div data-tpl-content="body">Default content</div> EOF # time = Benchmark.measure do # Skinhead.render(doc, {:body => 'Test body'}).strip.should == '<div>Test body</div>' # end # puts time Skinhead.render(tpl, {:body => 'Test body'}).strip.should == '<div>Test body</div>' end end describe 'data-tpl-remove' do it 'removes element entirely' do tpl = <<-EOF <div>This will stay</div> <div data-tpl-remove="true">This will go</div> EOF Skinhead.render(tpl).strip.should == '<div>This will stay</div>' end end describe 'data-tpl-capture' do it 'captures the contents of element' it 'assigns the captured content to variable given in attribute value' end describe 'filters' do describe 'find-replace' do it 'finds the value of data-tpl-filter-find and replaces it with data-tpl-filter-replace value' do tpl = <<-EOF <div data-tpl-filter-find="Foo" data-tpl-filter-replace="Bar">Foo baz</div> EOF Skinhead.render(tpl).strip.should == '<div>Bar baz</div>' end end end end<file_sep>/lib/skinhead.rb require 'nokogiri' module Skinhead class << self def render(tpl, assigns = {}) doc = Nokogiri::HTML::DocumentFragment.parse(tpl) doc.css('*[data-tpl-content]').each do |i| # i['data-tpl-content'] = nil i.content = assigns[i['data-tpl-content'].to_sym] i.remove_attribute('data-tpl-content') end doc.css('*[data-tpl-remove]').each { |i| i.unlink } # Filters doc.css('*[data-tpl-filter-find]').each do |i| find = i['data-tpl-filter-find'] replace = i['data-tpl-filter-replace'] if find and replace i.content = i.content.gsub(%r{#{find}}, replace) end i.remove_attribute('data-tpl-filter-find') i.remove_attribute('data-tpl-filter-replace') end doc.to_html end end end
3e4c021b9dde5290b8391700d526f76013fa09b2
[ "Markdown", "Ruby" ]
3
Markdown
tanelj/skinhead
0a0bac56be06cf28a16e92873a704aa6af2dcc1d
1ad4d4743696f404fafea57d915b2cf44ba08c92
refs/heads/master
<file_sep># sima_logger Tool for logging sensor information about fermentation process. For now plan is to have temperature logging and serve it to web server. In the future might include scale to measure how much of the sugar has been converted to alcohol and CO2. <file_sep>"""main.py Main file of the program. Will maybe have some terminal text based UI Or LCD and button based UI. @author <NAME> <<EMAIL>> """ from threading import Timer from time import sleep from sensor import ds18b20_sensor from constants import SENSOR_ID_LOCATIONS, SENSOR_TIMINGS #List for storing sensor objects sensor_list = [] #Key is the sensor family code/etc. For ds18b20 sensors, id always starts with the family code 28- #TODO: Figure out if this works for weight sensor as well and possible other sensors. sensor_classes = {"28-": ds18b20_sensor} def cleanup(): pass def init(): #Create class for each sensor and then create timer. for sensor_id in SENSOR_ID_LOCATIONS.keys(): #Checking what kind of sensor it is and then using correct constructor for sensor_family_code in sensor_classes: #We check if sensor id starts with if sensor_id.startswith(sensor_family_code): sensor = sensor_classes[sensor_family_code](sensor_id, SENSOR_ID_LOCATIONS[sensor_id]) sensor_list.append(sensor) def main(): init() while 1: print("Looping") sleep(2) if __name__ == "__main__": main() <file_sep>"""constants.py File for all the constants needed by different files. @author <NAME> <<EMAIL>> """ import glob #Database parameters TEMPERATURE_DATABASE_NAME_DB = "simaattori_temperature.db" TEMPERATURE_DATABASE_NAME_JSON = "simaattori_temperature.json" DS18B20_BASE_DIR = '/sys/bus/w1/devices/' #Timer, key is sensor id, value is time in seconds. How often temperature values are saved. SENSOR_TIMINGS = {"28-000006564895": 3} #Sensor information SENSOR_ID_LOCATIONS = { "28-000006564895" : "Waterproof DS18B20 sensor" } <file_sep>"""main.py For handling database. Either SQL or stick with JSON, depending on do I want to edit lines later on. @author <NAME> <<EMAIL>> """ import sqlite3 from constants import * def init_tables(): #TODO: Check if table has been created already pass #TODO: if not then create def main(): conn = sqlite3.connect(TEMPERATURE_DATABASE_NAME_DB) cursor = conn.cursor() #Save something to database cursor.execute("CREATE TABLE DS18B20( measurement_id INT NOT NULL AUTO_INCREMENT, \ sensor_id INT NOT NULL, \ date DATE NOT NULL, \ time TIME NOT NULL, \ value varchar(50), \ PRIMARY KEY ( measurement_id ))") conn.commit() #Retrieve what was saved to confirm it works. cursor.execute("SELECT * FROM Cars") rows = cursor.fetchall() for row in rows: print "Id: %d, Model: %s, Price: %d" % (row[0], row[1], row[2]) if conn: conn.close() if __name__ == "__main__": main() <file_sep>"""sensor.py Implementation of base sensor class. Also holds all sensor sub classes. @author <NAME> <<EMAIL>> """ import os, time from threading import Timer #Not sure of the database and what kind it should be yet so import everything. import database from constants import SENSOR_ID_LOCATIONS, SENSOR_TIMINGS, DS18B20_BASE_DIR class RepeatTimer(object): """ Timer that repeats after <interval>. Timer from threading doesnt do this, so this improved timer that uses threading.Timer does. """ def __init__(self, interval, function, args=[], kwargs={}): """ Used to initialize timer @param interval nada @param function nada @param args not needed right now, maybe later """ self._interval = interval self._function = function self._timer = None self._args = args self._kwargs = kwargs def start(self): print("Timer started") self._timer = Timer(self._interval, self._function, *self._args, **self._kwargs) self._timer.start() class sensor(object): """ Sensor class. Used for dealing with indiividual sensors. Will hold information such as sensor id, what to do when saving time etc. Note that this is baseclass. For each sensor type create its own class. Also, if sensor placement/usage dictates different way of saving information, then also inherit. """ def __init__(self, sensor_id, descr_str): """ Used to initialize sensor. @param sensor_id nada @param descr_str nada """ print("Creating sensor with id: %s, with timing: %d and description: %s" % (sensor_id, SENSOR_TIMINGS[sensor_id], descr_str)) self._sensor_id = sensor_id self._descr_str = descr_str self._timer = RepeatTimer(SENSOR_TIMINGS[sensor_id], self.save_value, ()) self._timer.start() def _get_value(self): """ Virtual class. """ assert(False) def save_value(self): """ Wrapper that handler commong operations for saving values and calls virtual function """ value = self._get_value() print("From sensor: %s / %s got value: %s" % (self._sensor_id, self._descr_str, value)) self._timer.start() class ds18b20_sensor(sensor): """ Dallas instruments DS18B20 Temperature sensor handler. Used Adafruit code for getting temperature values and converting to celsius code as an example. """ def __init__(self, sensor_id, descr_str): sensor.__init__(self, sensor_id, descr_str) self._device_file = DS18B20_BASE_DIR + sensor_id + '/w1_slave' #TODO: Check that this sensor is connected, if not throw exception. def _get_raw_data(self): f = open(self._device_file, 'r') lines = f.readlines() f.close() return lines def _get_value(self): """ Gets Temperature from the sensor and saves it to the database @return Returns the value from the sensor """ #TODO: Create fetching of temperature lines = self._get_raw_data() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = self._get_raw_data() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 return temp_c class weight_sensor(sensor): """ This will be custom weight sensor created using normal scale. Hardware not ready yet as such implementation cannot be done. """ def __init__(self, sensor_id, descr_str): sensor.__init__(self, sensor_id, descr_str) #TODO: Check that this sensor is connected, if not throw exception. <file_sep>Block diagram created with www.draw.io. XML file can be loaded to the web application for editing. Does not follow Any official UML etc.
c00befeeb4048bf944e688c559cacc0fdca4ea40
[ "Markdown", "Python", "Text" ]
6
Markdown
ukasofisosaari/simaattori
98e02b1419752704e88b93d2550576ba4b6edae8
55b325eb4bf806219ed8d5b29cb5f2bea6287dae
refs/heads/master
<repo_name>jemusser/Cargparse<file_sep>/argparse.c #include "argparse.h" Arg* head = 0; Arg* tail = 0; char* l_ptr; void assert(int v, char* format, ...) { if (!v) { va_list args; va_start(args, format); vprintf(format, args); va_end(args); exit(-1); } } Arg* _find_long(const char* value) { Arg* tmparg = head; while (tmparg) { if (strncmp(value, tmparg->long_flag, strlen(value)) == 0) break; tmparg = tmparg->next; } assert(tmparg != NULL, "Unknown flag - %s\n", value); return tmparg; } Arg* _find_short(char value) { Arg* tmparg = head; while (tmparg) { if (value == tmparg->short_flag) break; tmparg = tmparg->next; } assert(tmparg != NULL, "Unknown flag - %c\n", value); return tmparg; } Arg* _find_flagless(int index) { Arg* tmparg = head; while (tmparg) { if (!tmparg->long_flag && ! tmparg->short_flag) { if (index == 0) break; index -= 1; } tmparg = tmparg->next; } assert(tmparg != NULL, "Unknown positional argument - %d\n", index); return tmparg; } void print_help(const char* desc) { Arg* tmparg = head; printf("\n%s\n\n", desc); while (tmparg) { int llen = (tmparg->long_flag == NULL ? 0 : strlen(tmparg->long_flag)); printf(" "); if (tmparg->short_flag) printf("-%c", tmparg->short_flag); else printf(" "); printf(" "); if (tmparg->long_flag) printf("--%s", tmparg->long_flag); else printf(" "); for (int i=0; i < 15 - llen; i++) printf(" "); switch (tmparg->data.type) { case INTEGER: printf(" [integer] "); break; case STRING: printf(" [string] "); break; case BOOLEAN: printf(" [boolean] "); break; } printf(" %s %s\n", (tmparg->required ? "(REQUIRED)":""), tmparg->description); tmparg = tmparg->next; } } void parse_args(int nargs, char* kwargs[], const char* desc) { int nflagless = 0; for (int i = 1; i < nargs; i++) { char* arg = kwargs[i]; if (strncmp(arg, "--help", strlen(arg)) == 0 || strncmp(arg, "-h", 2) == 0) { print_help(desc); exit(0); } if (strncmp(arg, "--", 2) == 0) { /* long name */ arg += 2; Arg* a = _find_long(arg); if (a) { if (a->data.type == BOOLEAN) a->data.value.i = 1; else { i += 1; assert(i < nargs && kwargs[i][0] != '-', "Value required for flag - %s\n", a->name); if (a->data.type == INTEGER) a->data.value.i = atoi(kwargs[i]); else a->data.value.s = kwargs[i]; } a->exists = 1; } } else if (arg[0] == '-') { /* short name */ arg += 1; int len = strlen(arg); for (int j=0; j < len; j++) { Arg* a = _find_short(arg[j]); if (a) { if (a->data.type == BOOLEAN) a->data.value.i = 1; else { i += 1; assert(i < nargs && j == len - 1 && kwargs[i][0] != '-', "Value required for flag - %s\n", a->name); if (a->data.type == INTEGER) a->data.value.i = atoi(kwargs[i]); else a->data.value.s = kwargs[i]; } a->exists = 1; } } } else { /* unnamed arguments */ Arg* a = _find_flagless(nflagless); nflagless += 1; if (a->data.type == STRING) a->data.value.s = arg; else a->data.value.i = atoi(arg); a->exists = 1; } } Arg* tmparg = head; while (tmparg) { assert(tmparg->exists > 0, "%s is required\n", tmparg->name); tmparg = tmparg->next; } } int add_argument(const char* name, const char* _short, const char* _long, ArgValue _default, ty _type, int required, const char* desc) { Arg* newArg = (Arg*) malloc(sizeof(Arg)); newArg->name = name; newArg->short_flag = (_short == NULL ? 0 : _short[0]); newArg->long_flag = _long; newArg->data.type = _type; newArg->data.value = _default; newArg->exists = (required ? 0 : 1); newArg->required = required; newArg->description = desc; newArg->next = NULL; if (tail) { tail->next = newArg; tail = newArg; } else { head = newArg; tail = newArg; } return 1; } int add_integer_arg(const char* name, char* _short, const char* _long, int _default, int required, const char* desc) { ArgValue val; val.i = _default; return add_argument(name, _short, _long, val, INTEGER, required, desc); } int add_string_arg(const char* name, char* _short, const char* _long, char* _default, int required, const char* desc) { ArgValue val; val.s = _default; return add_argument(name, _short, _long, val, STRING, required, desc); } int add_boolean_arg(const char* name, char* _short, const char* _long, const char* desc) { ArgValue val; val.i = 0; return add_argument(name, _short, _long, val, BOOLEAN, 0, desc); } ArgValue get_argument(const char* name) { Arg* tmphead = head; while (tmphead) { if (strncmp(tmphead->name, name, strlen(name)) == 0) { break; return tmphead->data.value; } tmphead = tmphead->next; } assert(tmphead != NULL, "Argument does not exist - %s\n", name); return tmphead->data.value; } char* get_string_arg(const char* name) { return get_argument(name).s; } int get_boolean_arg(const char* name) { return get_argument(name).i; } int get_integer_arg(const char* name) { return get_argument(name).i; } void del_argparse() { Arg* tmphead = head; Arg* current; while (tmphead) { current = tmphead; tmphead = tmphead->next; free(current); } } <file_sep>/argparse.h #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #define STRING 0 #define INTEGER 1 #define BOOLEAN 2 typedef int ty; typedef union { int i; char* s; } ArgValue; typedef struct t_arg_type { ty type; ArgValue value; } ArgType; typedef struct t_arg Arg; struct t_arg { Arg* next; const char* name; const char* long_flag; char short_flag; ArgType data; int exists; int required; const char* description; }; void parse_args(int nargs, char* kwargs[], const char* desc); int add_integer_arg(const char* name, char* _short, const char* _long, int _default, int required, const char* desc); int add_string_arg(const char* name, char* _short, const char* _long, char* _default, int required, const char* desc); int add_boolean_arg(const char* name, char* _short, const char* _long, const char* desc); char* get_string_arg(const char* name); int get_boolean_arg(const char* name); int get_integer_arg(const char* name); void del_argparse();
b75277990de1d075ad6d110157d8fdbccb47a7fd
[ "C" ]
2
C
jemusser/Cargparse
a869d9d810e5102b53feeb666439d90cb486b559
c2e39b06cd68c1b278edb63a53911c512b24139a
refs/heads/master
<file_sep>class Idioma < ApplicationRecord has_and_belongs_to_many :libros end <file_sep>class ParentPdf < Prawn::Document def initialize(libro) super(top_margin: 70) @libro = libro text "Libro \##{@libro.nombre}" text "Idiomas \##{@libro.idiomas.map(&:nombre).join(', ')}" end end<file_sep>json.partial! "idiomas_libros/idiomas_libro", idiomas_libro: @idiomas_libro <file_sep>class Autor < ApplicationRecord has_and_belongs_to_many :libros end <file_sep>require "application_system_test_case" class IdiomasLibrosTest < ApplicationSystemTestCase setup do @idiomas_libro = idiomas_libros(:one) end test "visiting the index" do visit idiomas_libros_url assert_selector "h1", text: "Idiomas Libros" end test "creating a Idiomas libro" do visit idiomas_libros_url click_on "New Idiomas Libro" fill_in "Idioma", with: @idiomas_libro.idioma_id fill_in "Libro", with: @idiomas_libro.libro_id click_on "Create Idiomas libro" assert_text "Idiomas libro was successfully created" click_on "Back" end test "updating a Idiomas libro" do visit idiomas_libros_url click_on "Edit", match: :first fill_in "Idioma", with: @idiomas_libro.idioma_id fill_in "Libro", with: @idiomas_libro.libro_id click_on "Update Idiomas libro" assert_text "Idiomas libro was successfully updated" click_on "Back" end test "destroying a Idiomas libro" do visit idiomas_libros_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Idiomas libro was successfully destroyed" end end <file_sep>json.array! @idiomas_libros, partial: "idiomas_libros/idiomas_libro", as: :idiomas_libro <file_sep>class Libro < ApplicationRecord has_and_belongs_to_many :idiomas has_and_belongs_to_many :autors end <file_sep>json.extract! libro, :id, :nombre, :idioma_id, :created_at, :updated_at json.url libro_url(libro, format: :json) <file_sep>require 'test_helper' class AutorsLibrosControllerTest < ActionDispatch::IntegrationTest setup do @autors_libro = autors_libros(:one) end test "should get index" do get autors_libros_url assert_response :success end test "should get new" do get new_autors_libro_url assert_response :success end test "should create autors_libro" do assert_difference('AutorsLibro.count') do post autors_libros_url, params: { autors_libro: { autor_id: @autors_libro.autor_id, libro_id: @autors_libro.libro_id } } end assert_redirected_to autors_libro_url(AutorsLibro.last) end test "should show autors_libro" do get autors_libro_url(@autors_libro) assert_response :success end test "should get edit" do get edit_autors_libro_url(@autors_libro) assert_response :success end test "should update autors_libro" do patch autors_libro_url(@autors_libro), params: { autors_libro: { autor_id: @autors_libro.autor_id, libro_id: @autors_libro.libro_id } } assert_redirected_to autors_libro_url(@autors_libro) end test "should destroy autors_libro" do assert_difference('AutorsLibro.count', -1) do delete autors_libro_url(@autors_libro) end assert_redirected_to autors_libros_url end end <file_sep>Rails.application.routes.draw do devise_for :users resources :autors_libros resources :autors resources :idiomas_libros resources :libros resources :idiomas resources :users root 'libros#index', as: 'user_signedin' devise_scope :user do root 'devise/sessions#new' end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end <file_sep>class AutorsLibrosController < ApplicationController before_action :set_autors_libro, only: [:show, :edit, :update, :destroy] # GET /autors_libros # GET /autors_libros.json def index @autors_libros = AutorsLibro.all end # GET /autors_libros/1 # GET /autors_libros/1.json def show end # GET /autors_libros/new def new @autors_libro = AutorsLibro.new end # GET /autors_libros/1/edit def edit end # POST /autors_libros # POST /autors_libros.json def create @autors_libro = AutorsLibro.new(autors_libro_params) respond_to do |format| if @autors_libro.save format.html { redirect_to @autors_libro, notice: 'Autors libro was successfully created.' } format.json { render :show, status: :created, location: @autors_libro } else format.html { render :new } format.json { render json: @autors_libro.errors, status: :unprocessable_entity } end end end # PATCH/PUT /autors_libros/1 # PATCH/PUT /autors_libros/1.json def update respond_to do |format| if @autors_libro.update(autors_libro_params) format.html { redirect_to @autors_libro, notice: 'Autors libro was successfully updated.' } format.json { render :show, status: :ok, location: @autors_libro } else format.html { render :edit } format.json { render json: @autors_libro.errors, status: :unprocessable_entity } end end end # DELETE /autors_libros/1 # DELETE /autors_libros/1.json def destroy @autors_libro.destroy respond_to do |format| format.html { redirect_to autors_libros_url, notice: 'Autors libro was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_autors_libro @autors_libro = AutorsLibro.find(params[:id]) end # Only allow a list of trusted parameters through. def autors_libro_params params.require(:autors_libro).permit(:libro_id, :autor_id) end end <file_sep>json.partial! "autors_libros/autors_libro", autors_libro: @autors_libro <file_sep>class LibrosController < ApplicationController before_action :set_libro, only: [:show, :edit, :update, :destroy] # GET /libros # GET /libros.json def index @libros = Libro.all end # GET /libros/1 # GET /libros/1.json def show respond_to do |format| format.html format.pdf do pdf = ParentPdf.new(@libro) send_data pdf.render, filename: "libro_#{@libro.nombre}.pdf", type: "application/pdf", disposition: "inline" end end end # GET /libros/new def new @libro = Libro.new @libros = Libro.all end # GET /libros/1/edit def edit @libros = Libro.all end # POST /libros # POST /libros.json def create @libro = Libro.new(libro_params) params[:libro][:idioma_ids].each do |idioma_id| unless idioma_id.empty? idioma = Idioma.find(idioma_id) @libro.idiomas << idioma end end params[:libro][:autor_ids].each do |autor_id| unless autor_id.empty? autor = Autor.find(autor_id) @libro.autors << autor end end respond_to do |format| if @libro.save format.html { redirect_to new_libro_path , notice: 'Libro was successfully created.' } format.json { render :show, status: :created, location: @libro } else format.html { render :new } format.json { render json: @libro.errors, status: :unprocessable_entity } end end end # PATCH/PUT /libros/1 # PATCH/PUT /libros/1.json def update params[:libro][:idioma_ids].each do |idioma_id| unless idioma_id.empty? idioma = Idioma.find(idioma_id) @libro.idiomas << idioma end end params[:libro][:autor_ids].each do |autor_id| unless autor_id.empty? autor = Autor.find(autor_id) @libro.autors << autor end end respond_to do |format| if @libro.update(libro_params) format.html { redirect_to new_libro_path, notice: 'Libro was successfully updated.' } format.json { render :show, status: :ok, location: @libro } else format.html { render :edit } format.json { render json: @libro.errors, status: :unprocessable_entity } end end end # DELETE /libros/1 # DELETE /libros/1.json def destroy @libro.destroy respond_to do |format| format.html { redirect_to new_libro_path, notice: 'Libro was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_libro @libro = Libro.find(params[:id]) end # Only allow a list of trusted parameters through. def libro_params params.require(:libro).permit(:nombre, :idioma_id, :autor_id) end end <file_sep>//= link_tree ../images //= link_directory ../stylesheets .css //= require stisla //= require scripts //= require custom<file_sep>class IdiomasLibrosController < ApplicationController before_action :set_idiomas_libro, only: [:show, :edit, :update, :destroy] # GET /idiomas_libros # GET /idiomas_libros.json def index @idiomas_libros = IdiomasLibro.all end # GET /idiomas_libros/1 # GET /idiomas_libros/1.json def show end # GET /idiomas_libros/new def new @idiomas_libro = IdiomasLibro.new end # GET /idiomas_libros/1/edit def edit end # POST /idiomas_libros # POST /idiomas_libros.json def create @idiomas_libro = IdiomasLibro.new(idiomas_libro_params) respond_to do |format| if @idiomas_libro.save format.html { redirect_to @idiomas_libro, notice: 'Idiomas libro was successfully created.' } format.json { render :show, status: :created, location: @idiomas_libro } else format.html { render :new } format.json { render json: @idiomas_libro.errors, status: :unprocessable_entity } end end end # PATCH/PUT /idiomas_libros/1 # PATCH/PUT /idiomas_libros/1.json def update respond_to do |format| if @idiomas_libro.update(idiomas_libro_params) format.html { redirect_to @idiomas_libro, notice: 'Idiomas libro was successfully updated.' } format.json { render :show, status: :ok, location: @idiomas_libro } else format.html { render :edit } format.json { render json: @idiomas_libro.errors, status: :unprocessable_entity } end end end # DELETE /idiomas_libros/1 # DELETE /idiomas_libros/1.json def destroy @idiomas_libro.destroy respond_to do |format| format.html { redirect_to idiomas_libros_url, notice: 'Idiomas libro was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_idiomas_libro @idiomas_libro = IdiomasLibro.find(params[:id]) end # Only allow a list of trusted parameters through. def idiomas_libro_params params.require(:idiomas_libro).permit(:idioma_id, :libro_id) end end <file_sep>class IdiomasLibro < ApplicationRecord belongs_to :idioma belongs_to :libro end <file_sep>require 'test_helper' class IdiomasLibrosControllerTest < ActionDispatch::IntegrationTest setup do @idiomas_libro = idiomas_libros(:one) end test "should get index" do get idiomas_libros_url assert_response :success end test "should get new" do get new_idiomas_libro_url assert_response :success end test "should create idiomas_libro" do assert_difference('IdiomasLibro.count') do post idiomas_libros_url, params: { idiomas_libro: { idioma_id: @idiomas_libro.idioma_id, libro_id: @idiomas_libro.libro_id } } end assert_redirected_to idiomas_libro_url(IdiomasLibro.last) end test "should show idiomas_libro" do get idiomas_libro_url(@idiomas_libro) assert_response :success end test "should get edit" do get edit_idiomas_libro_url(@idiomas_libro) assert_response :success end test "should update idiomas_libro" do patch idiomas_libro_url(@idiomas_libro), params: { idiomas_libro: { idioma_id: @idiomas_libro.idioma_id, libro_id: @idiomas_libro.libro_id } } assert_redirected_to idiomas_libro_url(@idiomas_libro) end test "should destroy idiomas_libro" do assert_difference('IdiomasLibro.count', -1) do delete idiomas_libro_url(@idiomas_libro) end assert_redirected_to idiomas_libros_url end end <file_sep>class AutorsLibro < ApplicationRecord belongs_to :libro belongs_to :autor end <file_sep>json.array! @autors_libros, partial: "autors_libros/autors_libro", as: :autors_libro <file_sep>json.extract! autors_libro, :id, :libro_id, :autor_id, :created_at, :updated_at json.url autors_libro_url(autors_libro, format: :json) <file_sep>json.extract! idiomas_libro, :id, :idioma_id, :libro_id, :created_at, :updated_at json.url idiomas_libro_url(idiomas_libro, format: :json) <file_sep>require "application_system_test_case" class AutorsLibrosTest < ApplicationSystemTestCase setup do @autors_libro = autors_libros(:one) end test "visiting the index" do visit autors_libros_url assert_selector "h1", text: "Autors Libros" end test "creating a Autors libro" do visit autors_libros_url click_on "New Autors Libro" fill_in "Autor", with: @autors_libro.autor_id fill_in "Libro", with: @autors_libro.libro_id click_on "Create Autors libro" assert_text "Autors libro was successfully created" click_on "Back" end test "updating a Autors libro" do visit autors_libros_url click_on "Edit", match: :first fill_in "Autor", with: @autors_libro.autor_id fill_in "Libro", with: @autors_libro.libro_id click_on "Update Autors libro" assert_text "Autors libro was successfully updated" click_on "Back" end test "destroying a Autors libro" do visit autors_libros_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Autors libro was successfully destroyed" end end
b1f25937c5010a4eaa5d59d6c808205aa57acfb1
[ "JavaScript", "Ruby" ]
22
Ruby
Dfsma/biblioteca-rails
78e86e323f11264d94bf6df07d8e14774477d1cb
2ce37f64899c474483b4b3a3b52578b7e3cbdb88
refs/heads/main
<repo_name>anlgev/Association_Rule_Learning<file_sep>/Association_Rule_Learning.py ############################################ # Project ARL Recommendation ############################################ # Data Set Information: # This Online Retail II data set contains all the transactions occurring for a UK-based and registered, # non-store online retail between 01/12/2009 and 09/12/2011. The company mainly sells unique all-occasion gift-ware. # Many customers of the company are wholesalers. # Invoice: Invoice number. if the invoice values contain 'C' it means return # StockCode: Product (item) code. # Description: Product (item) name. # Quantity: The quantities of each product (item) per Invoice. # InvoiceDate: Invoice date and time. # UnitPrice: Unit price. # CustomerID: Customer number. # Country: Country name. import datetime as dt import pandas as pd import pymysql from sqlalchemy import create_engine from sklearn.preprocessing import MinMaxScaler from lifetimes import BetaGeoFitter from lifetimes import GammaGammaFitter from mlxtend.frequent_patterns import apriori, association_rules from helpers.helpers import crm_data_prep from helpers.myfunc import check_data pd.set_option('display.max_columns', None) df_ = pd.read_excel('dataset/online_retail_II.xlsx', sheet_name="Year 2010-2011") df = df_.copy() df.info() df.head() ###################################### # Data Preparation ###################################### df_prep = crm_data_prep(df) df_prep.head() check_data(df_prep) ###################################### # Create CLTV Segment and Prediction ####################################### def create_cltv_p(dataframe): today_date = dt.datetime(2011, 12, 11) # Create RFM Metrics rfm = dataframe.groupby('Customer ID').agg({'InvoiceDate': [lambda date: (date.max() - date.min()).days, lambda date: (today_date - date.min()).days], 'Invoice': lambda num: num.nunique(), 'TotalPrice': lambda TotalPrice: TotalPrice.sum()}) rfm.columns = rfm.columns.droplevel(0) ## recency_cltv_p rfm.columns = ['recency_cltv_p', 'T', 'frequency', 'monetary'] ## basic monetary_avg rfm["monetary"] = rfm["monetary"] / rfm["frequency"] rfm.rename(columns={"monetary": "monetary_avg"}, inplace=True) # convert daily values to weekly for recency and tenure # recency_weekly_cltv_p rfm["recency_weekly_cltv_p"] = rfm["recency_cltv_p"] / 7 rfm["T_weekly"] = rfm["T"] / 7 # Control rfm = rfm[rfm["monetary_avg"] > 0] rfm = rfm[(rfm['frequency'] > 1)] rfm["frequency"] = rfm["frequency"].astype(int) # BGNBD Model bgf = BetaGeoFitter(penalizer_coef=0.01) bgf.fit(rfm['frequency'], rfm['recency_weekly_cltv_p'], rfm['T_weekly']) # exp_sales_1_month rfm["exp_sales_1_month"] = bgf.predict(4, rfm['frequency'], rfm['recency_weekly_cltv_p'], rfm['T_weekly']) # exp_sales_3_month rfm["exp_sales_3_month"] = bgf.predict(12, rfm['frequency'], rfm['recency_weekly_cltv_p'], rfm['T_weekly']) # expected_average_profit ggf = GammaGammaFitter(penalizer_coef=0.01) ggf.fit(rfm['frequency'], rfm['monetary_avg']) rfm["expected_average_profit"] = ggf.conditional_expected_average_profit(rfm['frequency'], rfm['monetary_avg']) # 6 month cltv_p cltv = ggf.customer_lifetime_value(bgf, rfm['frequency'], rfm['recency_weekly_cltv_p'], rfm['T_weekly'], rfm['monetary_avg'], time=6, freq="W", discount_rate=0.01) rfm["cltv_p"] = cltv # minmaxscaler scaler = MinMaxScaler(feature_range=(1, 100)) scaler.fit(rfm[["cltv_p"]]) rfm["cltv_p"] = scaler.transform(rfm[["cltv_p"]]) # rfm.fillna(0, inplace=True) # cltv_p_segment rfm["cltv_p_segment"] = pd.qcut(rfm["cltv_p"], 3, labels=["C", "B", "A"]) ## recency_cltv_p, recency_weekly_cltv_p rfm = rfm[["recency_cltv_p", "T", "monetary_avg", "recency_weekly_cltv_p", "T_weekly", "exp_sales_1_month", "exp_sales_3_month", "expected_average_profit", "cltv_p", "cltv_p_segment"]] return rfm cltv_p = create_cltv_p(df_prep) check_data(cltv_p) cltv_p.head() cltv_p.groupby("cltv_p_segment").agg({"count", "mean"}) ###################################### # Identification of customers by cltv segments ###################################### # Get index value a_segment_ids = cltv_p[cltv_p["cltv_p_segment"] == "A"].index b_segment_ids = cltv_p[cltv_p["cltv_p_segment"] == "B"].index c_segment_ids = cltv_p[cltv_p["cltv_p_segment"] == "C"].index a_segment_df = df_prep[df_prep["Customer ID"].isin(a_segment_ids)] b_segment_df = df_prep[df_prep["Customer ID"].isin(b_segment_ids)] c_segment_df = df_prep[df_prep["Customer ID"].isin(c_segment_ids)] a_segment_df.head() check_data(a_segment_df) ###################################### # Apriori Rules ###################################### def create_invoice_product_df(dataframe): return dataframe.groupby(['Invoice', 'StockCode'])['Quantity'].sum().unstack().fillna(0). \ applymap(lambda x: 1 if x > 0 else 0) def create_rules(dataframe, country=False, head=5): if country: dataframe = dataframe[dataframe['Country'] == country] dataframe = create_invoice_product_df(dataframe) frequent_itemsets = apriori(dataframe, min_support=0.01, use_colnames=True) rules = association_rules(frequent_itemsets, metric="support", min_threshold=0.01) print(rules.sort_values("lift", ascending=False).head(head)) else: dataframe = create_invoice_product_df(dataframe) frequent_itemsets = apriori(dataframe, min_support=0.01, use_colnames=True) rules = association_rules(frequent_itemsets, metric="support", min_threshold=0.01) print(rules.sort_values("lift", ascending=False).head(head)) return rules # Identifying products by segments rules_a = create_rules(a_segment_df) product_a = int(rules_a["consequents"].apply(lambda x: list(x)[0]).astype("unicode")[0]) rules_b = create_rules(b_segment_df) product_b = int(rules_b["consequents"].apply(lambda x: list(x)[0]).astype("unicode")[0]) rules_c = create_rules(c_segment_df) product_c = int(rules_c["consequents"].apply(lambda x: list(x)[0]).astype("unicode")[0]) # Control def check_id(stock_code): product_name = df_prep[df_prep["StockCode"] == stock_code][["Description"]].values[0].tolist() return print(product_name) check_id(20719)
831d90551491d479efe0deacb49b189eadfed086
[ "Python" ]
1
Python
anlgev/Association_Rule_Learning
a0c1a371168d0e83e880a2cda0c331b1dd3c5746
968c501e62b3e9fc1dd9415c347f3b7caf76a124
refs/heads/master
<file_sep># -*- coding: utf-8 -*- import os import unittest from collective.csv2atvocabularymanager.testing import CSV2ATVM_INTEGRATION_TESTING from collective.csv2atvocabularymanager.csv_import import createVocabulary class TestUtility(unittest.TestCase): layer = CSV2ATVM_INTEGRATION_TESTING def test_basic_registration(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example1', "Foo 1", description="Simple foo vocabulary") self.assertTrue('example1' in portal.portal_vocabularies.objectIds()) self.assertEqual(portal.portal_vocabularies.example1.Title(), "Foo 1") self.assertEqual(portal.portal_vocabularies.example1.item_1.Title(), "Item one") self.assertEqual(portal.portal_vocabularies.example1.item_1.Language(), "en") def test_registration_with_lang_suffix(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example1', "Foo 1", change_master_with_language_id=True) self.assertTrue('item_1-en' in portal.portal_vocabularies.example1.objectIds()) def test_sort_control(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example2', "Foo 2") self.assertEqual(portal.portal_vocabularies.example2.objectIds(), ['item_3', 'item_1', 'item_2']) self.assertEqual(portal.portal_vocabularies.example2.getVocabularyLines(), [('item_1', 'Item one'), ('item_3', 'Item three'), ('item_2', 'Item two')]) portal_vocabularies.manage_delObjects('example2') createVocabulary(portal_vocabularies, base_path, 'example2', "Foo 2", sortMethod='getObjPositionInParent') self.assertEqual(portal.portal_vocabularies.example2.objectIds(), ['item_3', 'item_1', 'item_2']) self.assertEqual(portal.portal_vocabularies.example2.getVocabularyLines(), [('item_3', 'Item three'), ('item_1', 'Item one'), ('item_2', 'Item two')]) <file_sep># -*- coding: utf-8 -*- from zope.configuration import xmlconfig from plone.testing import z2 from plone.app.testing import PLONE_FIXTURE from plone.app.testing import PloneSandboxLayer from plone.app.testing import IntegrationTesting from plone.app.testing import quickInstallProduct from plone.app.testing import setRoles from plone.app.testing import TEST_USER_ID class Csv2AtvmPanel(PloneSandboxLayer): defaultBases = (PLONE_FIXTURE, ) def setUpZope(self, app, configurationContext): # Load ZCML for this package import collective.csv2atvocabularymanager import Products.ATVocabularyManager xmlconfig.file('configure.zcml', Products.ATVocabularyManager, context=configurationContext) xmlconfig.file('configure.zcml', Products.LinguaPlone, context=configurationContext) z2.installProduct(app, 'Products.ATVocabularyManager') z2.installProduct(app, 'Products.LinguaPlone') def setUpPloneSite(self, portal): #applyProfile(portal, 'collective.analyticspanel:default') quickInstallProduct(portal, 'Products.LinguaPlone') quickInstallProduct(portal, 'Products.ATVocabularyManager') setRoles(portal, TEST_USER_ID, ['Member', 'Manager']) ltool = portal.portal_languages defaultLanguage = 'en' supportedLanguages = ['en', 'it', 'es'] ltool.manage_setLanguageSettings(defaultLanguage, supportedLanguages) CSV2ATVM_FIXTURE = Csv2AtvmPanel() CSV2ATVM_INTEGRATION_TESTING = IntegrationTesting(bases=(CSV2ATVM_FIXTURE, ), name="CSV2ATVM:Integration") <file_sep># -*- extra stuff goes here -*- import logging logger = logging.getLogger('collective.csv2atvocabularymanager') <file_sep># -*- coding: utf-8 -*- import os import csv try: from collections import OrderedDict except ImportError: # Python <=2.6 from ordereddict import OrderedDict from Products.CMFCore.utils import getToolByName try: import Products.LinguaPlone from Products.LinguaPlone.I18NBaseObject import AlreadyTranslated HAS_LINGUAPLONE = True except ImportError: HAS_LINGUAPLONE = False from collective.csv2atvocabularymanager import logger def createVocabulary(portal_vocabularies, base_path, vid, title, description='', type_name='SimpleVocabulary', sortMethod='lexicographic_values', null_values=[], change_master_with_language_id=False): csvpath = os.path.join(base_path, "%s.csv" % vid) if os.path.exists(csvpath): if not hasattr(portal_vocabularies, vid): portal_vocabularies.invokeFactory(id=vid, type_name=type_name, title=title, description=description, sortMethod=sortMethod) logger.info('created vocabulary: %s' % vid) else: logger.info('taken vocabulary: %s' % vid) vocabulary = getattr(portal_vocabularies, vid) vocReader = csv.reader(open(csvpath, 'rb')) firstLine = True for row in vocReader: if firstLine: firstLine = False languages = row[1:] assert len(row)>1 continue assert len(row)== (1 + len(languages)) id = row[0] translations = row[1:] entries = OrderedDict() for x in range(len(languages)): l = languages[x] translation = translations[x] if translation and translation not in null_values: add_language_id = x>0 or change_master_with_language_id entries[l] = _createVocabularyEntry(vocabulary, id, translation, l, add_language_id = add_language_id) master_translation_title = row[1] master_translation = entries.values()[0] if master_translation_title and len(translations)>1: for entry in entries.values(): if master_translation is not entry and entry and HAS_LINGUAPLONE: _setTranslationLink(master_translation, entry) else: logger.error("not found %s.csv" % vid) def _createVocabularyEntry(vocabulary, id, title, lang, add_language_id=False): """Create a new entry with id that is "id-lang", in the right language""" ptool = getToolByName(vocabulary, 'plone_utils') newId = ptool.normalizeString(id) if add_language_id: newId += "-%s" % lang if not hasattr(vocabulary, newId): vocabulary.invokeFactory(id=newId, type_name='SimpleVocabularyTerm', title=title) entry = getattr(vocabulary, newId) entry.setLanguage(lang) entry.reindexObject(idxs=['language']) logger.info('\__ created entry: %s' % newId) else: entry = getattr(vocabulary, newId) return entry def _setTranslationLink(one, two): try: two.addTranslationReference(one) except AlreadyTranslated: logger.info('%s already translated' % two.Title()) return logger.info('\__ set %s as %s translation of %s' % (two.Title(), two.Language(), one.Title())) <file_sep>Introduction ============ .. Note:: **This is not a Plone add-on**. This library is an utility that helps developers to integrate vocabulary done using `ATVocabularyManager`__ to be imported using Generic Setup Python handlers and CSV sources. __ http://plone.org/products/atvocabularymanager/ It also support `LinguaPlone`__ (if present). __ http://plone.org/products/linguaplone How to use ========== Just import the ``createVocabulary`` function and use it:: >>> portal_vocabularies = getToolByName(portal, 'portal_vocabularies') >>> from collective.csv2atvocabularymanager.csv_import import createVocabulary >>> createVocabulary(portal_vocabularies, fs_path, 'my.vocabulary.id', ... "My vocabulary", description='A vocabulary for...') Where: ``portal_vocabularies`` is the ATVocabularyManager tool created after installing it ``fs_path`` is a filesystem path of a folder, where you must put you CSV sources. If the code is called from a ``setuphandlers.py`` script, you can call something like:: >>> os.path.join(os.path.dirname( __file__ ), 'vocabularies') This way the code will look for a "vocabularies" folder inside you project ``vid`` is the vocabulary id that will be created *and* a file with that name and ".csv" extension will be searched inside the ``fs_path`` folder. ``title`` is the title of the vocabulary ``description`` is the description of the vocabulary Also, you have other optional additional parameters: ``type_name`` If the portal_type name of the vocabulary created (default is "SimpleVocabulary") ``sortMethod`` is the sort method of the vocabulary ``null_values`` is a list of possible values that must be used as "null" (can be useful is your CSV is taken from a raw export from SQL database, and strings like "NULL" can be found inside the source). ``change_master_with_language_id`` is a boolean flag used to change the generated vocabulary term id, adding to it the language code suffix. CSV format examples ------------------- A CSV file named "foo.bar.vocabulary.csv" in that format:: "id","en" "item-1","Item one" "item-2","Item two" ... Will create a vocabulary entry with id "foo.bar.vocabulary", with vocabulary terms ids "item-1" and "item-2", ... and titles "Item one", "Item two", ... The header row is required. While the id column's name is not used, that language column name is used to specify the vocabulary term language code (so: normally use the portal default language). You can also import item in different languages:: "id","en","it" "item-1","Item one","Elemento 1" "item-2","Item two","Elemento 2" ... In that way you will create same terms as in previous example, and additional vocabulary terms with ids "item-1-it", "item-2-it", ... and titles "Elemento 1", "Elemento 2", ... You can provide additional languages addim more columns. Just remember to keep the fist language column as the one with portal default language. The real power of language columns will be used if you also install *LinguaPlone*. In that way you will create translations of vocabulary terms. Final notes =========== Please, keep in mind that ATVocabularyManager already support Generic Setup integration for creating vocabularies at install time. However you are foced to use the "*IMS VDEX Vocabulary File*". Please note also that vocabulary implementation from ATVM already provides a ``importCSV`` method. Authors ======= This product was developed by RedTurtle Technology team. .. image:: http://www.redturtle.net/redturtle_banner.png :alt: RedTurtle Technology Site :target: http://www.redturtle.it/ <file_sep># -*- coding: utf-8 -*- import os import unittest from collective.csv2atvocabularymanager.testing import CSV2ATVM_INTEGRATION_TESTING from collective.csv2atvocabularymanager.csv_import import createVocabulary class TestUtility(unittest.TestCase): layer = CSV2ATVM_INTEGRATION_TESTING def test_basic_linguaplone_behavior(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example3', "Foo 3") self.assertEqual(portal.portal_vocabularies.example3.item_1.Title(), "Item one") self.assertEqual(portal.portal_vocabularies.example3.item_1.Language(), "en") self.assertEqual(portal.portal_vocabularies.example3['item_1-it'].Title(), "Elemento unò") self.assertEqual(portal.portal_vocabularies.example3['item_1-it'].Language(), "it") self.assertEqual(portal.portal_vocabularies.example3['item_1-it'].getTranslation().absolute_url(), portal.portal_vocabularies.example3.item_1.absolute_url()) def test_linguaplone_not_translate_master(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example4', "Foo 4") self.assertEqual(portal.portal_vocabularies.example4['item_1-it'].Title(), "Elemento unò") self.assertEqual(portal.portal_vocabularies.example4['item_1-it'].getTranslation(), None) # still, other row with master defined are LinguaPlone linked self.assertEqual(portal.portal_vocabularies.example4['item_2-it'].getTranslation().absolute_url(), portal.portal_vocabularies.example4.item_2.absolute_url()) def test_linguaplone_null_values(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example5', "Foo 5", null_values=['NULL',]) self.assertEqual(portal.portal_vocabularies.example5.objectIds(), ['item_1']) def test_linguaplone_multiple_values(self): portal = self.layer['portal'] portal_vocabularies = portal.portal_vocabularies base_path = os.path.join(os.path.dirname( __file__ ), 'csv') createVocabulary(portal_vocabularies, base_path, 'example6', "Foo 6", null_values=['NULL',]) self.assertEqual(portal.portal_vocabularies.example6['item_1-it'].getTranslationLanguages(), ['en', 'it', 'es']) self.assertEqual(portal.portal_vocabularies.example6['item_1-it'].getTranslation('es').absolute_url(), portal.portal_vocabularies.example6['item_1-es'].absolute_url())
03f5f774ec9242218e0b8a057ccebd594cf7cc43
[ "Python", "reStructuredText" ]
6
Python
RedTurtle/collective.csv2atvocabularymanager
896b0c129b1d6b439e8bb42e49273eaa833778eb
c94b475e0240eb36b1b8cc0981c8da99c7f4aef5
refs/heads/master
<repo_name>owainlewis/rails-error-messages<file_sep>/README.md # Rails error pages Some clean and simple error pages for your Rails applications that look nicer than the defaults. # Previews ![](https://raw.github.com/owainlewis/rails-error-messages/master/previews/phone.png) ![](https://raw.github.com/owainlewis/rails-error-messages/master/previews/400.png) ## Use Just drop them in your public folder to replace the existing error pages. ## The lazy way A quick install script will download them for you if you're on OSX. Be careful sourcing random shell scripts from the web ; ) Make sure you're in the root of your Rails project and run ``` cd public && source <(curl -s https://raw.github.com/owainlewis/rails-error-messages/master/install.sh) ``` <file_sep>/install.sh curl -O https://raw.githubusercontent.com/owainlewis/rails-error-messages/master/light/404.html curl -O https://raw.githubusercontent.com/owainlewis/rails-error-messages/master/light/500.html
e6627d5a0746ee155c0b62f639a8b02d687e8a27
[ "Markdown", "Shell" ]
2
Markdown
owainlewis/rails-error-messages
dee81b621d91dfaf016eb242e9ffe571d0214b33
5eb8f72180c93814b4585dd2fa90a9df8fa03f67
refs/heads/master
<file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using RoomsAndSpacesManagerDesktop.Models.ExcelModels; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Input; namespace RoomsAndSpacesManagerDesktop.ViewModels { class RoomEquipmentsViewModel : ViewModel { public static RoomNameDto RoomName { get; set; } EquipmentDbContext context = new EquipmentDbContext(); MainDbContext roomContext = new MainDbContext(); public RoomEquipmentsViewModel() { if (RoomName != null) { RoomEquipmentsList = CollectionViewSource.GetDefaultView(context.GetEquipments(RoomName)); RoomEquipmentsList.Refresh(); } else { RoomEquipmentsList = CollectionViewSource.GetDefaultView(context.GetAllEquipments()); RoomEquipmentsList.Refresh(); } AddNewRowCommand = new RelayCommand(OnAddNewRowCommandExecuted, CanAddNewRowCommandExecute); SaveChangesCommand = new RelayCommand(OnSaveChangesCommandExecuted, CanSaveChangesCommandExecute); ChangeDataFromExcelCommand = new RelayCommand(OnChangeDataFromExcelCommandExecuted, CanChangeDataFromExcelCommandExecute); DeleteEquipmentCommand = new RelayCommand(OnDeleteEquipmentCommandExecuted, CanDeleteEquipmentCommandExecute); } #region КоллекшенВью для списка оборудования private ICollectionView roomEquipmentsList; public ICollectionView RoomEquipmentsList { get => roomEquipmentsList; set => Set(ref roomEquipmentsList, value); } #endregion #region Комманд. Добавить новую строку public ICommand AddNewRowCommand { get; set; } private void OnAddNewRowCommandExecuted(object obj) { context.AddNewEquipment(RoomName); RoomEquipmentsList = CollectionViewSource.GetDefaultView(context.GetEquipments(RoomName)); RoomEquipmentsList.Refresh(); } private bool CanAddNewRowCommandExecute(object obj) => true; #endregion #region Комманд. Сохранить изменения public ICommand SaveChangesCommand { get; set; } private void OnSaveChangesCommandExecuted(object obj) { context.SaveChanges(); } private bool CanSaveChangesCommandExecute(object obj) => true; #endregion #region Комманд. Заменить данные на данные из Excel public ICommand ChangeDataFromExcelCommand { get; set; } private void OnChangeDataFromExcelCommandExecuted(object obj) { MainExcelModel mainExcelModel = new MainExcelModel(); mainExcelModel.AddToDbFromExcelEqupment(RoomName); RoomEquipmentsList = CollectionViewSource.GetDefaultView(context.GetEquipments(RoomName)); RoomEquipmentsList.Refresh(); } private bool CanChangeDataFromExcelCommandExecute(object obj) => true; #endregion #region Комманд. Удалить строку оборудования public ICommand DeleteEquipmentCommand { get; set; } private void OnDeleteEquipmentCommandExecuted(object obj) { context.RemoveEquipment(obj as RoomEquipmentDto); RoomEquipmentsList = CollectionViewSource.GetDefaultView(context.GetEquipments(RoomName)); RoomEquipmentsList.Refresh(); } private bool CanDeleteEquipmentCommandExecute(object obj) => true; #endregion } } <file_sep>using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using RoomsAndSpacesManagerLib.Models.RevitModels; using RoomsAndSpacesManagerLib.ViewModels; using RoomsAndSpacesManagerLib.Views.Windows; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerLib { [Transaction(TransactionMode.Manual)] public class Cmd : IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; AddParametersIntoSpacies addParametersIntoSpacies = new AddParametersIntoSpacies(); SelectRoomEventHendler evHendSelectRoom = new SelectRoomEventHendler(); ExternalEvent ExEventSelectRoom = ExternalEvent.Create(evHendSelectRoom); ExternalEvent ExEventAddParameters = ExternalEvent.Create(addParametersIntoSpacies); MainWindow mainWindow = new MainWindow(); MainWindowViewModel vm = new MainWindowViewModel(); vm.ApplyEventGetRoomFromRvtModel = ExEventSelectRoom; vm.ApplyEventAddParametersIntoSpacies = ExEventAddParameters; mainWindow.DataContext = vm; mainWindow.Show(); return Result.Succeeded; } } } <file_sep>namespace RoomsAndSpacesManagerDesktop.Migrations { using System; using System.Data.Entity.Migrations; public partial class NewRoomsInSubdiv : DbMigration { public override void Up() { DropForeignKey("dbo.RaSM_SubdivisionDto", "SubdivisionDto_Id", "dbo.RaSM_SubdivisionDto"); DropIndex("dbo.RaSM_SubdivisionDto", new[] { "SubdivisionDto_Id" }); DropColumn("dbo.RaSM_SubdivisionDto", "SubdivisionDto_Id"); } public override void Down() { AddColumn("dbo.RaSM_SubdivisionDto", "SubdivisionDto_Id", c => c.Int()); CreateIndex("dbo.RaSM_SubdivisionDto", "SubdivisionDto_Id"); AddForeignKey("dbo.RaSM_SubdivisionDto", "SubdivisionDto_Id", "dbo.RaSM_SubdivisionDto", "Id"); } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDesktop.Infrastructure.Repositories { class EquipmentRep { private List<EquipmentDto> equipments = new List<EquipmentDto>(); public List<EquipmentDto> Equipments { get { SortMandatoryByFirstPosition(); return equipments; } private set { value = equipments; } } public EquipmentRep() { } public EquipmentRep(List<EquipmentDto> equipmentDtos) { equipments = equipmentDtos; SortMandatoryByFirstPosition(); } public int Count { get { return equipments.Count; } } public void Add(EquipmentDto equipment) { equipments.Add(equipment); SortMandatoryByFirstPosition(); } public void AddRange(List<EquipmentDto> equipments) { equipments.AddRange(equipments); SortMandatoryByFirstPosition(); } public void Remove(EquipmentDto equipment) { equipments.Remove(equipment); SortMandatoryByFirstPosition(); } public List<EquipmentDto> GetEquipments() { SortMandatoryByFirstPosition(); return equipments; } private void SortMandatoryByFirstPosition() { equipments.Sort((x, y) => x.Number.CompareTo(y.Number)); int activeNumber = default; foreach (EquipmentDto eq in equipments) { if (!activeNumber.Equals(eq.Number)) { activeNumber = eq.Number; eq.Currently = true; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace RoomAndSpacesOV.Infrastructure.CustomControls { public class CustomTubItem : TabItem { public CustomTubItem() { Visibility = Visibility.Hidden; } public int ListCount { get { return (int)GetValue(ListCountProperty); } set { SetValue(ListCountProperty, value); if (ListCount != 0) { Background = Brushes.Pink; Visibility = Visibility.Visible; } } } public static readonly DependencyProperty ListCountProperty = DependencyProperty.Register("ListCount", typeof(int), typeof(CustomTubItem), new FrameworkPropertyMetadata(0, new PropertyChangedCallback(PropertyNameChanged))); private static void PropertyNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CustomTubItem)d).ListCount = ((CustomTubItem)d).ListCount; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using Microsoft.VisualBasic.FileIO; using RoomAndSpacesManagerConsole.DbModel; namespace RoomAndSpacesManagerConsole { class Program { static void Main(string[] args) { //AddToRoomNameSubCategoryIdModel addToRoomNameSubCategoryIdModel = new AddToRoomNameSubCategoryIdModel(); //addToRoomNameSubCategoryIdModel.AddOrderCountToSubdivision(); } //public static void RoomInfoToDb() //{ // CsvToDbRooms csvToDbRooms = new CsvToDbRooms(); // csvToDbRooms.AddCats(); // csvToDbRooms.GetSubCatsCsv(); // csvToDbRooms.AddRooms(); //} //public static void ProjectInfoToDb() //{ // AddInfoToDb projCont = new AddInfoToDb(); // projCont.ProjectInfoToDB("Екатеринбург", "ЕКА-ЦКЛ"); //} } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Data.DataBaseContext; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Infrastructure.Repositories; using RoomsAndSpacesManagerDesktop.Models.CsvModels; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using RoomsAndSpacesManagerDesktop.Models.ExcelModels; using RoomsAndSpacesManagerDesktop.Models.SqlModel; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using RoomsAndSpacesManagerDesktop.Views.Windows; namespace RoomsAndSpacesManagerDesktop.ViewModels { class CreateIssueViewModel : ViewModel { #region филды ProjectsDbContext projContext = new ProjectsDbContext(); List<RoomDto> roomDtos; RoomsDbContext roomsContext = new RoomsDbContext(); UploadToCsvModel uploadToCsvModel = new UploadToCsvModel(); List<RoomNameDto> roomsNamesList; #endregion public CreateIssueViewModel() { allRoomNames = roomsContext.GetAllRoomNames(); Projects = projContext.GetProjects(); Categories = roomsContext.GetCategories(); #region Команды PushToDbCommand = new RelayCommand(OnPushToDbCommandExecutde, CanPushToDbCommandExecute); UploadProgramToExcelCommand = new RelayCommand(OnUploadProgramToExcelCommandExecutde, CanUploadProgramToExcelCommandExecute); UploadStandartEquipmentToExcelCommand = new RelayCommand(OnUploadStandartEquipmentToExcelCommandExecutde, CanUploadStandartEquipmentToExcelCommandExecute); AddNewRowCommand = new RelayCommand(OnAddNewRowCommandExecutde, CanAddNewRowCommandExecute); AddNewProjectCommand = new RelayCommand(OnAddNewProjectCommandExecutde, CanAddNewProjectCommandExecute); AddNewBuildingCommand = new RelayCommand(OnAddNewBuildingCommandExecutde, CanAddNewBuildingCommandExecute); DeleteCommand = new RelayCommand(OnDeleteCommandExecutde, CanDeleteCommandExecute); DeleteIssueCommand = new RelayCommand(OnDeleteIssueCommandExecutde, CanDeleteIssueCommandExecute); SetDefaultValueCommand = new RelayCommand(OnSetDefaultValueCommandExecutde, CanSetDefaultValueCommandExecute); AddNewSubdivisionCommand = new RelayCommand(OnAddNewSubdivisionCommandExecutde, CanAddNewSubdivisionCommandExecute); RenderComboboxCommand = new RelayCommand(OnRenderComboboxCommandExecutde, CanRenderComboboxCommandExecute); LoadedCommand = new RelayCommand(OnLoadedCommandExecutde, CanLoadedCommandExecute); CopySubdivisionCommnd = new RelayCommand(OnCopySubdivisionCommndExecutde, CanCopySubdivisionCommndExecute); LoadedSummuryCommand = new RelayCommand(OnLoadedSummuryCommandExecutde, CanLoadedSummuryCommandExecute); UploadProgramToCsv = new RelayCommand(OnUploadProgramToCsvExecutde, CanUploadProgramToCsvExecute); ClearTextboxCommand = new RelayCommand(OnClearTextboxCommandExecuted, CanClearTextboxCommandExecute); GetEquipmentCommand = new RelayCommand(OnGetEquipmentCommandExecutde, CanGetEquipmentCommandExecute); PushToDbSaveChangesCommand = new RelayCommand(OnPushToDbSaveChangesCommandExecutde, CanPushToDbSaveChangesCommandExecute); UploadAllEquipmentToExcelCommand = new RelayCommand(OnUploadAllEquipmentToExcelCommandExecuted, CanUploadAllEquipmentToExcelCommandExecute); RenameSubdivisionCommand = new RelayCommand(OnRenameSubdivisionCommandExecuted); RenameBuildingCommand = new RelayCommand(OnRenameBuildingCommandExecuted); ProjectSettingsCommand = new RelayCommand(OnProjectSettingsCommandExecuted, CanProjectSettingsCommandExecute); #endregion } /*MainWindow~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Команда рендера окна public ICommand LoadedCommand { get; set; } private void OnLoadedCommandExecutde(object obj) { if (SelectedSubdivision != null) { roomDtos = projContext.GetRooms(SelectedSubdivision); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } } private bool CanLoadedCommandExecute(object obj) => true; #endregion /*Создание нового проекта и здания~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Имена новых проекта и здания private string newProjectName; public string NewProjectName { get => newProjectName; set => Set(ref newProjectName, value); } private string newBuildingName; public string NewBuildingName { get => newBuildingName; set => Set(ref newBuildingName, value); } private string newSubdivisionName; public string NewSubdivisionName { get => newSubdivisionName; set => Set(ref newSubdivisionName, value); } #endregion #region СелектедПроджект для добавления новых проектов private ProjectDto selectedProjectForAdd; public ProjectDto SelectedProjectForAdd { get { return selectedProjectForAdd; } set { selectedProjectForAdd = value; } } #endregion /*Верхняя панель. Список проектов и зданий~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Список проектов. Выбранный проект private List<ProjectDto> projects; /// <summary> Список проектов. Из БД </summary> public List<ProjectDto> Projects { get => projects; set => Set(ref projects, value); } private ProjectDto selectedProject; public ProjectDto SelectedProject { get { return selectedProject; } set { selectedProject = value; if (SelectedProject != null) { if (SelectedProject.Buildings != null) Buildings = projContext.GetModels(SelectedProject); AllRooms = projContext.GetAllRoomsByProject(SelectedProject).OrderBy(x => x.Subdivision.BuildingId).ToList(); } else { Buildings = new List<BuildingDto>(); } OnLoadedSummuryCommandExecutde(""); } } #endregion #region Список зданий. Выбранное здание private List<BuildingDto> buildings; /// <summary> Список проектов. Из БД </summary> public List<BuildingDto> Buildings { get => buildings; set => Set(ref buildings, value); } private BuildingDto selectedBuilding; public BuildingDto SelectedBuilding { get { return selectedBuilding; } set { selectedBuilding = value; if (SelectedBuilding != null) { if (SelectedBuilding.Subdivisions != null) Subdivisions = projContext.GetSubdivisions(SelectedBuilding); } else Subdivisions = null; } } #endregion #region Список подразделений. Выбранное подразделение private List<SubdivisionDto> subdivisions; /// <summary> Список проектов. Из БД </summary> public List<SubdivisionDto> Subdivisions { get => subdivisions; set => Set(ref subdivisions, value); } private SubdivisionDto selectedSubdivision; public SubdivisionDto SelectedSubdivision { get { return selectedSubdivision; } set { selectedSubdivision = value; if (SelectedSubdivision != null) { roomDtos = projContext.GetRooms(SelectedSubdivision); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } else Rooms = null; } } #endregion #region Комманда. Создать новый проект public ICommand AddNewProjectCommand { get; set; } private void OnAddNewProjectCommandExecutde(object p) { projContext.AddNewProjects(new ProjectDto() { Name = NewProjectName }); Projects = projContext.GetProjects(); NewProjectName = string.Empty; if (Buildings != null && Buildings.Count != 0) { Buildings.Clear(); OnPropertyChanged(nameof(Buildings)); } } private bool CanAddNewProjectCommandExecute(object p) => true; #endregion #region Комманда. Создать новую модель public ICommand AddNewBuildingCommand { get; set; } private void OnAddNewBuildingCommandExecutde(object p) { if (p != null) { projContext.AddNewBuilding(new BuildingDto() { ProjectId = (p as ProjectDto).Id, Name = NewBuildingName }); Buildings = projContext.GetModels(p as ProjectDto); } NewBuildingName = string.Empty; } private bool CanAddNewBuildingCommandExecute(object p) { if (p != null) { return true; } else { return false; } } #endregion #region Комманда. Создать новое подразделение public ICommand AddNewSubdivisionCommand { get; set; } private void OnAddNewSubdivisionCommandExecutde(object p) { if (p != null) { int nextOrder; if ((p as BuildingDto).Subdivisions != null && (p as BuildingDto).Subdivisions.Count != 0) nextOrder = (p as BuildingDto).Subdivisions.Select(x => x.Order).Max() + 1; else nextOrder = 1; projContext.AddNewSubdivision(new SubdivisionDto() { BuildingId = (p as BuildingDto).Id, Name = NewSubdivisionName, Order = nextOrder }); Subdivisions = projContext.GetSubdivisions(p as BuildingDto); } NewBuildingName = string.Empty; } private bool CanAddNewSubdivisionCommandExecute(object p) { if (p != null) { return true; } else { return false; } } #endregion #region Комманда удаления проектов и зданий public ICommand DeleteCommand { get; set; } private void OnDeleteCommandExecutde(object p) { if (p is ProjectDto) { projContext.RemoveProject(p as ProjectDto); Projects = projContext.GetProjects(); } if (p is BuildingDto) { projContext.RemoveBuilding(p as BuildingDto); Buildings = projContext.GetModels(SelectedProject); } if (p is SubdivisionDto) { projContext.RemoveSubDivision(p as SubdivisionDto); Subdivisions = projContext.GetSubdivisions(SelectedBuilding); } } private bool CanDeleteCommandExecute(object p) => true; #endregion #region Комманд. Открыть окно настроек для проектов public ICommand ProjectSettingsCommand { get; set; } private void OnProjectSettingsCommandExecuted(object obj) { ProjectSettingsWindow projectSettingsWindow = new ProjectSettingsWindow(); ProjectSettingsViewModel projectSettingsViewModel = new ProjectSettingsViewModel(Subdivisions, ref projContext, projectSettingsWindow); projectSettingsWindow.DataContext = projectSettingsViewModel; projectSettingsWindow.ShowDialog(); if (SelectedBuilding != null) { if (SelectedBuilding.Subdivisions != null) Subdivisions = projContext.GetSubdivisions(SelectedBuilding); } else Subdivisions = null; } private bool CanProjectSettingsCommandExecute(object obj) => true; #endregion #region Комманд. Переименвоание подразделений public ICommand RenameSubdivisionCommand { get; set; } private void OnRenameSubdivisionCommandExecuted(object obj) { var renamedSubdivision = obj as SubdivisionDto; if (renamedSubdivision.IsReadOnly) { projContext.SaveChanges(); } if (renamedSubdivision.IsReadOnly) renamedSubdivision.IsReadOnly = false; else renamedSubdivision.IsReadOnly = true; } #endregion #region Комманд. Переименвоание зданий public ICommand RenameBuildingCommand { get; set; } private void OnRenameBuildingCommandExecuted(object obj) { var renamedSubdivision = obj as BuildingDto; if (renamedSubdivision.IsReadOnly) { projContext.SaveChanges(); } if (renamedSubdivision.IsReadOnly) renamedSubdivision.IsReadOnly = false; else renamedSubdivision.IsReadOnly = true; } #endregion /*Верхняя панель. Список категорий~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Combobox - Список категорий private List<CategoryDto> categories; public List<CategoryDto> Categories { get { return categories; } set { categories = value; } } private CategoryDto selectedCategoties; /// <summary> /// Выбранная категория помещений /// </summary> public CategoryDto SelectedCategoties { get { return selectedCategoties; } set { Set(ref selectedCategoties, value); SubCategories = roomsContext.GetSubCategotyes(SelectedCategoties); } } #endregion #region Combobox - список подкатегорий private List<SubCategoryDto> subCategories; public List<SubCategoryDto> SubCategories { get { return subCategories; } set { Set(ref subCategories, value); } } private SubCategoryDto selectedSubCategoties; /// <summary> /// Выбранная подкатегория помещений /// </summary> public SubCategoryDto SelectedSubCategoties { get { return selectedSubCategoties; } set { selectedSubCategoties = value; } } #endregion #region Список исходных помещений List<RoomNameDto> allRoomNames { get; set; } private ICollectionView roomsNames; public ICollectionView RoomsNames { get => roomsNames; set => Set(ref roomsNames, value); } private RoomNameDto selectedRoomName; public RoomNameDto SelectedRoomName { get { return selectedRoomName; } set { selectedRoomName = value; AddRoomInfo(); EquipmentDbContext equipmentDbContext = new EquipmentDbContext(); if (SelectedRoom.Id != 0) { equipmentDbContext.RemoveAllEquipment(SelectedRoom); equipmentDbContext.CopyRoomNameEquipmentsToRoomIssue(SelectedRoomName, SelectedRoom); //#region Сортировка списка. Чтобы были только первые позиции в списке //List<EquipmentDto> equpmets = equipmentDbContext.GetEquipments(SelectedRoomName) // .Where(x => x.RoomNameId == SelectedRoomName.Id) // .Select(x => new EquipmentDto(x) { RoomId = SelectedRoom.Id, Mandatory = x.Mandatory, Currently = false }) // .ToList(); //EquipmentRep equipments = new EquipmentRep(equpmets); ////equpmets.Sort((x, y) => x.Number.CompareTo(y.Number)); ////int activeNumber = default; ////foreach (EquipmentDto eq in equpmets) ////{ //// if (!activeNumber.Equals(eq.Number)) //// { //// activeNumber = eq.Number; //// eq.Mandatory = true; //// } ////} //#endregion ////List<EquipmentDto> equipment = equipmentDbContext.GetEquipmentsWithSortItems(SelectedRoomName); //var eee = equipments.GetEquipments(); } selectedRoomName = null; } } private void AddRoomInfo() { SelectedRoom.RoomNameId = SelectedRoomName.Id; SelectedRoom.Min_area = SelectedRoomName.Min_area; SelectedRoom.Class_chistoti_GMP = SelectedRoomName.Class_chistoti_GMP; SelectedRoom.Class_chistoti_SanPin = SelectedRoomName.Class_chistoti_SanPin; SelectedRoom.Class_chistoti_SP_158 = SelectedRoomName.Class_chistoti_SP_158; SelectedRoom.T_calc = SelectedRoomName.T_calc; SelectedRoom.T_max = SelectedRoomName.T_max; SelectedRoom.T_min = SelectedRoomName.T_min; SelectedRoom.Pritok = SelectedRoomName.Pritok; SelectedRoom.Vityazhka = SelectedRoomName.Vityazhka; SelectedRoom.Ot_vlazhnost = SelectedRoomName.Ot_vlazhnost; SelectedRoom.KEO_est_osv = SelectedRoomName.KEO_est_osv; SelectedRoom.KEO_sovm_osv = SelectedRoomName.KEO_sovm_osv; SelectedRoom.Discription_OV = SelectedRoomName.Discription_OV; SelectedRoom.Osveshennost_pro_obshem_osvech = SelectedRoomName.Osveshennost_pro_obshem_osvech; SelectedRoom.Group_el_bez = SelectedRoomName.Group_el_bez; SelectedRoom.Discription_EOM = SelectedRoomName.Discription_EOM; SelectedRoom.Discription_AR = SelectedRoomName.Discription_AR; SelectedRoom.Equipment_VK = SelectedRoomName.Equipment_VK; SelectedRoom.Discription_SS = SelectedRoomName.Discription_SS; SelectedRoom.Discription_AK_ATH = SelectedRoomName.Discription_AK_ATH; SelectedRoom.Discription_GSV = SelectedRoomName.Discription_GSV; SelectedRoom.Discription_HS = SelectedRoomName.Discription_HS; } #region Флаг разворачивания Comboboxa private bool isDropDownOpen; public bool IsDropDownOpen { get { return isDropDownOpen; } set { Set(ref isDropDownOpen, value); } } #endregion #endregion #region Комманда при отрисовке комбобокса private ICommand renderComboboxCommand; public ICommand RenderComboboxCommand { get => renderComboboxCommand; set => renderComboboxCommand = value; } private void OnRenderComboboxCommandExecutde(object p) { if (p != null) { roomsNamesList = RoomsPropertiesViewModel.roomsContext.GetRoomNames(p as SubCategoryDto); RoomsNames = CollectionViewSource.GetDefaultView(roomsNamesList); RoomsNames.Refresh(); } if (RoomNameFiltering != "") { RoomsNames = CollectionViewSource.GetDefaultView(allRoomNames); RoomsNames.Filter = delegate (object item) { RoomNameDto user = item as RoomNameDto; if (user != null && user.Name != null && user.Name.ToLower().StartsWith(RoomNameFiltering.ToLower())) return true; return false; }; RoomsNames.Refresh(); } } private bool CanRenderComboboxCommandExecute(object p) => true; #endregion #region Строки фильтрации помещений private string roomNameFiltering = ""; public string RoomNameFiltering { get { return roomNameFiltering; } set { roomNameFiltering = value; if (RoomNameFiltering != "") { IsDropDownOpen = true; } else { IsDropDownOpen = false; } CollectionViewSource.GetDefaultView(allRoomNames).Refresh(); } } private bool UserFilter(object item) { if (String.IsNullOrEmpty(RoomNameFiltering)) return true; else return ((item as RoomNameDto).Name.IndexOf(RoomNameFiltering, StringComparison.OrdinalIgnoreCase) >= 0); } #endregion #region Анлоадед текстбокс public ICommand ClearTextboxCommand { get; set; } private void OnClearTextboxCommandExecuted(object obj) { RoomNameFiltering = ""; } private bool CanClearTextboxCommandExecute(object obj) => true; #endregion /*Центральная панель. Список проектов и зданий~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Список помещений. Выбранное помещение private ICollectionView rooms; public ICollectionView Rooms { get => rooms; set => Set(ref rooms, value); } private static RoomDto selectedRoom; public static RoomDto SelectedRoom { get => selectedRoom; set { selectedRoom = value; } } #endregion #region Филтер. По Id //private string idFilter; //public string IdFilter //{ // get { return idFilter; } // set // { // idFilter = value; // } //} #endregion #region Перенос помещения из одного подразделения в другое private SubdivisionDto selectedSubdivisionAction; public SubdivisionDto SelectedSubdivisionAction { get { return selectedSubdivisionAction; } set { selectedSubdivisionAction = value; if (SelectedSubdivisionAction != null) { SelectedRoom.Subdivision = SelectedSubdivisionAction; SelectedRoom.SubdivisionId = SelectedSubdivisionAction.Id; projContext.SaveChanges(); roomDtos = projContext.GetRooms(SelectedSubdivision); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); SelectedSubdivisionAction = null; } } } #endregion #region Комманд. Удаление строк из списка public ICommand DeleteIssueCommand { get; set; } private void OnDeleteIssueCommandExecutde(object p) { if ((p as RoomDto).Id == default) { roomDtos.Remove(p as RoomDto); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } else { projContext.RemoveRoom(p as RoomDto); roomDtos = projContext.GetRooms(SelectedSubdivision); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } } private bool CanDeleteIssueCommandExecute(object p) => true; #endregion #region Комманд. Получить значение по умолчанию по выбранной строке public ICommand SetDefaultValueCommand { get; set; } private void OnSetDefaultValueCommandExecutde(object p) { RoomDto room = p as RoomDto; if (room.Name != null) { room.RoomNameId = room.RoomName.Id; room.Min_area = room.RoomName.Min_area; room.Class_chistoti_GMP = room.RoomName.Class_chistoti_GMP; room.Class_chistoti_SanPin = room.RoomName.Class_chistoti_SanPin; room.Class_chistoti_SP_158 = room.RoomName.Class_chistoti_SP_158; room.T_calc = room.RoomName.T_calc; room.T_max = room.RoomName.T_max; room.T_min = room.RoomName.T_min; room.Pritok = room.RoomName.Pritok; room.Vityazhka = room.RoomName.Vityazhka; room.Ot_vlazhnost = room.RoomName.Ot_vlazhnost; room.KEO_est_osv = room.RoomName.KEO_est_osv; room.KEO_sovm_osv = room.RoomName.KEO_sovm_osv; room.Discription_OV = room.RoomName.Discription_OV; room.Osveshennost_pro_obshem_osvech = room.RoomName.Osveshennost_pro_obshem_osvech; room.Group_el_bez = room.RoomName.Group_el_bez; room.Discription_EOM = room.RoomName.Discription_EOM; room.Discription_AR = room.RoomName.Discription_AR; room.Equipment_VK = room.RoomName.Equipment_VK; room.Discription_SS = room.RoomName.Discription_SS; room.Discription_AK_ATH = room.RoomName.Discription_AK_ATH; room.Discription_GSV = room.RoomName.Discription_GSV; room.Discription_HS = room.RoomName.Discription_HS; Rooms = CollectionViewSource.GetDefaultView(roomDtos); } //Rooms.Refresh(); } private bool CanSetDefaultValueCommandExecute(object p) => true; #endregion #region Комманд. Открыть окно с оборудованием public ICommand GetEquipmentCommand { get; set; } private void OnGetEquipmentCommandExecutde(object p) { EquipmentsViewModel.Room = SelectedRoom; EquipmentsWindow equipmentsWindow = new EquipmentsWindow(); EquipmentsViewModel vm = new EquipmentsViewModel(); equipmentsWindow.DataContext = vm; equipmentsWindow.ShowDialog(); } private bool CanGetEquipmentCommandExecute(object p) => true; #endregion /*Нижняя панель. Интерфейс добавления строки и синхронизации с БД~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Добавить новую строку комнаты с Айдишником здания public ICommand AddNewRowCommand { get; set; } /// <summary> /// Метод. Добавть новую строку /// </summary> /// <param name="p"></param> private void OnAddNewRowCommandExecutde(object p) { if (SelectedBuilding != null) { roomDtos.Add(new RoomDto() { SubdivisionId = SelectedSubdivision.Id }); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } } private bool CanAddNewRowCommandExecute(object p) { if (SelectedSubdivision == null) return false; else return true; } #endregion #region Копировать подразделение из другого здания public ICommand CopySubdivisionCommnd { get; set; } public static List<SubdivisionDto> CopySubdivisionList { get; set; } /// <summary> /// Метод. Добавть новую строку /// </summary> /// <param name="p"></param> private void OnCopySubdivisionCommndExecutde(object p) { CopySubDivisionViewModel.projContext = projContext; CopySubDivisionViewModel.selectedBuildingId = SelectedBuilding.Id; CopySubDivisionViewModel.Building = SelectedBuilding; CopySubdivisionWindow copySubdivisionWindow = new CopySubdivisionWindow(); CopySubDivisionViewModel copySubDivisionViewModel = new CopySubDivisionViewModel(); copySubDivisionViewModel.copySubdivisionWindow = copySubdivisionWindow; copySubdivisionWindow.DataContext = copySubDivisionViewModel; copySubdivisionWindow.ShowDialog(); Subdivisions = projContext.GetSubdivisions(SelectedBuilding); } private bool CanCopySubdivisionCommndExecute(object p) { if (SelectedBuilding == null) return false; return true; } #endregion #region Комманд. Закинуть обновления пространств в БД public ICommand PushToDbCommand { get; set; } private void OnPushToDbCommandExecutde(object p) { if (roomDtos != null) { projContext.AddNewRooms(roomDtos); projContext.SaveChanges(); roomDtos = projContext.GetRooms(SelectedSubdivision); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); MessageBox.Show("Данные успешно загруженны в базу данных", "Статус"); } else { MessageBox.Show("Ошибка! Нет выбранных помещений", "Статус"); } } private bool CanPushToDbCommandExecute(object p) { return true; } #endregion #region Комманд. Выгрузить программу в эксель public ICommand UploadProgramToExcelCommand { get; set; } private void OnUploadProgramToExcelCommandExecutde(object p) { MainExcelModel.UploadProgramToExcel(projContext.GetRooms(SelectedSubdivision)); } private bool CanUploadProgramToExcelCommandExecute(object p) { if (SelectedSubdivision != null) return true; return false; } #endregion #region Комманд. Выгрузить стандарт список оборудвания в эксель public ICommand UploadStandartEquipmentToExcelCommand { get; set; } private void OnUploadStandartEquipmentToExcelCommandExecutde(object p) { //SqlMainModel.GetEqupmentByProjects(SelectedProject); SqlMainModel.GetStandartEquipmnetByProject(SelectedProject); } private bool CanUploadStandartEquipmentToExcelCommandExecute(object p) { if (SelectedProject != null) return true; return false; } #endregion #region Комманд. Выгрузить список оборудования целиком в эксель public ICommand UploadAllEquipmentToExcelCommand { get; set; } private void OnUploadAllEquipmentToExcelCommandExecuted(object obj) { SqlMainModel.GetAllEquipmnetByProject(SelectedProject); } private bool CanUploadAllEquipmentToExcelCommandExecute(object obj) { if (SelectedProject != null) return true; return false; } #endregion /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*ViewModel для таблицы "Программа помещений"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Список помещений для целого проекта с сортировкой. Помещения получаются при выборе проекта. private List<RoomDto> allRooms; public List<RoomDto> AllRooms { get { return allRooms; } set { Set(ref allRooms, value); } } #endregion #region Комманд. Сохранить изменения в номерах помещений public ICommand PushToDbSaveChangesCommand { get; set; } private void OnPushToDbSaveChangesCommandExecutde(object obj) { projContext.SaveChanges(); } private bool CanPushToDbSaveChangesCommandExecute(object obj) { if (AllRooms != null && AllRooms.Count != 0) return true; else return false; } #endregion /*Таблица "Сводная"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Список всех помещений для проекта private List<BuildingDto> _summury; public List<BuildingDto> _Summury { get => _summury; set => _summury = value; } private ICollectionView summury; public ICollectionView Summury { get => summury; set => Set(ref summury, value); } #endregion #region Комманд. Загрузка окна Summury private List<BuildingDto> buildList; public ICommand LoadedSummuryCommand { get; set; } private void OnLoadedSummuryCommandExecutde(object obj) { int? sss = 0; if (SelectedProject != null) { buildList = projContext.GetModels(SelectedProject); foreach (var build in buildList) { int? summAreaBuild = 0; foreach (var subDiv in build.Subdivisions) { int? summAreaSubdiv = 0; foreach (var room in subDiv.Rooms) { if (room.Min_area != null) { int i; int.TryParse(room.Min_area, out i); summAreaSubdiv += i; } } subDiv.SunnuryArea = summAreaSubdiv; summAreaBuild += summAreaSubdiv; } build.SunnuryArea = summAreaBuild; sss += summAreaBuild; } Summury = CollectionViewSource.GetDefaultView(buildList); Summury.Refresh(); SummuryArea = sss; } } private bool CanLoadedSummuryCommandExecute(object obj) => false; #endregion #region Итоговая площадь private int? summuryArea; public int? SummuryArea { get { return summuryArea; } set { Set(ref summuryArea, value); } } #endregion #region Комманд. Выгрузка в Excel public ICommand UploadProgramToCsv { get; set; } private void OnUploadProgramToCsvExecutde(object obj) { try { UploadToCsvModel UploadToCsvModel = new UploadToCsvModel(SelectedProject, buildList, Koef); UploadToCsvModel.UploadToExcel(); //uploadToCsvModel.UploadRoomProgramToExcel(SelectedProject); //uploadToCsvModel.UploadRoomSummaryToExcel(buildList); MessageBox.Show("Выгрузка завершена", "Статус"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка"); } } private bool CanUploadProgramToCsvExecute(object obj) => true; #endregion #region Коэффициент умножения площади private double koef = 2.5; public double Koef { get { return koef; } set { koef = value; } } #endregion /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ } }<file_sep>using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interactivity; using System.Windows.Media; namespace RoomsAndSpacesManagerDesktop.Infrastructure.Behaviors { public class DataGridCellColorBehavior : Behavior<DataGridCell> { protected override void OnAttached() { base.OnAttached(); } protected override void OnDetaching() { base.OnDetaching(); } } } <file_sep>namespace RoomsAndSpacesManagerDesktop.Migrations { using System; using System.Data.Entity.Migrations; public partial class addnewfieldinEquipment : DbMigration { public override void Up() { AddColumn("dbo.RaSM_Equipments", "Currently", c => c.Boolean(nullable: false)); } public override void Down() { DropColumn("dbo.RaSM_Equipments", "Currently"); } } } <file_sep>using Microsoft.VisualBasic.FileIO; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesManagerConsole { class AddInfoToDb { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); public void ProjectInfoToDB(string ProjectName, string BuildingName) { //Добавление проекта roomAndSpacesDbContext.RaSM_Projects.Add(new ProjectDto() { Name = ProjectName }); roomAndSpacesDbContext.SaveChanges(); //Добавление здания roomAndSpacesDbContext.RaSM_Buildings.Add(new BuildingDto() { Name = BuildingName, ProjectId = roomAndSpacesDbContext.RaSM_Projects.FirstOrDefault(x => x.Name == ProjectName).Id }); roomAndSpacesDbContext.SaveChanges(); using (TextFieldParser parser = new TextFieldParser(@"C:\Users\ya.goreglyad\Desktop\ЕКА-ЦКЛ Задание ТХ - Общий.csv")) { List<RoomDto> roomDtos = new List<RoomDto>(); parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); var straintname = fields[2]; var id = roomAndSpacesDbContext.RaSM_RoomNames.FirstOrDefault(x => x.Name == straintname)?.Id; var ddd = new RoomDto() { //BuildingId = roomAndSpacesDbContext.RaSM_Buildings.FirstOrDefault(x => x.Name == BuildingName).Id, RoomNumber = fields[1], //Name = fields[2], ShortName = fields[3], Min_area = fields[4], //Count = Convert.ToInt32(fields[5]), //Summary_Area = Convert.ToInt32(fields[6]), Rab_mesta_posetiteli = fields[7], Categoty_pizharoopasnosti = fields[8], Class_chistoti_SanPin = fields[9], Class_chistoti_SP_158 = fields[10], Class_chistoti_GMP = fields[11], Discription_AR = fields[12], T_calc = fields[13], T_min = fields[14], T_max = fields[15], Pritok = fields[16], Vityazhka = fields[17], Ot_vlazhnost = fields[18], Discription_OV = fields[19], Equipment_VK = fields[20], KEO_est_osv = fields[21], KEO_sovm_osv = fields[22], Osveshennost_pro_obshem_osvech = fields[23], El_Nagruzka = fields[24], Group_el_bez = fields[25], Discription_EOM = fields[26], Discription_SS = fields[27], Discription_AK_ATH = fields[28], Nagruzki_na_perekririe = fields[29], Discription_GSV = fields[30], Discription_HS = fields[31], }; if (id != null) ddd.RoomNameId = Convert.ToInt32(id); roomDtos.Add(ddd); } roomAndSpacesDbContext.RaSM_Rooms.AddRange(roomDtos.Where(x => x.Name != null)); roomAndSpacesDbContext.SaveChanges(); } } } } <file_sep>using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesOV.Models.DbModels { public static class MainDbModel { private static RoomAndSpacesDbContext context; static MainDbModel() { context = new RoomAndSpacesDbContext(); } public static List<ProjectDto> GetProjects() { return context.RaSM_Projects.ToList(); } public static List<BuildingDto> GetBuildingsByProject(ProjectDto project) { return context.RaSM_Buildings.Where(x => x.ProjectId == project.Id).ToList(); } public static List<RoomDto> GetRoomsByBuilding(BuildingDto building) { List<RoomDto> rooms = new List<RoomDto>(); foreach (SubdivisionDto subdiv in building.Subdivisions) { rooms.AddRange(subdiv.Rooms); } return rooms; } } } <file_sep>using RoomsAndSpacesManagerDesktop.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace RoomsAndSpacesManagerDesktop.Views.Windows { /// <summary> /// Логика взаимодействия для Window1.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); CreateIssueViewModel createIssueViewModel = new CreateIssueViewModel(); CreateIssue.DataContext = createIssueViewModel; ArTub.DataContext = createIssueViewModel; VkTab.DataContext = createIssueViewModel; MgtgTab.DataContext = createIssueViewModel; KrTab.DataContext = createIssueViewModel; OvTab.DataContext = createIssueViewModel; EomTab.DataContext = createIssueViewModel; SsTab.DataContext = createIssueViewModel; HsTab.DataContext = createIssueViewModel; RoomProgramm.DataContext = createIssueViewModel; Summury.DataContext = createIssueViewModel; } } } <file_sep>using Autodesk.Revit.DB; using RoomAndSpacesOV.Dto; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesOV.Models.RvtHelper { class MainModelRvtHelper { public ParameterDto SetPropertt(string paramName, string dtoProp, Element item, RoomDto roomDto) { Parameter param = item.LookupParameter(paramName); if (param != null) { string storageType = param.StorageType.ToString(); if (storageType.ToString() == "String") { string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); if (propValue == null) propValue = ""; if (param.AsString() != propValue) { ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = propValue; parameterDto.OldValue = param.AsString(); param?.Set(propValue); return parameterDto; } } if (storageType.ToString() == "Integer") { string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); int value; if (!int.TryParse(propValue, out value)) value = 0; if (propValue == null | propValue == "") value = 0; if (param.AsInteger() == value) return null; ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = value.ToString(); parameterDto.OldValue = param.AsInteger().ToString(); param?.Set(value); return parameterDto; } if (storageType.ToString() == "Double") { double value; string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); if (!double.TryParse(propValue, out value)) value = 0; if (propValue == null | propValue == "") value = 0; if (param.AsDouble() != value && param.AsDouble() != UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS) && param.AsDouble() != UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_CELSIUS)) { ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = value.ToString(); parameterDto.OldValue = param.AsDouble().ToString(); if (param.DisplayUnitType == DisplayUnitType.DUT_SQUARE_METERS) value = UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS); if (param.DisplayUnitType == DisplayUnitType.DUT_CELSIUS) value = UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_CELSIUS); param?.Set(value); return parameterDto; } } } return null; } } } <file_sep>using Autodesk.Revit.DB; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerLib.Dto; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerLib.Models.RevitHelper { class RevitHelperModel { public static ParameterDto SetProperty(string paramName, string dtoProp, Element item, RoomDto roomDto) { Parameter param = item.LookupParameter(paramName); if (param != null) { string storageType = param.StorageType.ToString(); if (storageType.ToString() == "String") { string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); if (param.AsString() != propValue) { ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = propValue; parameterDto.OldValue = param.AsString(); param?.Set(propValue); return parameterDto; } } if (storageType.ToString() == "Integer") { string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); if (propValue == null) return null; int value; if (!int.TryParse(propValue, out value)) return null; if (param.AsInteger() != value) { ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = propValue.ToString(); parameterDto.OldValue = param.AsInteger().ToString(); param?.Set(value); return parameterDto; } } if (storageType.ToString() == "Double") { double value; string propValue = roomDto.GetType().GetProperty(dtoProp)?.GetValue(roomDto)?.ToString(); if (propValue == null) return null; if (!double.TryParse(propValue, out value)) return null; if (param.AsDouble() != value & param.AsDouble() != UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS)) { ParameterDto parameterDto = new ParameterDto(); parameterDto.Name = paramName; parameterDto.NewValue = value.ToString(); parameterDto.OldValue = param.AsDouble().ToString(); if (param.DisplayUnitType == DisplayUnitType.DUT_SQUARE_METERS) value = UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS); param?.Set(value); return parameterDto; } } } return null; } } } <file_sep>using Autodesk.Revit.DB; using Autodesk.Revit.UI; using RoomAndSpacesOV.Dto; using RoomAndSpacesOV.Infrastructure; using RoomAndSpacesOV.Models.DbModels; using RoomAndSpacesOV.Models.RvtModels; using RoomAndSpacesOV.ViewModels.Base; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Input; namespace RoomAndSpacesOV.ViewModels { class MainWindowViewModel : ViewModel { public static List<SpaceDto> SpaciesList { get; set; } public static List<RoomDto> UnfoundedRooms { get; set; } public ExternalEvent AddParamtersToModelExEvent { get; set; } public MainWindowViewModel() { Projects = MainDbModel.GetProjects(); AddParametersCommand = new RelayCommand(OnAddParametersCommandExecuted, CanAddParametersCommandExecure); AddParametersToModelEvHend.ChangeUI += ViewChangedSpaciesList; } #region Список измененых помещений. Метод отображение измененных помезений private ICollectionView spacesList; public ICollectionView SpacesList { get => spacesList; set => Set(ref spacesList, value); } private void ViewChangedSpaciesList(object obj) { SpacesList = CollectionViewSource.GetDefaultView(SpaciesList); SpacesList.Refresh(); if (UnfoundedRooms != null & UnfoundedRooms.Count != 0) { UnfoundedRoomsList = CollectionViewSource.GetDefaultView(UnfoundedRooms); UnfoundedRoomsList.Refresh(); ListCount = UnfoundedRooms.Count; } } #endregion #region Список проектов. Выбранный проект public List<ProjectDto> Projects { get; set; } private ProjectDto selectedProject; public ProjectDto SelectedProject { get => selectedProject; set { selectedProject = value; if (SelectedProject != null) Buildings = MainDbModel.GetBuildingsByProject(SelectedProject); } } #endregion #region Список зданий. Выбранное здание private List<BuildingDto> buildings; public List<BuildingDto> Buildings { get { return buildings; } set { Set(ref buildings, value); } } private BuildingDto selectedBuilding; public BuildingDto SelectedBuilding { get { return selectedBuilding; } set { selectedBuilding = value; } } #endregion #region Комманд. Заполнить параметры public ICommand AddParametersCommand { get; set; } private void OnAddParametersCommandExecuted(object obj) { try { AddParametersToModelEvHend.RoomsDto = MainDbModel.GetRoomsByBuilding(SelectedBuilding); } catch (Exception ex) { throw ex; } AddParamtersToModelExEvent.Raise(); } private bool CanAddParametersCommandExecure(object obj) { if (SelectedBuilding == null) return false; return true; } #endregion #region Список отсутсвующиз помещений private ICollectionView unfoundedRoomsList; public ICollectionView UnfoundedRoomsList { get => unfoundedRoomsList; set => Set( ref unfoundedRoomsList, value); } private int listCount; public int ListCount { get { return listCount; } set { Set(ref listCount, value); } } #endregion } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDesktop.Models.ExcelModels; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDesktop.Models.SqlModel { public static class SqlMainModel { static SqlDataReader sqlDataReader; private static string connectionString = @"Data Source=nt-db01.ukkalita.local;Initial Catalog=M1_Revit;integrated security=True;MultipleActiveResultSets=True"; /// <summary> /// Получает список оборудования (SQL) из базы данных по выбранному проекту. Возвращает список Id оборудования с конкретным проектом /// </summary> /// <param name="ProjectId"></param> /// <returns></returns> public static SqlDataReader GetEqupmentByProjects(ProjectDto project) { string sqlExpression = "select e.Id, b.Name, s.Name, r.ShortName, e.ClassificationCode, e.Name, e.Count, e.Number, e.Mandatory from RaSM_Equipments e INNER JOIN RaSM_Rooms r ON e.RoomId = r.Id INNER JOIN RaSM_SubdivisionDto s ON r.SubdivisionId = s.Id inner join RaSM_Buildings b on s.BuildingId = b.Id inner join RaSM_Projects p on b.ProjectId = p.Id where p.Id = " + project.Id.ToString() + " and e.Mandatory = 1"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(sqlExpression, connection); SqlDataReader sqlDataReader = command.ExecuteReader(); MainExcelModel.UploadStandartEquipmentToExcel(sqlDataReader, project.Name); connection.Close(); return sqlDataReader; } } public static SqlDataReader GetStandartEquipmnetByProject(ProjectDto project) { string sqlExpression = "SELECT p.Name, b.Name, s.Name, r.Id, r.ShortName, e.Id, e.ClassificationCode, e.Name, e.Count, e.Number, e.Mandatory,e.Currently FROM RaSM_Rooms r Left JOIN RaSM_SubdivisionDto s ON r.SubdivisionId = s.Id Left join RaSM_Buildings b on s.BuildingId = b.Id Left join RaSM_Projects p on b.ProjectId = p.Id left join RaSM_Equipments e on r.Id = e.RoomId where p.Id = " + project.Id.ToString(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(sqlExpression, connection); SqlDataReader sqlDataReader = command.ExecuteReader(); MainExcelModel.UploadStandartEquipmentToExcel(sqlDataReader, project.Name); connection.Close(); return sqlDataReader; } } public static SqlDataReader GetAllEquipmnetByProject(ProjectDto project) { string sqlExpression = "SELECT p.Name, b.Name, s.Name, r.Id, r.ShortName, e.Id, e.ClassificationCode, e.Name, e.Count, e.Number, e.Mandatory,e.Currently FROM RaSM_Rooms r Left JOIN RaSM_SubdivisionDto s ON r.SubdivisionId = s.Id Left join RaSM_Buildings b on s.BuildingId = b.Id Left join RaSM_Projects p on b.ProjectId = p.Id left join RaSM_Equipments e on r.Id = e.RoomId where p.Id = " + project.Id.ToString(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(sqlExpression, connection); SqlDataReader sqlDataReader = command.ExecuteReader(); MainExcelModel.UploadAllEquipmentToExcel(sqlDataReader, project.Name); connection.Close(); return sqlDataReader; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesOV.Dto { class SpaceDto { public string RoomNumber { get; set; } public string Name { get; set; } public List<ParameterDto> parameters { get; set; } = new List<ParameterDto>(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; namespace RoomsAndSpacesManagerDataBase.Dto { [Table("RaSM_Projects")] public class ProjectDto { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<BuildingDto> Buildings { get; set; } public override string ToString() { return Name; } } } <file_sep>using System.Collections.Generic; using System.Linq; using System.Windows; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; namespace RoomsAndSpacesManagerDesktop.Models.DbModels { public class ProjectsDbContext : MainDbContext { public void DB() { } #region Добавть данные /// <summary> /// Добавить новый проект в БД /// </summary> /// <param name="proj"></param> public void AddNewProjects(ProjectDto proj) { context.RaSM_Projects.Add(proj); context.SaveChanges(); } /// <summary> /// Добавить новое здание в БД /// </summary> /// <param name="building"></param> public void AddNewBuilding(BuildingDto building) { context.RaSM_Buildings.Add(building); context.SaveChanges(); } /// <summary> /// Добавить новое подразделение в БД /// </summary> /// <param name="subdivision"></param> public void AddNewSubdivision(SubdivisionDto subdivision) { context.RaSM_Subdivisions.Add(subdivision); context.SaveChanges(); } /// <summary> /// Добавить новое помещение в БД /// </summary> /// <param name="rooms"></param> public void AddNewRooms(List<RoomDto> rooms) { context.RaSM_Rooms.AddRange(rooms.Where(x => x.Id == default).ToList()); context.SaveChanges(); } public void AddNewRoom(RoomDto room) { context.RaSM_Rooms.Add(room); context.SaveChanges(); } #endregion #region Получить данные /// <summary> /// Получить список проектов из БД /// </summary> /// <returns></returns> public List<ProjectDto> GetProjects() { return context.RaSM_Projects.ToList(); } /// <summary> /// Получить список зданий из БД /// </summary> /// <param name="project"></param> /// <returns></returns> public List<BuildingDto> GetModels(ProjectDto project) { return context.RaSM_Buildings.Where(x => x.ProjectId == project.Id).ToList(); } /// <summary> /// Получить список подразделений из БД /// </summary> /// <param name="building"></param> /// <returns></returns> public List<SubdivisionDto> GetSubdivisions(BuildingDto building) { return context.RaSM_Subdivisions.Where(x => x.BuildingId == building.Id).OrderBy(x => x.Order).ToList(); } /// <summary> /// Получить список задний из БД /// </summary> /// <param name="subdivision"></param> /// <returns></returns> public List<RoomDto> GetRooms(SubdivisionDto subdivision) { if (subdivision != null) return context.RaSM_Rooms.Where(x => x.Subdivision.Id == subdivision.Id).ToList(); else return null; } public List<RoomDto> GetAllRoomsByProject(ProjectDto project) { if (project != null) { List<int> subDivsIds = new List<int>(); foreach (BuildingDto build in project.Buildings) { foreach (SubdivisionDto subdiv in build.Subdivisions.OrderBy(x => x.Order)) { subDivsIds.Add(subdiv.Id); } } return context.RaSM_Rooms.Where(x => subDivsIds.Contains(x.SubdivisionId)).OrderBy(x => x.Subdivision.Order).ToList(); } return null; } #endregion #region Удалить данные /// <summary> /// Удалить проект из БД. (С проектом удаляются все здания, подразделения и помещения из БД) /// </summary> /// <param name="projDto"></param> public void RemoveProject(ProjectDto projDto) { context.RaSM_Projects.Remove(projDto); context.SaveChanges(); } /// <summary> /// Удалить здание из БД. (Со зданием удаляются все подразделения и помещения из БД) /// </summary> /// <param name="buildDto"></param> public void RemoveBuilding(BuildingDto buildDto) { context.RaSM_Buildings.Remove(buildDto); context.SaveChanges(); } /// <summary> /// Удалить подразделения из БД. (С подразделение удаляются все помещения, которые соотвествуют подразделению, из БД) /// </summary> /// <param name="subdiv"></param> public void RemoveSubDivision(SubdivisionDto subdiv) { context.RaSM_Subdivisions.Remove(subdiv); context.SaveChanges(); } /// <summary> /// Удалить помещение из БД /// </summary> /// <param name="room"></param> public void RemoveRoom(RoomDto room) { context.RaSM_Rooms.Remove(room); context.SaveChanges(); } #endregion /// <summary> /// Сохранить изменения в БД /// </summary> public void SaveChanges() { context.SaveChanges(); } } } <file_sep>using OfficeOpenXml; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.SqlModel; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RoomsAndSpacesManagerDesktop.Models.ExcelModels { class MainExcelModel { public void AddToDbFromExcelEqupment(RoomNameDto roomName) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.ShowDialog(); MessageBox.Show(openFileDialog.FileName); ExcelPackage excel = new ExcelPackage(new FileInfo(openFileDialog.FileName)); List<RoomEquipmentDto> equipnets = new List<RoomEquipmentDto>(); string idPom = "start"; var workbook = excel.Workbook; var worksheet = workbook.Worksheets.First(); int rowCount = 2; int colCount = 1; while (idPom != "") { if (worksheet.Cells[rowCount, colCount].Value == null) break; RoomEquipmentDto roomEquipmentDto = new RoomEquipmentDto(); roomEquipmentDto.RoomNameId = roomName.Id; if (worksheet.Cells[rowCount, 2].Value != null) roomEquipmentDto. Number = Convert.ToInt32(worksheet.Cells[rowCount, 2].Value); if (worksheet.Cells[rowCount, 3].Value != null) roomEquipmentDto.ClassificationCode = worksheet.Cells[rowCount, 3].Value.ToString(); if (worksheet.Cells[rowCount, 4].Value != null) roomEquipmentDto.TypeName = worksheet.Cells[rowCount, 4].Value.ToString(); if (worksheet.Cells[rowCount, 5].Value != null) roomEquipmentDto.Name = worksheet.Cells[rowCount, 5].Value.ToString(); if (worksheet.Cells[rowCount, 6].Value != null) roomEquipmentDto.Count = Convert.ToInt32(worksheet.Cells[rowCount, 6].Value); string ddd = worksheet.Cells[rowCount, 7].Value?.ToString(); if (worksheet.Cells[rowCount, 7].Value != null) { if (ddd == "True") roomEquipmentDto.Mandatory = true; } equipnets.Add(roomEquipmentDto); rowCount++; } EquipmentDbContext context = new EquipmentDbContext(); context.AddNewEquipments(equipnets); } public static bool UploadProgramToExcel (List<RoomDto> rooms) { ExcelPackage excel = new ExcelPackage(); FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); openFileDialog.ShowDialog(); string path; path = openFileDialog.SelectedPath + "\\" + rooms.First().Subdivision.Name + ".xlsx"; if (File.Exists(path)) File.Delete(path); excel.Workbook.Worksheets.Add("Сформированное задание"); ExcelWorksheet worksheet = excel.Workbook.Worksheets["Сформированное задание"]; int rowCount = 1; int colCount = 1; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Id); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Subdivision); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Name); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.ShortName); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.RoomNumber); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Min_area); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Kolichestvo_personala); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Kolichestvo_posetitelei); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Categoty_pizharoopasnosti); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Class_chistoti_SanPin); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Class_chistoti_SP_158); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Class_chistoti_GMP); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_AR); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.T_calc); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.T_min); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.T_max); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Pritok); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Vityazhka); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Ot_vlazhnost); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_OV); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Equipment_VK); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.KEO_est_osv); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.KEO_sovm_osv); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Osveshennost_pro_obshem_osvech); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.El_Nagruzka); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Group_el_bez); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_EOM); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_SS); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Nagruzki_na_perekririe); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_AK_ATH); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_GSV); colCount++; worksheet.Cells[rowCount, colCount].Value = nameof(RoomDto.Discription_HS); colCount = 1; rowCount++; foreach (var item in rooms) { worksheet.Cells[rowCount, colCount].Value = item.Id.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Subdivision?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Name?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.ShortName?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.RoomNumber?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Min_area?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Kolichestvo_personala?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Kolichestvo_posetitelei?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Categoty_pizharoopasnosti?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Class_chistoti_SanPin?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Class_chistoti_SP_158?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Class_chistoti_GMP?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_AR?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.T_calc?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.T_min?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.T_max?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Pritok?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Vityazhka?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Ot_vlazhnost?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_OV?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Equipment_VK?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.KEO_est_osv?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.KEO_sovm_osv?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Osveshennost_pro_obshem_osvech?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.El_Nagruzka?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Group_el_bez?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_EOM?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_SS?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Nagruzki_na_perekririe?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_AK_ATH?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_GSV?.ToString(); colCount++; worksheet.Cells[rowCount, colCount].Value = item.Discription_HS?.ToString(); colCount++; colCount = 1; rowCount++; } FileInfo excelFile = new FileInfo(path); excel.SaveAs(excelFile); return true; } /// <summary> /// Выгрузка стандарта оборудования в Excel по проекту /// </summary> /// <param name="project"></param> public static void UploadStandartEquipmentToExcel(SqlDataReader sqlDataReader, string projectName) { ExcelPackage excel = new ExcelPackage(); FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); openFileDialog.ShowDialog(); string path; path = openFileDialog.SelectedPath + "\\" + "Стандарт оборудования по" + projectName + ".xlsx"; if (File.Exists(path)) File.Delete(path); excel.Workbook.Worksheets.Add("Оборудование"); ExcelWorksheet worksheet = excel.Workbook.Worksheets["Оборудование"]; int rowCount = 1; int colCount = 1; worksheet.Cells[rowCount, colCount].Value = "Проект"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Здание"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Подразделение"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Id помещения"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Имя помещения"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Id оборудования"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Номер"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Код по классификатору"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Имя оборудования"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Количество"; colCount++; rowCount++; colCount = 1; while (sqlDataReader.Read()) { string o1 = sqlDataReader.GetValue(10).ToString().ToLower(); string o2 = sqlDataReader.GetValue(11).ToString().ToLower(); if ((o1 == "true" && o2 == "true") | (o1 == "" && o2 == "")) { worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(0); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(1); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(2); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(3); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(4); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(5); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(9); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(6); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(7); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(8); colCount++; colCount = 1; rowCount++; } else { continue; } } FileInfo excelFile = new FileInfo(path); excel.SaveAs(excelFile); } /// <summary> /// Выгрузка всего списка оборудования в Excel по проекту /// </summary> /// <param name="project"></param> public static void UploadAllEquipmentToExcel(SqlDataReader sqlDataReader, string projectName) { ExcelPackage excel = new ExcelPackage(); FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); openFileDialog.ShowDialog(); string path; path = openFileDialog.SelectedPath + "\\" + "Все оборудование по" + projectName + ".xlsx"; if (File.Exists(path)) File.Delete(path); excel.Workbook.Worksheets.Add("Оборудование"); ExcelWorksheet worksheet = excel.Workbook.Worksheets["Оборудование"]; int rowCount = 1; int colCount = 1; worksheet.Cells[rowCount, colCount].Value = "Проект"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Здание"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Подразделение"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Id помещения"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Имя помещения"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Id оборудования"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Номер"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Код по классификатору"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Имя оборудования"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Количество"; colCount++; rowCount++; colCount = 1; while (sqlDataReader.Read()) { string o1 = sqlDataReader.GetValue(10).ToString().ToLower(); string o2 = sqlDataReader.GetValue(11).ToString().ToLower(); if ( o1 == "true" | o1 == "") { worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(0); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(1); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(2); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(3); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(4); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(5); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(9); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(6); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(7); colCount++; worksheet.Cells[rowCount, colCount].Value = sqlDataReader.GetValue(8); colCount++; colCount = 1; rowCount++; } else { continue; } } FileInfo excelFile = new FileInfo(path); excel.SaveAs(excelFile); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; namespace RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure { [Table("RaSM_RoomNames")] public class RoomNameDto : ViewModel { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); public RoomNameDto() { var eee = SubCategotyId; var ddererr = SubCategory; } private int id; public int Id { get => id; set { id = value; var edee = roomAndSpacesDbContext.RaSM_RoomEquipments.Where(x => x.RoomNameId == Id).ToList(); if (edee.Count == 0) { EquipmentAvailability = "No"; } else { EquipmentAvailability = "Yes"; } } } public string Key { get; set; } public string Name { get; set; } #region Исходные данные по помещениям public string Min_area { get; set; } public string Class_chistoti_SanPin { get; set; } public string Class_chistoti_SP_158 { get; set; } public string Class_chistoti_GMP { get; set; } public string T_calc { get; set; } public string T_min { get; set; } public string T_max { get; set; } public string Pritok { get; set; } public string Vityazhka { get; set; } public string Ot_vlazhnost { get; set; } public string KEO_est_osv { get; set; } public string KEO_sovm_osv { get; set; } public string Discription_OV { get; set; } public string Osveshennost_pro_obshem_osvech { get; set; } public string Group_el_bez { get; set; } public string Discription_EOM { get; set; } public string Discription_AR { get; set; } public string Equipment_VK { get; set; } public string Discription_SS { get; set; } public string Discription_AK_ATH { get; set; } public string Discription_GSV { get; set; } public string Categoty_Chistoti_po_san_epid { get; set; } public string Discription_HS { get; set; } #endregion [NotMapped] public string EquipmentAvailability { get => equipmentAvailability; set { Set(ref equipmentAvailability, value); } } public int SubCategotyId { get; set; } private ICollection<RoomEquipmentDto> roomEquipments; private string equipmentAvailability; public virtual ICollection<RoomEquipmentDto> RoomEquipments { get => roomEquipments; set { roomEquipments = value; } } public virtual SubCategoryDto SubCategory { get; set; } [NotMapped] public string SubCategoryDtoName { get; set; } public override string ToString() { return Name; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; namespace RoomsAndSpacesManagerDataBase.Dto { [Table("RaSM_Buildings")] public class BuildingDto : ViewModel { public int Id { get; set; } public string Name { get; set; } public string Path { get; set; } public int ProjectId { get; set; } [NotMapped] public int? SunnuryArea { get; set; } private bool isReadOnly = false; [NotMapped] public bool IsReadOnly { get => isReadOnly; set => Set(ref isReadOnly, value); } public virtual ProjectDto Project { get; set; } public virtual ICollection<SubdivisionDto> Subdivisions { get; set; } public override string ToString() { return Name; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Infrastructure.Repositories; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using RoomsAndSpacesManagerDesktop.Views.Windows; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace RoomsAndSpacesManagerDesktop.ViewModels { class CopySubDivisionViewModel : ViewModel { public CopySubdivisionWindow copySubdivisionWindow; public static ProjectsDbContext projContext; EquipmentDbContext equipmentDbContext = new EquipmentDbContext(); public static int selectedBuildingId; public static BuildingDto Building; public CopySubDivisionViewModel() { Projects = projContext.GetProjects(); CopySubdivisionCommand = new RelayCommand(OnCopySubdivisionCommandExecuted, CanCopySubdivisionCommandExecute); } #region Список проектов. Выбранный проект private List<ProjectDto> projects; /// <summary> Список проектов. Из БД </summary> public List<ProjectDto> Projects { get => projects; set => Set(ref projects, value); } private ProjectDto selectedProject; public ProjectDto SelectedProject { get { return selectedProject; } set { selectedProject = value; if (SelectedProject != null) { if (SelectedProject.Buildings != null) Buildings = projContext.GetModels(SelectedProject); } else { Buildings = new List<BuildingDto>(); } } } #endregion #region Список зданий. Выбранное здание private List<BuildingDto> buildings; /// <summary> Список проектов. Из БД </summary> public List<BuildingDto> Buildings { get => buildings; set => Set(ref buildings, value); } private BuildingDto selectedBuilding; public BuildingDto SelectedBuilding { get { return selectedBuilding; } set { selectedBuilding = value; if (SelectedBuilding != null) { if (SelectedBuilding.Subdivisions != null) Subdivisions = projContext.GetSubdivisions(SelectedBuilding); } else Subdivisions = null; } } #endregion #region Список подразделений. Выбранное подразделение private List<SubdivisionDto> subdivisions; /// <summary> Список проектов. Из БД </summary> public List<SubdivisionDto> Subdivisions { get => subdivisions; set => Set(ref subdivisions, value); } private SubdivisionDto selectedSubdivision; public SubdivisionDto SelectedSubdivision { get { return selectedSubdivision; } set { Set(ref selectedSubdivision, value); } } #endregion #region Комманд. Копирование public ICommand CopySubdivisionCommand { get; set; } private void OnCopySubdivisionCommandExecuted(object obj) { EquipmentDbContext eqContext = new EquipmentDbContext(); List<SubdivisionDto> newSubDivivsions = Subdivisions.Where(x => x.IsChecked).Select(x => new SubdivisionDto(x) { BuildingId = selectedBuildingId }).ToList(); Subdivisions.Where(x => x.IsChecked).Select(x => projContext.GetRooms(x)).ToList(); int nextOrder; if (Building.Subdivisions != null && Building.Subdivisions.Count != 0) nextOrder = Building.Subdivisions.Select(x => x.Order).Max() + 1; else nextOrder = 1; foreach (SubdivisionDto subdivision in Subdivisions.Where(x => x.IsChecked)) { SubdivisionDto newSubdivision = new SubdivisionDto(subdivision) { BuildingId = selectedBuildingId, Order = nextOrder }; nextOrder++; projContext.AddNewSubdivision(newSubdivision); List<RoomDto> newRooms = new List<RoomDto>(); foreach (RoomDto room in projContext.GetRooms(subdivision)) { var newRom = new RoomDto(room) { SubdivisionId = newSubdivision.Id }; projContext.AddNewRoom(newRom); if (room.Equipments != null & room.Equipments.Count != 0) eqContext.CopyEquipmentBetweenRoomIssue(room, newRom); //foreach (var currnetEquipment in room.Equipments) //{ // equipmentDbContext.AddNewEquipment(new EquipmentDto(currnetEquipment, newRom.Id)); //} //var newEq = equipmentDbContext.GetEquipments(newRom); //EquipmentRep equipment = new EquipmentRep(newEq); } projContext.AddNewRooms(newRooms); } copySubdivisionWindow.Close(); } private bool CanCopySubdivisionCommandExecute(object obj) => true; #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; namespace RoomsAndSpacesManagerDesktop.Infrastructure.CustomControls { class ComboBoxTemplateSelectorExtension : MarkupExtension { public DataTemplate SelectedItemTemplate { get; set; } public DataTemplateSelector SelectedItemTemplateSelector { get; set; } public DataTemplate DropdownItemsTemplate { get; set; } public DataTemplateSelector DropdownItemsTemplateSelector { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) => new ComboBoxTemplateSelector() { SelectedItemTemplate = SelectedItemTemplate, SelectedItemTemplateSelector = SelectedItemTemplateSelector, DropdownItemsTemplate = DropdownItemsTemplate, DropdownItemsTemplateSelector = DropdownItemsTemplateSelector }; } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using RoomsAndSpacesManagerDesktop.Views.Windows; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace RoomsAndSpacesManagerDesktop.ViewModels { class RoomsPropertiesViewModel : ViewModel { public static RoomsDbContext roomsContext = new RoomsDbContext(); public RoomsPropertiesViewModel() { Categories = roomsContext.GetCategories(); #region Комманды PushToDbCommand = new RelayCommand(OnPushToDbCommandExecutde, CanPushToDbCommandExecute); AddNewRowCommand = new RelayCommand(OnAddNewRowCommandExecutde, CanAddNewRowCommandExecute); DeleteRoomCommand = new RelayCommand(OnDeleteRoomCommandExecutde, CanDeleteRoomCommandExecute); GetRoomEquipments = new RelayCommand(OnGetRoomEquipmentsExecutde, CanGetRoomEquipmentsExecute); LoadedCommand = new RelayCommand(OnLoadedCommandExecutde, CanLoadedCommandExecute); AddNewCategoryCommand= new RelayCommand(OnAddNewCategoryCommandExecutde, CanAddNewCategoryCommandExecute); #endregion } /*MainWindow~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Комманд. Рендер окна public ICommand LoadedCommand { get; set; } private async void OnLoadedCommandExecutde(object obj) { if (RoomsList == null | RoomsList?.Count == 0) { RoomsList = roomsContext.GetAllRoomNames(); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Filter = delegate (object item) { RoomNameDto user = item as RoomNameDto; if (user != null && user.Name != null && user.Name.ToLower().StartsWith(RoomNameFiltering.ToLower())) return true; return false; }; Rooms.Refresh(); } } private bool CanLoadedCommandExecute(object obj) => true; #endregion /*Верхняя панель. Список категорий и подкатегорий~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Combobox - Список категорий private List<CategoryDto> categories; public List<CategoryDto> Categories { get { return categories; } set { categories = value; } } private CategoryDto selectedCategoties; /// <summary> /// Выбранная категория помещений /// </summary> public CategoryDto SelectedCategoties { get { return selectedCategoties; } set { Set(ref selectedCategoties, value); if (SelectedCategoties != null) { SubCategories = roomsContext.GetSubCategotyes(SelectedCategoties); RoomsList = new List<RoomNameDto>(); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } } } #endregion #region Combobox - список подкатегорий private List<SubCategoryDto> subCategories; public List<SubCategoryDto> SubCategories { get { return subCategories; } set { Set(ref subCategories, value); } } private SubCategoryDto selectedSubCategoties; /// <summary> /// Выбранная подкатегория помещений /// </summary> public SubCategoryDto SelectedSubCategoties { get { return selectedSubCategoties; } set { selectedSubCategoties = value; if (SelectedSubCategoties != null) { RoomsDbContext newroomsDbContext = new RoomsDbContext(); RoomsList = newroomsDbContext.GetRoomNames(SelectedSubCategoties); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } } } #endregion #region Фильтер помещений по имени и ID private string roomNameFiltering = string.Empty; public string RoomNameFiltering { get { return roomNameFiltering; } set { if (RoomNameFiltering != "") { RoomsList = roomsContext.GetAllRoomNames(); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Filter = delegate (object item) { RoomNameDto user = item as RoomNameDto; if (user != null && user.Name != null && user.Name.ToLower().Contains(RoomNameFiltering.ToLower())) return true; return false; }; Rooms.Refresh(); } roomNameFiltering = value; CollectionViewSource.GetDefaultView(RoomsList).Refresh(); } } #endregion /*Верхняя панель. Новые картеории и подкатегрии~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Новая категория. Комманд на добавление и текстбокс с именем private string newCategoryName; public string NewCategoryName { get { return newCategoryName; } set { newCategoryName = value; } } public ICommand AddNewCategoryCommand { get; set; } private void OnAddNewCategoryCommandExecutde(object obj) { } private bool CanAddNewCategoryCommandExecute(object obj) { if (NewCategoryName != null && NewCategoryName != "") return true; return false; } #endregion /*Центральная панель. Список комнат~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Список комнат private List<RoomNameDto> roomsList; public List<RoomNameDto> RoomsList { get { return roomsList; } set => Set(ref roomsList, value); } private ICollectionView rooms; public ICollectionView Rooms { get => rooms; set => Set(ref rooms, value); } #endregion /*Нижнаяя панель. Комманды взаимодвествия с БД~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #region Комманд. Удаление помещения public ICommand DeleteRoomCommand { get; set; } private void OnDeleteRoomCommandExecutde(object obj) { if ((obj as RoomNameDto).Id == 0) { RoomsList.Remove(obj as RoomNameDto); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } else { roomsContext.RemoveRoom(obj as RoomNameDto); RoomsList = roomsContext.GetRoomNames(SelectedSubCategoties); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } } private bool CanDeleteRoomCommandExecute(object obj) => true; #endregion #region Комманд. Добавить строку public ICommand AddNewRowCommand { get; set; } private void OnAddNewRowCommandExecutde(object obj) { RoomsList.Add(new RoomNameDto() { SubCategotyId = SelectedSubCategoties.Id }); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } private bool CanAddNewRowCommandExecute(object obj) { if (SelectedSubCategoties != null) return true; else return false; } #endregion #region Комманд. Закинуть обновления пространств в БД public ICommand PushToDbCommand { get; set; } private void OnPushToDbCommandExecutde(object p) { roomsContext.SaveChanges(); roomsContext.AddRooms(RoomsList.Where(x => x.Id == 0).ToList()); RoomsList = roomsContext.GetRoomNames(SelectedSubCategoties); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); MessageBox.Show("Данные успешно загруженны в базу данных", "Статус"); } private bool CanPushToDbCommandExecute(object p) => true; #endregion #region Статус выполнения private string status; public string Status { get => status; set => Set(ref status, value); } #endregion #region Комманд. Список оборудования public ICommand GetRoomEquipments { get; set; } private void OnGetRoomEquipmentsExecutde(object p) { RoomEquipmentsViewModel.RoomName = p as RoomNameDto; RoomEquipmentsWindow roomEquipmentsWindow = new RoomEquipmentsWindow(); RoomEquipmentsViewModel roomEquipmentsViewModel = new RoomEquipmentsViewModel(); roomEquipmentsWindow.DataContext = roomEquipmentsViewModel; roomEquipmentsWindow.ShowDialog(); Rooms = CollectionViewSource.GetDefaultView(RoomsList); Rooms.Refresh(); } private bool CanGetRoomEquipmentsExecute(object p) => true; #endregion } } <file_sep>using Autodesk.Revit.DB; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.UI; using RoomAndSpacesOV.Dto; using RoomAndSpacesOV.Models.RvtHelper; using RoomAndSpacesOV.ViewModels; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesOV.Models.RvtModels { class AddParametersToModelEvHend : IExternalEventHandler { /// <summary> /// Список помещений. Из Cmd /// </summary> public static List<Space> Spacies { get; set; } /// <summary> /// Список помещений из БД. Из vm /// </summary> public static List<RoomDto> RoomsDto { get; set; } MainModelRvtHelper mainModelRvtHelper = new MainModelRvtHelper(); public static event Action<object> ChangeUI; public void Execute(UIApplication app) { Document doc = app.ActiveUIDocument.Document; List<SpaceDto> spacesDto = new List<SpaceDto>(); using (Transaction transaction = new Transaction(doc, "Внесение значений параметров")) { transaction.Start(); foreach (Space item in Spacies) { var rvtRoomNumber = item.LookupParameter("Номер").AsString(); var roomDto = RoomsDto.FirstOrDefault(x => x.RoomNumber == rvtRoomNumber); SpaceDto space = new SpaceDto() { Name = item.Name, RoomNumber = rvtRoomNumber }; #region Внесение параметров if (roomDto != null) { space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Вытяжка кратность", nameof(roomDto.Vityazhka), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Группа по электробезопасности", nameof(roomDto.Group_el_bez), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Категория пожароопасности", nameof(roomDto.Categoty_pizharoopasnosti), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Класс чистоты по СанПиН", nameof(roomDto.Class_chistoti_SanPin), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Класс чистоты по СП 158", nameof(roomDto.Class_chistoti_SP_158), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Количество пациентов", nameof(roomDto.Kolichestvo_posetitelei), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Количество персонала", nameof(roomDto.Kolichestvo_personala), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Мощность_ТХ", nameof(roomDto.El_Nagruzka), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Освещенность_ТХ", nameof(roomDto.Osveshennost_pro_obshem_osvech), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Относительная влажность_Текст", nameof(roomDto.Ot_vlazhnost), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание АР", nameof(roomDto.Discription_AR), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ВК", nameof(roomDto.Equipment_VK), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание КР", nameof(roomDto.Nagruzki_na_perekririe), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание МГ", nameof(roomDto.Discription_GSV), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ОВ", nameof(roomDto.Discription_OV), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ТГ", nameof(roomDto.Discription_GSV), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ЭМ", nameof(roomDto.Discription_EOM), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание СС", nameof(roomDto.Discription_SS), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ХС", nameof(roomDto.Discription_HS), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Приток кратность", nameof(roomDto.Pritok), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Расчетная площадь", nameof(roomDto.Min_area), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура максимальная С", nameof(roomDto.T_max), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура минимальная С", nameof(roomDto.T_min), item, roomDto)); space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура расчетная С", nameof(roomDto.T_calc), item, roomDto)); space.parameters.RemoveAll(x => x == null); } #endregion RoomsDto.Remove(roomDto); spacesDto.Add(space); } transaction.Commit(); MainWindowViewModel.SpaciesList = spacesDto.Where(x => x.parameters.Count != 0).ToList(); MainWindowViewModel.UnfoundedRooms = RoomsDto; ChangeUI?.Invoke(this); } } public string GetName() => nameof(AddParametersToModelEvHend); } } <file_sep>using OfficeOpenXml; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RoomsAndSpacesManagerDesktop.Models.CsvModels { internal class UploadToCsvModel { RoomAndSpacesDbContext context = new RoomAndSpacesDbContext(); private ProjectDto Project { get; set; } private string path; private ExcelPackage excel = new ExcelPackage(); private List<BuildingDto> BuildList { get; set; } private double Koef { get; set; } public UploadToCsvModel(ProjectDto project, List<BuildingDto> buildList, double koef) { this.Project = project; this.BuildList = buildList; this.Koef = koef; } public UploadToCsvModel() { } public void UploadToExcel() { FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); openFileDialog.ShowDialog(); path = openFileDialog.SelectedPath; if (File.Exists(path + @"\Программа.xlsx")) File.Delete(path + @"\Программа.xlsx"); excel.Workbook.Worksheets.Add("Программа помещений"); excel.Workbook.Worksheets.Add("Сводная"); UploadRoomProgramToExcel(Project); UploadRoomSummaryToExcel(BuildList); FileInfo excelFile = new FileInfo(path + @"\Программа.xlsx"); excel.SaveAs(excelFile); } public void UploadRoomProgramToExcel(ProjectDto project) { var worksheet = excel.Workbook.Worksheets["Программа помещений"]; int rowCount = 1; int colCount = 1; worksheet.Cells[rowCount, colCount].Value = "№/№"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Наименование помещения"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Площадь, м^2"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Примечание"; colCount = 1; rowCount++; int i = 1; foreach (BuildingDto build in context.RaSM_Projects.FirstOrDefault(x => x.Id == project.Id).Buildings) { worksheet.Cells[rowCount, colCount].Value = i; colCount++; worksheet.Cells[rowCount, colCount].Value = build.Name; colCount = 1; rowCount++; int ii = 1; foreach (SubdivisionDto subdivision in build.Subdivisions) { string iis = i.ToString() + "." + ii.ToString(); worksheet.Cells[rowCount, colCount].Value = iis; colCount++; worksheet.Cells[rowCount, colCount].Value = subdivision.Name; colCount = 1; rowCount++; int iii = 1; foreach (RoomDto room in subdivision.Rooms) { string iiis = i.ToString() + "." + ii.ToString() + "." + iii.ToString(); worksheet.Cells[rowCount, colCount].Value = iiis; colCount++; worksheet.Cells[rowCount, colCount].Value = room.ShortName; colCount++; worksheet.Cells[rowCount, colCount].Value = room.Min_area; colCount++; worksheet.Cells[rowCount, colCount].Value = room.Notation; colCount = 1; rowCount++; iii++; } ii++; } i++; } } public void UploadRoomSummaryToExcel(List<BuildingDto> buildList) { var worksheet = excel.Workbook.Worksheets["Сводная"]; int rowCount = 1; int colCount = 1; worksheet.Cells[rowCount, colCount].Value = "№/№"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Подразделение"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Площадь расчётная, м^2"; colCount++; worksheet.Cells[rowCount, colCount].Value = "Ориент. общая площадь, м^2"; colCount = 1; rowCount++; int n1 = 1; double sumarea = 0; double Ksumarea = 0; foreach (BuildingDto build in buildList) { worksheet.Cells[rowCount, 1].Value = n1.ToString(); worksheet.Cells[rowCount, 2].Value = build.Name; worksheet.Cells[rowCount, 3].Value = build.SunnuryArea; sumarea += Convert.ToDouble(build.SunnuryArea); Ksumarea += Convert.ToDouble(build.SunnuryArea) * Koef; worksheet.Cells[rowCount, 4].Value = build.SunnuryArea * Koef; rowCount++; int n2 = 1; foreach (SubdivisionDto subdiv in build.Subdivisions) { worksheet.Cells[rowCount, 1].Value = n1.ToString() + "." + n2.ToString(); worksheet.Cells[rowCount, 2].Value = subdiv.Name; worksheet.Cells[rowCount, 3].Value = subdiv.SunnuryArea; worksheet.Cells[rowCount, 4].Value = subdiv.SunnuryArea * Koef; n2++; rowCount++; } n1++; } worksheet.Cells[rowCount, 3].Value = sumarea; worksheet.Cells[rowCount, 4].Value = Ksumarea; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace RoomsAndSpacesManagerDesktop.Infrastructure.CustomControls { class CustomTextBlockColumnTemplate : TextBlock { public string PropertyName { get { return (string)GetValue(PropertyNameProperty); } set { SetValue(PropertyNameProperty, value); } } public CustomTextBlockColumnTemplate() { TextWrapping = TextWrapping.Wrap; } public static readonly DependencyProperty PropertyNameProperty = DependencyProperty.Register("PropertyName", typeof(string), typeof(CustomTextBlockColumnTemplate), new FrameworkPropertyMetadata("", new PropertyChangedCallback(PropertyNameChanged))); private static void PropertyNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CustomTextBlockColumnTemplate)d).PropertyName = ((CustomTextBlockColumnTemplate)d).PropertyName; } public string FirstValue { get { return (string)GetValue(FirstValueProperty); } set { SetValue(FirstValueProperty, value); string propValue = SecondValue?.GetType().GetProperty(PropertyName)?.GetValue(SecondValue)?.ToString(); if (FirstValue != propValue) { Background = Brushes.Pink; } else { Background = Brushes.Transparent; } } } public static readonly DependencyProperty FirstValueProperty = DependencyProperty.Register("FirstValue", typeof(string), typeof(CustomTextBlockColumnTemplate), new FrameworkPropertyMetadata("", new PropertyChangedCallback(FirstValueChanged))); private static void FirstValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CustomTextBlockColumnTemplate)d).FirstValue = ((CustomTextBlockColumnTemplate)d).FirstValue; } public RoomNameDto SecondValue { get { return (RoomNameDto)GetValue(SecondValueProperty); } set { SetValue(SecondValueProperty, value); string propValue = SecondValue?.GetType().GetProperty(PropertyName)?.GetValue(SecondValue)?.ToString(); if (FirstValue != propValue) { Background = Brushes.Pink; } else { Background = Brushes.Transparent; } } } public static readonly DependencyProperty SecondValueProperty = DependencyProperty.Register("SecondValue", typeof(RoomNameDto), typeof(CustomTextBlockColumnTemplate), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(SecondValueChanged))); private static void SecondValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CustomTextBlockColumnTemplate)d).SecondValue = ((CustomTextBlockColumnTemplate)d).SecondValue; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using RoomsAndSpacesManagerDesktop.Views.Windows; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Input; namespace RoomsAndSpacesManagerDesktop.ViewModels { class ProjectSettingsViewModel : ViewModel { List<SubdivisionDto> subdivisionsList = new List<SubdivisionDto>(); ProjectsDbContext context; ProjectSettingsWindow window; public ProjectSettingsViewModel() { } public ProjectSettingsViewModel(List<SubdivisionDto> _subdivisionsList, ref ProjectsDbContext _context, ProjectSettingsWindow _window) { SubdivisionTypes = new List<string>() { "Палатное", "Оперблок", "РИТ", "ДС", "Амбулаторное", "Иное" }; ApplyChangesCommand = new RelayCommand(OnApplyChangesCommandExecuted, CanApplyChangesCommandExecute); UpCommand = new RelayCommand(OnUpCommandExecuted, CanUpCommandExecute); DownCommand = new RelayCommand(OnDownCommandExecuted, CanDownCommandExecute); subdivisionsList = _subdivisionsList; context = _context; window = _window; Subdivisions = CollectionViewSource.GetDefaultView(subdivisionsList); Subdivisions.Refresh(); } #region КоллекшенВью. Список подразделений private ICollectionView subdivisions; public ICollectionView Subdivisions { get { return subdivisions; } set { Set(ref subdivisions, value); } } private SubdivisionDto selectedSubdivision; public SubdivisionDto SelectedSubdivision { get { return selectedSubdivision; } set { Set(ref selectedSubdivision, value); } } #endregion #region Комманд. Сохранить изменения public ICommand ApplyChangesCommand { get; set; } private void OnApplyChangesCommandExecuted(object obj) { context.SaveChanges(); window.Close(); } private bool CanApplyChangesCommandExecute(object obj) => true; #endregion #region Комманд. Переместить выбранное подразделение вверх public ICommand UpCommand { get; set; } private void OnUpCommandExecuted(object obj) { var subDiv = obj as SubdivisionDto; if (subDiv.Order > 1) { subdivisionsList.FirstOrDefault(x => x.Order == subDiv.Order - 1).Order = subDiv.Order; subDiv.Order = subDiv.Order - 1; context.SaveChanges(); var sortList = subdivisionsList.OrderBy(x => x.Order).ToList(); Subdivisions = CollectionViewSource.GetDefaultView(sortList); Subdivisions.Refresh(); } } private bool CanUpCommandExecute(object obj) => true; #endregion #region Комманд. Переместить выбранное подразделение вниз public ICommand DownCommand { get; set; } private void OnDownCommandExecuted(object obj) { var subDiv = obj as SubdivisionDto; if (subDiv.Order < subdivisionsList.Count) { subdivisionsList.FirstOrDefault(x => x.Order == subDiv.Order + 1).Order = subDiv.Order; subDiv.Order = subDiv.Order + 1; context.SaveChanges(); var sortList = subdivisionsList.OrderBy(x => x.Order).ToList(); Subdivisions = CollectionViewSource.GetDefaultView(sortList); Subdivisions.Refresh(); } } private bool CanDownCommandExecute(object obj) => true; #endregion #region Список типов подразделений public List<string> SubdivisionTypes { get; set; } #endregion } }<file_sep>using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.UI; using RoomsAndSpacesManagerLib.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace RoomsAndSpacesManagerLib.Models.RevitModels { [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] class SelectRoomEventHendler : IExternalEventHandler { public static event Action<object> ChangeUI; public static int DbRommId; public void Execute(UIApplication app) { Autodesk.Revit.UI.UIDocument uiDoc = app.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selection = uiDoc.Selection; var selectedIds = uiDoc.Selection.GetElementIds(); Element dd = uiDoc.Document.GetElement(selectedIds.First()); MainWindowViewModel.roomId = (dd as Room).get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString(); MainWindowViewModel.rvtToomId = dd.Id.IntegerValue; using (Transaction trans = new Transaction(app.ActiveUIDocument.Document, "AddToFamilyParam")) { trans.Start(); dd.LookupParameter("М1_ID_задания")?.Set(DbRommId); //dd.LookupParameter("Имя").Set(DbRommId); trans.Commit(); } ChangeUI.Invoke(this); } public string GetName() => nameof(SelectRoomEventHendler); } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDesktop.Data.DataBaseContext { public class RoomAndSpacesDbContext : DbContext { public RoomAndSpacesDbContext() { this.Database.Connection.ConnectionString = @"Data Source=nt-db01.ukkalita.local;Initial Catalog=M1_Revit;integrated security=True;MultipleActiveResultSets=True"; } public DbSet<ProjectDto> RaSM_Projects { get; set; } public DbSet<BuildingDto> RaSM_Buildings { get; set; } public DbSet<RoomDto> RaSM_Rooms { get; set; } public DbSet<CategoryDto> RaSM_RoomCategories { get; set; } public DbSet<SubCategoryDto> RaSM_RoomSubCategories { get; set; } public DbSet<RoomNameDto> RaSM_RoomNames { get; set; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RoomsAndSpacesManagerDataBase.Dto { [Table("RaSM_Rooms")] public class RoomDto : ViewModel { static RoomAndSpacesDbContext context = new RoomAndSpacesDbContext(); private int roomNameId; private string min_area; private string class_chistoti_SanPin; private string class_chistoti_SP_158; private string class_chistoti_GMP; private string t_calc; private string discription_HS; private string categoty_Chistoti_po_san_epid; private string discription_GSV; private string discription_AK_ATH; private string discription_SS; private string equipment_VK; private string discription_AR; private string discription_EOM; private string group_el_bez; private string osveshennost_pro_obshem_osvech; private string discription_OV; private string kEO_sovm_osv; private string kEO_est_osv; private string ot_vlazhnost; private string vityazhka; private string pritok; private string t_max; private string t_min; public RoomDto() { } public RoomDto(RoomDto oldRoom) { this.RoomNameId = oldRoom.RoomNameId; this.ShortName = oldRoom.ShortName; this.RoomNumber = oldRoom.RoomNumber; this.Min_area = oldRoom.Min_area; this.Class_chistoti_SanPin = oldRoom.Class_chistoti_SanPin; this.Class_chistoti_SP_158 = oldRoom.Class_chistoti_SP_158; this.Class_chistoti_GMP = oldRoom.Class_chistoti_GMP; this.T_calc = oldRoom.T_calc; this.T_min = oldRoom.T_min; this.T_max = oldRoom.T_max; this.Pritok = oldRoom.Pritok; this.Vityazhka = oldRoom.Vityazhka; this.Ot_vlazhnost = oldRoom.Ot_vlazhnost; this.KEO_est_osv = oldRoom.KEO_est_osv; this.KEO_sovm_osv = oldRoom.KEO_sovm_osv; this.Discription_OV = oldRoom.Discription_OV; this.Osveshennost_pro_obshem_osvech = oldRoom.Osveshennost_pro_obshem_osvech; this.Group_el_bez = oldRoom.Group_el_bez; this.Discription_EOM = oldRoom.Discription_EOM; this.Discription_AR = oldRoom.Discription_AR; this.Equipment_VK = oldRoom.Equipment_VK; this.Discription_SS = oldRoom.discription_SS; this.Discription_AK_ATH = oldRoom.Discription_AK_ATH; this.Discription_GSV = oldRoom.discription_GSV; this.Categoty_Chistoti_po_san_epid = oldRoom.Categoty_Chistoti_po_san_epid; this.Discription_HS = oldRoom.Discription_HS; this.Categoty_pizharoopasnosti = oldRoom.Categoty_pizharoopasnosti; this.Rab_mesta_posetiteli = oldRoom.Rab_mesta_posetiteli; this.Kolichestvo_personala = oldRoom.Kolichestvo_personala; this.Kolichestvo_posetitelei = oldRoom.Kolichestvo_posetitelei; this.Nagruzki_na_perekririe = oldRoom.Nagruzki_na_perekririe; this.El_Nagruzka = oldRoom.El_Nagruzka; } #region Поля для выгрузки public int Id { get; set; } private string name; [NotMapped] public string Name { get => name; set => Set(ref name, value); } public int RoomNameId { get => roomNameId; set { roomNameId = value; if (RoomNameId != 0) { RoomName = context.RaSM_RoomNames.FirstOrDefault(x => x.Id == RoomNameId); Name = RoomName?.Name; } } } public string ShortName { get; set; } public string RoomNumber { get; set; } #region Исходные данные по помещениям public string Min_area { get => min_area; set { Set(ref min_area, value); } } public string Class_chistoti_SanPin { get => class_chistoti_SanPin; set { Set(ref class_chistoti_SanPin, value); } } public string Class_chistoti_SP_158 { get => class_chistoti_SP_158; set { Set(ref class_chistoti_SP_158, value); } } public string Class_chistoti_GMP { get => class_chistoti_GMP; set { Set(ref class_chistoti_GMP, value); } } public string T_calc { get => t_calc; set { Set(ref t_calc, value); } } public string T_min { get => t_min; set { Set(ref t_min, value); } } public string T_max { get => t_max; set { Set(ref t_max, value); } } public string Pritok { get => pritok; set { Set(ref pritok, value); } } public string Vityazhka { get => vityazhka; set { Set(ref vityazhka, value); } } public string Ot_vlazhnost { get => ot_vlazhnost; set { Set(ref ot_vlazhnost, value); } } public string KEO_est_osv { get => kEO_est_osv; set { Set(ref kEO_est_osv, value); } } public string KEO_sovm_osv { get => kEO_sovm_osv; set { Set(ref kEO_sovm_osv, value); } } public string Discription_OV { get => discription_OV; set { Set(ref discription_OV, value); } } public string Osveshennost_pro_obshem_osvech { get => osveshennost_pro_obshem_osvech; set { Set(ref osveshennost_pro_obshem_osvech, value); } } public string Group_el_bez { get => group_el_bez; set { Set(ref group_el_bez, value); } } public string Discription_EOM { get => discription_EOM; set { Set(ref discription_EOM, value); } } public string Discription_AR { get => discription_AR; set { Set(ref discription_AR, value); } } public string Equipment_VK { get => equipment_VK; set { Set(ref equipment_VK, value); } } public string Discription_SS { get => discription_SS; set { Set(ref discription_SS, value); } } public string Discription_AK_ATH { get => discription_AK_ATH; set { Set(ref discription_AK_ATH, value); } } public string Discription_GSV { get => discription_GSV; set { Set(ref discription_GSV, value); } } public string Categoty_Chistoti_po_san_epid { get => categoty_Chistoti_po_san_epid; set { Set(ref categoty_Chistoti_po_san_epid, value); } } public string Discription_HS { get => discription_HS; set { Set(ref discription_HS, value); } } public string Categoty_pizharoopasnosti { get; set; } public string Rab_mesta_posetiteli { get; set; } public string Kolichestvo_personala { get; set; } public string Kolichestvo_posetitelei { get; set; } public string Nagruzki_na_perekririe { get; set; } public string El_Nagruzka { get; set; } public string Notation { get; set; } #endregion private int arRoomId; public int ArRoomId { get => arRoomId; set => Set(ref arRoomId, value); } #region SupClass private RoomNameDto roomName; [NotMapped] public RoomNameDto RoomName { get => roomName; set => Set(ref roomName, value); } #endregion public int SubdivisionId { get; set; } public virtual SubdivisionDto Subdivision { get; set; } public virtual ICollection<EquipmentDto> Equipments { get; set; } #endregion } } <file_sep>using Microsoft.VisualBasic.FileIO; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesManagerConsole { class CsvToDbRooms { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); List<CategoryDto> categoryDtos; List<SubCategoryDto> subCategoryDtos; public void AddCats() { List<CategoryDto> CatList = new List<CategoryDto>(); using (TextFieldParser parser = new TextFieldParser(@"C:\Users\ya.goreglyad\Desktop\Категории-Подкатегрии.csv")) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(";"); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); if (CatList.FirstOrDefault(x => x.Name == fields[0]) == null) { CatList.Add(new CategoryDto() { Key = fields[1], Name = fields[0] }); } } roomAndSpacesDbContext.RaSM_RoomCategories.AddRange(CatList); roomAndSpacesDbContext.SaveChanges(); } } public void GetSubCatsCsv() { categoryDtos = roomAndSpacesDbContext.RaSM_RoomCategories.ToList(); List<SubCategoryDto> SubCatList = new List<SubCategoryDto>(); using (TextFieldParser parser = new TextFieldParser(@"C:\Users\ya.goreglyad\Desktop\Категории-Подкатегрии.csv")) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(";"); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); SubCatList.Add(new SubCategoryDto() { Key = fields[3], Name = fields[2] }); } } foreach (SubCategoryDto _subCat in SubCatList) { var dd = _subCat.Key.Split('.')[1]; int id = categoryDtos.FirstOrDefault(x => x.Key.Split('.')[1] == dd).Id; _subCat.CategotyId = id; } roomAndSpacesDbContext.RaSM_RoomSubCategories.AddRange(SubCatList); roomAndSpacesDbContext.SaveChanges(); } public void AddRooms() { subCategoryDtos = roomAndSpacesDbContext.RaSM_RoomSubCategories.ToList(); List<RoomNameDto> RoomsList = new List<RoomNameDto>(); using (TextFieldParser parser = new TextFieldParser(@"C:\Users\ya.goreglyad\Desktop\Помещения.csv")) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(";"); while (!parser.EndOfData) { //Process row string[] fields = parser.ReadFields(); RoomsList.Add(new RoomNameDto() { Key = fields[0], Name = fields[1], Min_area = fields[2], Class_chistoti_SanPin = fields[3], Class_chistoti_SP_158 = fields[4], Class_chistoti_GMP = fields[5], T_calc = fields[6], T_min = fields[7], T_max = fields[8], Pritok = fields[9], Vityazhka = fields[10], Ot_vlazhnost = fields[11], KEO_est_osv = fields[12], KEO_sovm_osv = fields[13], Discription_OV = fields[14], Osveshennost_pro_obshem_osvech = fields[15], Group_el_bez = fields[16], Discription_EOM = fields[17], Discription_AR = fields[18], Equipment_VK = fields[19], Discription_SS = fields[20], Discription_AK_ATH = fields[21], Discription_GSV = fields[22], Categoty_Chistoti_po_san_epid = fields[23], Discription_HS = fields[24] }); } foreach (RoomNameDto room in RoomsList) { string roomKey = room.Key; var sdd = subCategoryDtos.FirstOrDefault(x => x.Key == roomKey); if (sdd != null) { room.SubCategotyId = sdd.Id; } } roomAndSpacesDbContext.RaSM_RoomNames.AddRange(RoomsList); roomAndSpacesDbContext.SaveChanges(); } } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Infrastructure.Repositories; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDesktop.Models.DbModels { class EquipmentDbContext : MainDbContext { #region RoomEq public List<RoomEquipmentDto> GetAllEquipments() { return context.RaSM_RoomEquipments.ToList(); } public List<RoomEquipmentDto> GetEquipments(RoomNameDto roomName) { return context.RaSM_RoomEquipments.Where(x => x.RoomNameId == roomName.Id).ToList(); } public List<EquipmentDto> GetEquipmentsWithSortItems(RoomNameDto roomName, RoomDto room) { List<EquipmentDto> equpmets = context.RaSM_RoomEquipments .Where(x => x.RoomNameId == roomName.Id) .Select(x => new EquipmentDto(x, 0) { RoomId = room.Id, Mandatory = false }) .ToList(); equpmets.Sort((x, y) => x.Number.CompareTo(y.Number)); int activeNumber = default; foreach (EquipmentDto eq in equpmets) { if (!activeNumber.Equals(eq.Number)) { activeNumber = eq.Number; eq.Mandatory = true; } } return equpmets; } public void AddNewEquipment(RoomNameDto roomName) { context.RaSM_RoomEquipments.Add(new RoomEquipmentDto() { RoomNameId = roomName.Id }); context.SaveChanges(); } public void AddNewEquipments(List<RoomEquipmentDto> equipments) { context.RaSM_RoomEquipments.AddRange(equipments); context.SaveChanges(); } public void RemoveEquipment(RoomEquipmentDto equipment) { context.RaSM_RoomEquipments.Remove(equipment); context.SaveChanges(); } #endregion #region Eq public List<EquipmentDto> GetEquipments(RoomDto room) { return context.RaSM_Equipments.Where(x => x.RoomId == room.Id).ToList(); } public List<EquipmentDto> AddEquipmentsByRoomNameId(RoomDto room) { var roomEqupments = context.RaSM_RoomEquipments.Where(x => x.RoomNameId == room.RoomNameId).ToList(); var equpments = roomEqupments.Select(x => new EquipmentDto(x, room.Subdivision?.SubdivisionForce) { RoomId = room.Id, Currently = false }).ToList(); EquipmentRep equipments = new EquipmentRep(equpments); context.RaSM_Equipments.AddRange(equipments.Equipments); context.SaveChanges(); return equipments.Equipments; } public void CopyRoomNameEquipmentsToRoomIssue(RoomNameDto roomName, RoomDto room) { //context.RaSM_Equipments.RemoveRange(context.RaSM_Equipments.Where(x => x.RoomId == room.Id)); List<EquipmentDto> equpmets = context.RaSM_RoomEquipments .Where(x => x.RoomNameId == roomName.Id).ToList() .Select(x => new EquipmentDto(x, room.Subdivision?.SubdivisionForce) { RoomId = room.Id, Mandatory = x.Mandatory, Currently = false }) .ToList(); EquipmentRep equipments = new EquipmentRep(equpmets); context.RaSM_Equipments.AddRange(equpmets); context.SaveChanges(); } public void CopyEquipmentBetweenRoomIssue(RoomDto defaultRoom, RoomDto currentRoom) { var equipments = context.RaSM_Equipments .Where(x => x.RoomId == defaultRoom.Id).ToList() .Select(x => new EquipmentDto(x, currentRoom.Id, currentRoom.Subdivision?.SubdivisionForce)).ToList(); context.RaSM_Equipments.AddRange(equipments); context.SaveChanges(); } public void AddNewEquipment(RoomDto room) { context.RaSM_Equipments.Add(new EquipmentDto() { RoomId = room.Id }); context.SaveChanges(); } public void AddNewEquipment(EquipmentDto eq) { context.RaSM_Equipments.Add(eq); context.SaveChanges(); } public void RemoveEquipment(EquipmentDto equipment) { context.RaSM_Equipments.Remove(equipment); context.SaveChanges(); } public void RemoveAllEquipment(RoomDto room) { context.RaSM_Equipments.RemoveRange(context.RaSM_Equipments.Where(x => x.RoomId == room.Id)); context.SaveChanges(); } #endregion public void SaveChanges() { context.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.UI; using RoomsAndSpacesManagerLib.ViewModels; using System.Windows; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerLib.Models.RevitHelper; using RoomsAndSpacesManagerLib.Dto; namespace RoomsAndSpacesManagerLib.Models.RevitModels { [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] class AddParametersIntoSpacies : IExternalEventHandler { public static List<RoomDto> Rooms { get; set; } public static event Action<object> ChangeUI; public void Execute(UIApplication app) { List<SpaceDto> changedSpacies = new List<SpaceDto>(); Document doc = app.ActiveUIDocument.Document; List<Room> elements = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .Select(x => x as Room) .Where(x => x.LookupParameter("Номер") != null & x.LookupParameter("Номер").AsString() != "") .ToList(); int count = 0; int count2 = 0; using (Transaction trans = new Transaction(doc, "set parameters")) { trans.Start(); foreach (RoomDto room in Rooms) { Room rvtRoom = elements.FirstOrDefault(x => x.LookupParameter("Номер").AsString() == room.RoomNumber); SpaceDto spaceDto = new SpaceDto() { Name = rvtRoom.Name, RoomNumber = rvtRoom.Number, }; if (rvtRoom == null) count++; else count2++; spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Категория пожароопасности", nameof(room.Categoty_pizharoopasnosti), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Класс чистоты по СанПиН", nameof(room.Class_chistoti_SanPin), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Класс чистоты по СП 158", nameof(room.Class_chistoti_SP_158), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Количество пациентов", nameof(room.Kolichestvo_posetitelei), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Количество персонала", nameof(room.Kolichestvo_personala), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Примечание АР", nameof(room.Discription_AR), rvtRoom, room)); spaceDto.parameters.Add(RevitHelperModel.SetProperty("М1_Расчетная площадь", nameof(room.Min_area), rvtRoom, room)); spaceDto.parameters.RemoveAll(x => x == null); changedSpacies.Add(spaceDto); } trans.Commit(); } MainWindowViewModel.Spacies = changedSpacies.Where(x => x.parameters.Count != 0).ToList(); ChangeUI?.Invoke(this); } public string GetName() => nameof(AddParametersIntoSpacies); } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDataBase.Dto { [Table("RaSM_Equipments")] public class EquipmentDto : ViewModel { private bool mandatory; private bool currently; public EquipmentDto() { } public EquipmentDto(RoomEquipmentDto roomEquipment, int? SubdivisionForse) { Number = roomEquipment.Number; ClassificationCode = roomEquipment.ClassificationCode; TypeName = roomEquipment.TypeName; Name = roomEquipment.Name; Count = roomEquipment.Count; Mandatory = roomEquipment.Mandatory; Currently = roomEquipment.Mandatory; CalcCount = roomEquipment.CalcCount; } public EquipmentDto(EquipmentDto equipmentDto, int roomId, int? SubdivisionForse) { Number = equipmentDto.Number; ClassificationCode = equipmentDto.ClassificationCode; TypeName = equipmentDto.TypeName; Name = equipmentDto.Name; Count = equipmentDto.Count; Mandatory = equipmentDto.Mandatory; Currently = equipmentDto.Currently; Discription = equipmentDto.Discription; RoomId = roomId; CalcCount = equipmentDto.CalcCount; } [Key] public int Id { get; set; } public int Number { get; set; } public string ClassificationCode { get; set; } public string TypeName { get; set; } public string Name { get; set; } public int Count { get; set; } public string CalcCount { get; set; } public bool Mandatory { get => mandatory; set => Set(ref mandatory, value); } public bool Currently { get => currently; set => Set(ref currently, value); } public string Discription { get; set; } private int roomId; public int RoomId { get => roomId; set => roomId = value; } private RoomDto room; public virtual RoomDto Room { get => room; set => room = value; } public override string ToString() { return Name; } } }<file_sep>namespace RoomsAndSpacesManagerDesktop.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddSubdivTypeFieldToSubdivision : DbMigration { public override void Up() { AddColumn("dbo.RaSM_SubdivisionDto", "SubdivisionType", c => c.String()); } public override void Down() { DropColumn("dbo.RaSM_SubdivisionDto", "SubdivisionType"); } } } <file_sep>using OfficeOpenXml; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomAndSpacesManagerConsole.DbModel { class AddToRoomNameSubCategoryIdModel { public void AddOrderCountToSubdivision() { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); foreach (BuildingDto build in roomAndSpacesDbContext.RaSM_Buildings) { int orderCount = 1; foreach (SubdivisionDto subdiv in build.Subdivisions) { subdiv.Order = orderCount; orderCount++; } orderCount = 1; } roomAndSpacesDbContext.SaveChanges(); } public void AddToRoomNameSubCategoryIdModelMain() { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); ExcelPackage excel = new ExcelPackage(new FileInfo(@"C:\Users\ya.goreglyad\Desktop\ПомещенияВДб.xlsx")); var workbook = excel.Workbook; var worksheet = workbook.Worksheets.First(); int rowCount = 1; int count = 1; List<string> roomNamesIsNotExcist = new List<string>(); while (rowCount < 112) { int subCatId = Convert.ToInt32(worksheet.Cells[rowCount, 1].Value); string roomName = worksheet.Cells[rowCount, 3].Value.ToString(); if (roomAndSpacesDbContext.RaSM_RoomNames.FirstOrDefault(x => x.Name == roomName) != null) { roomAndSpacesDbContext.RaSM_RoomNames.FirstOrDefault(x => x.Name == roomName).SubCategotyId = subCatId; } else { } rowCount++; } roomAndSpacesDbContext.SaveChanges(); } public void Change_1_Field() { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); //var dfdf = roomAndSpacesDbContext.RaSM_RoomNames.Where(x => x.SubCategotyId == 0).ToList(); roomAndSpacesDbContext.RaSM_RoomNames.RemoveRange(roomAndSpacesDbContext.RaSM_RoomNames.Where(x => x.SubCategotyId == 0)); roomAndSpacesDbContext.SaveChanges(); } public void SwapPersonalPosetiteli() { RoomAndSpacesDbContext roomAndSpacesDbContext = new RoomAndSpacesDbContext(); foreach (RoomDto room in roomAndSpacesDbContext.RaSM_Rooms.Where(x => x.Rab_mesta_posetiteli != null)) { var s = room.Rab_mesta_posetiteli.Split('/'); string personal = s[0]; string posetiteli = s[1]; room.Kolichestvo_personala = personal; room.Kolichestvo_posetitelei = posetiteli; } roomAndSpacesDbContext.SaveChanges(); } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Infrastructure.Commands; using RoomsAndSpacesManagerDesktop.Models.DbModels; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using RoomsAndSpacesManagerDesktop.Models.ExcelModels; using RoomsAndSpacesManagerDesktop.ViewModels.Base; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Input; namespace RoomsAndSpacesManagerDesktop.ViewModels { class EquipmentsViewModel : ViewModel { public static RoomDto Room { get; set; } EquipmentDbContext context = new EquipmentDbContext(); RoomsDbContext roomsContext = new RoomsDbContext(); List<EquipmentDto> equipmentsList { get; set; } public EquipmentsViewModel() { equipmentsList = context.GetEquipments(Room); RoomEquipmentsList = CollectionViewSource.GetDefaultView(equipmentsList); RoomEquipmentsList.Refresh(); #region Комманды AddNewRowCommand = new RelayCommand(OnAddNewRowCommandExecuted, CanAddNewRowCommandExecute); SaveChangesCommand = new RelayCommand(OnSaveChangesCommandExecuted, CanSaveChangesCommandExecute); ClickCheckboxCommand = new RelayCommand(OnClickCheckboxCommandExecuted, CanClickCheckboxCommandExecute); DeleteEquipmentCommand = new RelayCommand(OnDeleteEquipmentCommandExecuted, CanDeleteEquipmentCommandExecute); SetDefaultEquipmentsCommand = new RelayCommand(OnSetDefaultEquipmentsCommandExecuted, CanSetDefaultEquipmentsCommandExecute); #endregion } #region КоллекшенВью для списка оборудования private ICollectionView roomEquipmentsList; public ICollectionView RoomEquipmentsList { get => roomEquipmentsList; set => Set(ref roomEquipmentsList, value); } #endregion #region Комманд. Добавить новую строку public ICommand AddNewRowCommand { get; set; } private void OnAddNewRowCommandExecuted(object obj) { context.AddNewEquipment(Room); equipmentsList = context.GetEquipments(Room); RoomEquipmentsList = CollectionViewSource.GetDefaultView(equipmentsList); RoomEquipmentsList.Refresh(); } private bool CanAddNewRowCommandExecute(object obj) => true; #endregion #region Комманд. Сохранить изменения public ICommand SaveChangesCommand { get; set; } private void OnSaveChangesCommandExecuted(object obj) { context.SaveChanges(); } private bool CanSaveChangesCommandExecute(object obj) => true; #endregion #region Комманд. Удалить строку оборудования public ICommand DeleteEquipmentCommand { get; set; } private void OnDeleteEquipmentCommandExecuted(object obj) { context.RemoveEquipment(obj as EquipmentDto); equipmentsList = context.GetEquipments(Room); RoomEquipmentsList = CollectionViewSource.GetDefaultView(equipmentsList); RoomEquipmentsList.Refresh(); } private bool CanDeleteEquipmentCommandExecute(object obj) => true; #endregion #region Комманд. Обработчик нажайтий на Чекбокс внутри списка оборудования. public ICommand ClickCheckboxCommand { get; set; } private void OnClickCheckboxCommandExecuted(object obj) { EquipmentDto equipmentDto = obj as EquipmentDto; if (!equipmentDto.Currently) { if (equipmentsList.Where(x => x.Number == equipmentDto.Number).Count() > 1) { if (equipmentsList.Where(x => x.Number == equipmentDto.Number).Where(y => y.Currently == true).Count() == 0) { equipmentDto.Currently = true; } } else { equipmentDto.Currently = true; } } } private bool CanClickCheckboxCommandExecute(object obj) => true; #endregion #region Комманд. Сделать список оборудование по умолчанию public ICommand SetDefaultEquipmentsCommand { get; set; } private void OnSetDefaultEquipmentsCommandExecuted(object obj) { context.RemoveAllEquipment(Room); equipmentsList = context.AddEquipmentsByRoomNameId(Room); RoomEquipmentsList = CollectionViewSource.GetDefaultView(equipmentsList); RoomEquipmentsList.Refresh(); } private bool CanSetDefaultEquipmentsCommandExecute(object obj) { return true; } #endregion } } <file_sep>using Autodesk.Revit.UI; using RoomsAndSpacesManagerDataBase; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using RoomsAndSpacesManagerLib.Dto; using RoomsAndSpacesManagerLib.Infrastructure; using RoomsAndSpacesManagerLib.Models.DataBaseModels; using RoomsAndSpacesManagerLib.Models.RevitModels; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace RoomsAndSpacesManagerLib.ViewModels { class MainWindowViewModel : ViewModel { public ExternalEvent ApplyEventGetRoomFromRvtModel; public ExternalEvent ApplyEventAddParametersIntoSpacies; public static string roomId; public static int rvtToomId; ProjectsDbContext projectsDbContext = new ProjectsDbContext(); List<RoomDto> roomDtos; public MainWindowViewModel() { Projects = projectsDbContext.GetProjects(); SelectRoomEventHendler.ChangeUI += OnSelectRevitRoomCommandExecutdeEvent; AddParametersIntoSpacies.ChangeUI += OpenChangedSpaciesList; SelectRevitRoomCommand = new RelayCommand(OnSelectRevitRoomCommandExecutde, CanSelectRevitRoomCommandExecute); PushToDbCommand = new RelayCommand(OnPushToDbCommandExecuted, CanPushToDbCommandExecute); AddParametersCommand = new RelayCommand(OnAddParametersCommandExecuted, CanAddParametersCommandExecute); } #region СелектедИнекс ТабКонтрола private int selectedIndexTabControl; public int SelectedIndexTabControl { get => selectedIndexTabControl; set => Set(ref selectedIndexTabControl, value); } #endregion #region Список проектов. Выбранный проект private List<ProjectDto> projects; /// <summary> Список проектов. Из БД </summary> public List<ProjectDto> Projects { get => projects; set => Set(ref projects, value); } private ProjectDto selectedProject; public ProjectDto SelectedProject { get { return selectedProject; } set { selectedProject = value; if (SelectedProject != null) { if (SelectedProject.Buildings != null) Buildings = projectsDbContext.GetModels(SelectedProject); } else { Buildings = new List<BuildingDto>(); } } } #endregion #region Список зданий. Выбранное здание private List<BuildingDto> buildings; public List<BuildingDto> Buildings { get => buildings; set => Set(ref buildings, value); } private BuildingDto selectedBuilding; public BuildingDto SelectedBuilding { get { return selectedBuilding; } set { selectedBuilding = value; if (SelectedBuilding != null) { roomDtos = projectsDbContext.GetRoomsByModels(SelectedBuilding); Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } else Rooms = null; } } #endregion #region Список помещений. Выбранное помещение private ICollectionView rooms; public ICollectionView Rooms { get => rooms; set => Set(ref rooms, value); } private static RoomDto selectedRoom; public static RoomDto SelectedRoom { get => selectedRoom; set { selectedRoom = value; } } #endregion #region Выбрать помещение из ревита public ICommand SelectRevitRoomCommand { get; set; } private void OnSelectRevitRoomCommandExecutde(object sander) { SelectRoomEventHendler.DbRommId = (sander as RoomDto).Id; ApplyEventGetRoomFromRvtModel.Raise(); } private void OnSelectRevitRoomCommandExecutdeEvent(object sander) { SelectedRoom.RoomNumber = roomId.ToString(); SelectedRoom.ArRoomId = rvtToomId; Rooms = CollectionViewSource.GetDefaultView(roomDtos); Rooms.Refresh(); } private bool CanSelectRevitRoomCommandExecute(object sander) => true; #endregion #region Пуш в БД public ICommand PushToDbCommand { get; set; } private void OnPushToDbCommandExecuted(object obj) { projectsDbContext.SaveChanges(); MessageBox.Show("Изменения успешно внесены в БД!", "Статус"); } private bool CanPushToDbCommandExecute(object obj) => true; #endregion #region Комманд. Заполнить параметры пространст public ICommand AddParametersCommand { get; set; } private void OnAddParametersCommandExecuted(object obj) { AddParametersIntoSpacies.Rooms = roomDtos; ApplyEventAddParametersIntoSpacies.Raise(); } private bool CanAddParametersCommandExecute(object obj) => true; #endregion #region Список измененных помещений public static List<SpaceDto> Spacies { get; set; } private void OpenChangedSpaciesList(object obj) { SelectedIndexTabControl = 1; ChangeParametersList = CollectionViewSource.GetDefaultView(Spacies); ChangeParametersList.Refresh(); } private ICollectionView changeParametersList; public ICollectionView ChangeParametersList { get => changeParametersList; set => Set(ref changeParametersList, value); } #endregion } } <file_sep>namespace RoomsAndSpacesManagerDataBase.Migrations { using System; using System.Data.Entity.Migrations; public partial class NewTable : DbMigration { public override void Up() { CreateTable( "dbo.RaSM_Buildings", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Path = c.String(), ProjectId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RaSM_Projects", t => t.ProjectId, cascadeDelete: true) .Index(t => t.ProjectId); CreateTable( "dbo.RaSM_Projects", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RaSM_SubdivisionDto", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), BuildingId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RaSM_Buildings", t => t.BuildingId, cascadeDelete: true) .Index(t => t.BuildingId); CreateTable( "dbo.RaSM_Rooms", c => new { Id = c.Int(nullable: false, identity: true), RoomNameId = c.Int(nullable: false), ShortName = c.String(), RoomNumber = c.String(), Min_area = c.String(), Count = c.Int(), Summary_Area = c.Int(), Class_chistoti_SanPin = c.String(), Class_chistoti_SP_158 = c.String(), Class_chistoti_GMP = c.String(), T_calc = c.String(), T_min = c.String(), T_max = c.String(), Pritok = c.String(), Vityazhka = c.String(), Ot_vlazhnost = c.String(), KEO_est_osv = c.String(), KEO_sovm_osv = c.String(), Discription_OV = c.String(), Osveshennost_pro_obshem_osvech = c.String(), Group_el_bez = c.String(), Discription_EOM = c.String(), Discription_AR = c.String(), Equipment_VK = c.String(), Discription_SS = c.String(), Discription_AK_ATH = c.String(), Discription_GSV = c.String(), Categoty_Chistoti_po_san_epid = c.String(), Discription_HS = c.String(), Categoty_pizharoopasnosti = c.String(), Rab_mesta_posetiteli = c.String(), Nagruzki_na_perekririe = c.String(), El_Nagruzka = c.String(), ArRoomId = c.Int(nullable: false), BuildingId = c.Int(nullable: false), SubdivisionDto_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RaSM_Buildings", t => t.BuildingId, cascadeDelete: true) .ForeignKey("dbo.RaSM_SubdivisionDto", t => t.SubdivisionDto_Id) .Index(t => t.BuildingId) .Index(t => t.SubdivisionDto_Id); CreateTable( "dbo.RaSM_RoomCategory", c => new { Id = c.Int(nullable: false, identity: true), Key = c.String(), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RaSM_SubRoomCategory", c => new { Id = c.Int(nullable: false, identity: true), Key = c.String(), Name = c.String(), CategotyId = c.Int(nullable: false), Category_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RaSM_RoomCategory", t => t.Category_Id) .Index(t => t.Category_Id); CreateTable( "dbo.RaSM_RoomNames", c => new { Id = c.Int(nullable: false, identity: true), Key = c.String(), Name = c.String(), Min_area = c.String(), Class_chistoti_SanPin = c.String(), Class_chistoti_SP_158 = c.String(), Class_chistoti_GMP = c.String(), T_calc = c.String(), T_min = c.String(), T_max = c.String(), Pritok = c.String(), Vityazhka = c.String(), Ot_vlazhnost = c.String(), KEO_est_osv = c.String(), KEO_sovm_osv = c.String(), Discription_OV = c.String(), Osveshennost_pro_obshem_osvech = c.String(), Group_el_bez = c.String(), Discription_EOM = c.String(), Discription_AR = c.String(), Equipment_VK = c.String(), Discription_SS = c.String(), Discription_AK_ATH = c.String(), Discription_GSV = c.String(), Categoty_Chistoti_po_san_epid = c.String(), Discription_HS = c.String(), SubCategotyId = c.Int(nullable: false), SubCategory_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RaSM_SubRoomCategory", t => t.SubCategory_Id) .Index(t => t.SubCategory_Id); } public override void Down() { DropForeignKey("dbo.RaSM_RoomNames", "SubCategory_Id", "dbo.RaSM_SubRoomCategory"); DropForeignKey("dbo.RaSM_SubRoomCategory", "Category_Id", "dbo.RaSM_RoomCategory"); DropForeignKey("dbo.RaSM_Rooms", "SubdivisionDto_Id", "dbo.RaSM_SubdivisionDto"); DropForeignKey("dbo.RaSM_Rooms", "BuildingId", "dbo.RaSM_Buildings"); DropForeignKey("dbo.RaSM_SubdivisionDto", "BuildingId", "dbo.RaSM_Buildings"); DropForeignKey("dbo.RaSM_Buildings", "ProjectId", "dbo.RaSM_Projects"); DropIndex("dbo.RaSM_RoomNames", new[] { "SubCategory_Id" }); DropIndex("dbo.RaSM_SubRoomCategory", new[] { "Category_Id" }); DropIndex("dbo.RaSM_Rooms", new[] { "SubdivisionDto_Id" }); DropIndex("dbo.RaSM_Rooms", new[] { "BuildingId" }); DropIndex("dbo.RaSM_SubdivisionDto", new[] { "BuildingId" }); DropIndex("dbo.RaSM_Buildings", new[] { "ProjectId" }); DropTable("dbo.RaSM_RoomNames"); DropTable("dbo.RaSM_SubRoomCategory"); DropTable("dbo.RaSM_RoomCategory"); DropTable("dbo.RaSM_Rooms"); DropTable("dbo.RaSM_SubdivisionDto"); DropTable("dbo.RaSM_Projects"); DropTable("dbo.RaSM_Buildings"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure { [Table("RaSM_RoomEquipments")] public class RoomEquipmentDto { [Key] public int Id { get; set; } public int Number { get; set; } public string ClassificationCode { get; set; } public string TypeName { get; set; } public string Name { get; set; } public int Count { get; set; } public bool Mandatory { get; set; } public string Discription { get; set; } public string CalcCount { get; set; } public int RoomNameId { get; set; } public virtual RoomNameDto RoomName { get; set; } public override string ToString() { return Name; } } } <file_sep>using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.UI; using RoomAndSpacesOV.Dto; using RoomAndSpacesOV.Models.RvtHelper; using RoomAndSpacesOV.Models.RvtModels; using RoomAndSpacesOV.ViewModels; using RoomAndSpacesOV.Views.Windows; using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace RoomAndSpacesOV { [Transaction(TransactionMode.Manual)] public class Cmd : IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { MainModelRvtHelper mainModelRvtHelper = new MainModelRvtHelper(); Document doc = commandData.Application.ActiveUIDocument.Document; List<Element> spaces = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_MEPSpaces).ToElements().ToList(); AddParametersToModelEvHend.Spacies = spaces.Select(x => x as Space).ToList(); RoomAndSpacesDbContext context = new RoomAndSpacesDbContext(); List<SpaceDto> spacesDto = new List<SpaceDto>(); MainWindowViewModel.SpaciesList = spacesDto.Where(x => x.parameters.Count != 0).ToList(); ExternalEvent ExEventSelectRoom = ExternalEvent.Create(new AddParametersToModelEvHend()); MainWindow mainWindow = new MainWindow(); mainWindow.DataContext = new MainWindowViewModel() { AddParamtersToModelExEvent = ExEventSelectRoom }; mainWindow.Show(); //int count = 0; //using (Transaction transaction = new Transaction(doc, "Внесение значений параметров")) //{ // transaction.Start(); // foreach (Element item in spaces) // { // count++; // var rvtRoomNumber = item.LookupParameter("Номер").AsString(); // var roomDto = context.RaSM_Rooms.FirstOrDefault(x => x.RoomNumber == rvtRoomNumber); // SpaceDto space = new SpaceDto() // { // Name = item.Name, // RoomNumber = rvtRoomNumber // }; // #region Внесение параметров // if (roomDto != null) // { // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Класс чистоты по СанПиН", "Class_chistoti_SanPin", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Класс чистоты по СП 158", "Class_chistoti_SP_158", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Нагрузка ЭОМ", "El_Nagruzka", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Относительная влажность_Текст", "Ot_vlazhnost", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание АР", "Discription_AR", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ВК", "Equipment_VK", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание КР", "Nagruzki_na_perekririe", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание МГ", "Discription_GSV", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ОВ", "Discription_OV", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ЭОМ", "Discription_EOM", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание СС", "Discription_SS", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Примечание ХС", "Discription_HS", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Приток кратность", "Pritok", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("M1_Вытяжка кратность", "Vityazhka", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Расчетная площадь", "Summary_Area", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура максимальная С", "T_max", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура минимальная С", "T_min", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Температура расчетная С", "T_calc", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Мощность_ТХ", "El_Nagruzka", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Освещенность_ТХ", "Osveshennost_pro_obshem_osvech", item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Количество пациентов", nameof(roomDto.Kolichestvo_personala), item, roomDto)); // space.parameters.Add(mainModelRvtHelper.SetPropertt("М1_Количество персонала", nameof(roomDto.Kolichestvo_posetitelei), item, roomDto)); // space.parameters.RemoveAll(x => x == null); // } // if (roomDto?.Rab_mesta_posetiteli != null & roomDto?.Rab_mesta_posetiteli != "") // { // var roomDtodeee = roomDto?.Rab_mesta_posetiteli.Split('/'); // int pac; // int.TryParse(roomDtodeee[1], out pac); // if (pac != default) // item.LookupParameter("М1_Количество пациентов")?.Set(pac); // int per; // int.TryParse(roomDtodeee[0], out per); // if (per != default) // item.LookupParameter("М1_Количество персонала")?.Set(per); // } // #endregion // spacesDto.Add(space); // } // transaction.Commit(); //} //MainWindowViewModel.SpaciesList = spacesDto.Where(x => x.parameters.Count != 0).ToList(); //MainWindow mainWindow = new MainWindow(); //mainWindow.DataContext = new MainWindowViewModel(); //mainWindow.ShowDialog(); return Result.Succeeded; } } } <file_sep>namespace RoomsAndSpacesManagerDesktop.Migrations { using System; using System.Data.Entity.Migrations; public partial class DeleteCountAndSummuryArea : DbMigration { public override void Up() { DropColumn("dbo.RaSM_Rooms", "Count"); DropColumn("dbo.RaSM_Rooms", "Summary_Area"); } public override void Down() { AddColumn("dbo.RaSM_Rooms", "Summary_Area", c => c.Int()); AddColumn("dbo.RaSM_Rooms", "Count", c => c.Int()); } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace RoomsAndSpacesManagerDesktop.Infrastructure.CustomControls { class CustomColumnTemplate : DataGridTemplateColumn { public CustomColumnTemplate() { CellEditingTemplate = new DataTemplate(new TextBlock()); } public RoomDto BindingDataContext { get { return (RoomDto)GetValue(BindingDataContextProperty); } set { SetValue(BindingDataContextProperty, value); } } public static readonly DependencyProperty BindingDataContextProperty = DependencyProperty.Register("BindingDataContext", typeof(RoomDto), typeof(CustomColumnTemplate), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(BindingDataContextChanged))); private static void BindingDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CustomColumnTemplate)d).BindingDataContext = ((CustomColumnTemplate)d).BindingDataContext; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; using RoomsAndSpacesManagerDataBase.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerLib.Models.DataBaseModels { public class ProjectsDbContext { RoomAndSpacesDbContext context = new RoomAndSpacesDbContext(); public List<ProjectDto> GetProjects() { return context.RaSM_Projects.ToList(); } public List<BuildingDto> GetModels(ProjectDto projDto) { return context.RaSM_Buildings.Where(x => x.ProjectId == projDto.Id).ToList(); } public List<RoomDto> GetRooms(SubdivisionDto subdiv) { if (subdiv != null) return context.RaSM_Rooms.Where(x => x.Subdivision.Id == subdiv.Id).ToList(); else return null; } public List<RoomDto> GetRoomsByModels(BuildingDto building) { List<RoomDto> rooms = new List<RoomDto>(); foreach (SubdivisionDto subdiv in context.RaSM_Subdivisions.Where(x => x.BuildingId == building.Id)) { rooms.AddRange(context.RaSM_Rooms.Where(x => x.SubdivisionId == subdiv.Id)); } return rooms; } public void SaveChanges() { context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDataBase.Dto { [Table("RaSM_SubdivisionDto")] public class SubdivisionDto : ViewModel { public int Id { get; set; } public string Name { get; set; } [NotMapped] public bool IsChecked { get; set; } = false; [NotMapped] public int? SunnuryArea { get; set; } private bool isReadOnly = false; [NotMapped] public bool IsReadOnly { get => isReadOnly; set => Set(ref isReadOnly, value); } public int SubdivisionForce { get; set; } public string SubdivisionType { get; set; } public int BuildingId { get; set; } public int Order { get; set; } public virtual BuildingDto Building { get; set; } public virtual ICollection<RoomDto> Rooms { get; set; } public override string ToString() { return Name; } public SubdivisionDto() { } public SubdivisionDto(SubdivisionDto subdivision) { this.Name = subdivision.Name; } } } <file_sep>using RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure; using RoomsAndSpacesManagerDesktop.Models.DbModels.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDesktop.Models.DbModels { class RoomsDbContext : MainDbContext { #region Добавление в БД /// <summary> /// Добавить категории в БД (не актуален) /// </summary> /// <param name="subCategoryDtos"></param> public void AddCategoties(List<CategoryDto> subCategoryDtos) { context.RaSM_RoomCategories.AddRange(subCategoryDtos); context.SaveChanges(); } /// <summary> /// Добавить подкатегории в БД (не актуален) /// </summary> /// <param name="subCategoryDtos"></param> public void AddSubCategoties(List<SubCategoryDto> subCategoryDtos) { context.RaSM_RoomSubCategories.AddRange(subCategoryDtos); context.SaveChanges(); } /// <summary> /// Добавить имена комнат в БД (не актуален) /// </summary> /// <param name="subCategoryDtos"></param> public void AddRooms(List<RoomNameDto> roomNameDtos) { context.RaSM_RoomNames.AddRange(roomNameDtos); context.SaveChanges(); } /// <summary> /// Удалитить комнаты из исходжного списка помещений /// </summary> /// <param name="roomNameDto"></param> public void RemoveRoom(RoomNameDto roomNameDto) { context.RaSM_RoomNames.Remove(context.RaSM_RoomNames.FirstOrDefault(x => x.Id == roomNameDto.Id)); context.SaveChanges(); } public void SaveChanges() { context.SaveChanges(); } #endregion #region Получение из БД /// <summary> /// Получить список категорий /// </summary> /// <returns></returns> public List<CategoryDto> GetCategories() { return context.RaSM_RoomCategories.ToList(); } /// <summary> /// Получить список подкатегорий /// </summary> /// <returns></returns> public List<SubCategoryDto> GetSubCategotyes(CategoryDto cat) { return context.RaSM_RoomSubCategories.Where(x => x.CategotyId == cat.Id).ToList(); } /// <summary> /// Получить список имен комнат по подкатегрии /// </summary> /// <returns></returns> public List<RoomNameDto> GetRoomNames(SubCategoryDto subCat) { return context.RaSM_RoomNames.Where(x => x.SubCategotyId == subCat.Id).ToList(); } /// <summary> /// Получить весь список помещений асинхронно /// </summary> /// <returns></returns> public async Task<List<RoomNameDto>> GetAllRoomNamesAsync() { return await Task.Run(() => context.RaSM_RoomNames.ToList()); } /// <summary> /// Получить весь список помещений /// </summary> /// <returns></returns> public List<RoomNameDto> GetAllRoomNames() { return context.RaSM_RoomNames.ToList(); } /// <summary> /// Получить список помещений по категории /// </summary> /// <param name="category"></param> /// <returns></returns> public List<RoomNameDto> GetAllRoomNamesByCategoty(CategoryDto category) { return context.RaSM_RoomNames.ToList(); } #endregion } } <file_sep>using RoomsAndSpacesManagerDataBase.Data.DataBaseContext; namespace RoomsAndSpacesManagerDesktop.Models.DbModels.Base { public class MainDbContext { public RoomAndSpacesDbContext context; public MainDbContext() { context = new RoomAndSpacesDbContext(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure { [Table("RaSM_RoomCategory")] public class CategoryDto { public int Id { get; set; } public string Key { get; set; } public string Name { get; set; } //[NotMapped] //public List<SubCategoryDto> subCategoryDtos { get; set; } = new List<SubCategoryDto>(); public virtual ICollection<SubCategoryDto> SubCategories { get; set; } public override string ToString() { return Name; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; namespace RoomsAndSpacesManagerDataBase.Dto.RoomInfrastructure { [Table("RaSM_SubRoomCategory")] public class SubCategoryDto { public int Id { get; set; } public string Key { get; set; } public string Name { get; set; } public int CategotyId { get; set; } public virtual CategoryDto Category { get; set; } public virtual ICollection<RoomNameDto> RoomNames { get; set; } public override string ToString() { return Name; } } }
115e95bbfa83dc87638a50b7ac36758d3e3f8c99
[ "C#" ]
51
C#
MOneProject/RoomsAndSpacesManagerDesktop
32fded210526550ccf71d9422c2ed0ca3592b982
b0e154f25b89cdc2edeb13e63704a291b5701bff
refs/heads/master
<repo_name>NathanHarrington/NathanHarrington.github.io<file_sep>/content/posts/pdfexploder.md Title: PDFExploder - Web service to create thumbnail views of PDF documents Date: 2015-11-12 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/pdfexploder_thumbnail.gif Display a responsive web form. With the pdf uploaded by the user, generate a variety of exploded page view thumbnails like those shown below. Store the pdf and thumbnail links forever with permanent links. Live demo at http://waspho.com:8082 Written using [Pyramid](http://www.pylonsproject.org/) and [deform](https://github.com/Pylons/deform) Available on [GitHub](https://github.com/WasatchPhotonics/PDFExploder) <file_sep>/content/posts/pyinstaller_and_appveyor.md Title: Pyinstaller and filenames requiring .py extensions, on appveyor Date: 2016-12-08 Category: articles Tags: wasatch photonics With a code base that builds with pyinstaller on a Windows 10 Home system, and on appveyor. For example: [Dash 75dd852554](https://github.com/WasatchPhotonics/Dash/tree/75dd8525541cc5f55a73bce91884628324e2776b) Run a pyinstaller script like: pyinstaller --distpath=scripts/built-dist --workpath=scripts/work-path --noconfirm --clean --icon dash/assets/uic_qrc/images/DashIcon.ico --specpath scripts scripts/Dash.py On Windows 10 Home and premium, you will see a succesful build. On appveyor, you will see lines like: ... 493882 INFO: Building PKG (CArchive) out00-PKG.pkg 494023 INFO: Bootloader c:\miniconda\envs\conda_dash\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe 494023 INFO: checking EXE 494023 INFO: Building EXE because out00-EXE.toc is non existent 494023 INFO: Building EXE from out00-EXE.toc ... Change the Dash.py filename to Dash, and rebuild with the command: pyinstaller --distpath=scripts/built-dist --workpath=scripts/work-path --noconfirm --clean --icon dash/assets/uic_qrc/images/DashIcon.ico --specpath scripts scripts/Dash Windows 10 Home will still build fine. The appveyor build will break however, with the message below: ... 90423 INFO: Building PKG (CArchive) out00-PKG.pkg Traceback (most recent call last): File "c:\miniconda\envs\conda_dash\lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\miniconda\envs\conda_dash\lib\runpy.py", line 72, in _run_code exec code in run_globals ... code = get_code_object(nm, pathnm) File "c:\miniconda\envs\conda_dash\lib\site-packages\PyInstaller\building\utils.py", line 545, in get_code_object co = _load_code(modname, filename) File "c:\miniconda\envs\conda_dash\lib\site-packages\PyInstaller\building\utils.py", line 521, in _load_code assert loader and hasattr(loader, 'get_code') AssertionError This happens in a wide variety of contexts, with various indicators pointing back to the lack of the .py extension being an issue: [Github issue](https://github.com/pyinstaller/pyinstaller/issues/2093) [SO Discussion](http://stackoverflow.com/questions/37951808/pyinstaller-assertion-error-used-to-work-fine-now-it-doesnt) This can be particularly insidious to track, as you'll spend most of the time searching the git diffs for file <i>content</i> changes, instead of file extension changes. <file_sep>/content/patents/patent_8,918,383.md Title: Vector Space Lightweight Directory Access Protocol Data Search Date: 2014-12-23 template: patent patent_number: 8,918,383 A computer-implemented method, apparatus, and computer program product for performing a search for data. In one embodiment, the process converts each character of the search query into a phonetic variant to form an inflected search query. The process then identifies a set of inflected data fields of a vector space library satisfying the inflected search query. <file_sep>/content/posts/wasatch_bluegraph.md Title: bluegraph - high speed graphing and logging with guiqwt and zmq. SVG blueness in pyqt Date: 2015-12-11 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/bluegraph_thumbnail.gif This is a rewrite of the old 'ExtendedTest' interface. You can see a demonstration of this interface as part of Wasatch Photonics [Long Term Laser Test](https://drive.google.com/file/d/0B9a4-za84QgLX202TWpqMVJvalU/view?usp=sharing) setup shown below. [![Long Term Laser Test](/images/wasatch-images/wasatch_long_term_laser_test.png)](https://drive.google.com/file/d/0B9a4-za84QgLX202TWpqMVJvalU/view? usp=sharing) Also used as part of the Wasatch Photonics [Griddle](https://drive.google.com/file/d/0B9a4-za84QgLbVl5cUtsY3M0UFk/view?usp=sharing) spectrometer quality verification system. [![Griddle](/images/wasatch-images/wasatch_griddle_demo.png)](https://drive.google.com/file/d/0B9a4-za84QgLbVl5cUtsY3M0UFk/view?usp=sharing) Check the details on [GitHub](https://github.com/WasatchPhotonics/BlueGraph) <file_sep>/posts/stage-four-value-propositions.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>Stage Four: Value Propositions - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="/posts/stage-four-value-propositions.html"> <meta name="author" content="<NAME>" /> <meta name="keywords" content="business model canvas" /> <meta name="description" content="Fourth Stage: Value Propositions Research of known effective materials: Udacity course: How to Build a Startup, Lesson 5: Value Propositions All sections 1 - 27 Strategyzer: 10 Characteristics of a great Value Proposition checklist Strategyzer: Sell Your Colleagues on Value Proposition Design Strategyzer: Value Proposition Design book Preview Incorporation: Card deck …" /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="article"/> <meta property="og:title" content="Stage Four: Value Propositions"/> <meta property="og:url" content="/posts/stage-four-value-propositions.html"/> <meta property="og:description" content="Fourth Stage: Value Propositions Research of known effective materials: Udacity course: How to Build a Startup, Lesson 5: Value Propositions All sections 1 - 27 Strategyzer: 10 Characteristics of a great Value Proposition checklist Strategyzer: Sell Your Colleagues on Value Proposition Design Strategyzer: Value Proposition Design book Preview Incorporation: Card deck …"/> <meta property="article:published_time" content="2017-09-22" /> <meta property="article:section" content="articles" /> <meta property="article:tag" content="business model canvas" /> <meta property="article:author" content="<NAME>" /> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li class="active"> <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <article> <div class="entry-content"> <p>Fourth Stage: Value Propositions</p> <p><strong>Research of known effective materials:</strong></p> <p>Udacity course: How to Build a Startup, Lesson 5: <a href="https://classroom.udacity.com/courses/ep245/lessons/48745133/concepts/482999050923">Value Propositions</a></p> <p>All sections 1 - 27</p> <p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/10-characteristics-of-great-value-propositions-checklist.pdf">10 Characteristics of a great Value Proposition checklist</a></p> <p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/sell-your-colleagues-on-value-proposition-design.pdf">Sell Your Colleagues on Value Proposition Design</a></p> <p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/value-proposition-design-book-preview-2014.pdf">Value Proposition Design book Preview</a></p> <hr> <h4>Incorporation:</h4> <p><strong>Card deck 1 of 6 INTRO</strong></p> <pre> Chapter 1. Value Proposition What product or service are you building, for who, and what does it solve for those people? It's about satisfying a customer need, not just you thinking: "What a great idea". Chapter 4. COMPONENTS 1. The features of your products and services. 2. What gain are you creating for customers? 3. What pain are you solving for them? The goal is the smallest possible feature set that solves these pains and creates these gains for the customer. That is the Minimally Viable Product. Chapter 9. PRODUCT Which are part of your value proposition? -manufactured goods, commodity product... Which intangible products are part? -copyrights, licenses... Which financial products? -financial guarantees, insurance policies... Which digital products? -mp3 files, ebooks.... The product is the whole package of all the above Chapter 10. SERVICES Which core services are part of the value proposition? -Consulting, a haircut, investment advice... Which pre-sales or sales services? -help finding right solution, financing, free-delivery Which after-sales services? -free maintenance, disposal... What is it that your product features do? </pre> <p><a href="/images/learning/learning_value_proposition_intro_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_intro_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_intro_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_intro_card_deck_back.jpg"></a></p> <hr> <p><strong>Card deck 2 of 6 PAIN</strong></p> <pre> PAIN KILLERS What are you going to reduce or eliminate for the customer? Chapter 12. PAIN Questions: Produce savings? Time, money, effort Feel better? Frustration, annoyance, headaches Fix solutions? New features, better, faster End challenges? Easier, eliminate resistance? Impact social consequences? wipe out negative social consequences or add to social status? Eliminate risk? Financial, social or technical risk Chapter 14. PAIN Importance Rank each pain according to its intensity and frequency </pre> <p><a href="/images/learning/learning_value_proposition_pain_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_pain_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_pain_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_pain_card_deck_back.jpg"></a></p> <hr> <p><strong>Card deck 3 of 6 GAIN</strong></p> <pre> GAIN CREATORS What are the benefits the customer expects, desires or is surprised by? Chapter 15. GAIN Questions Happy customers? Save time, save money, save effort Better outcomes? Higher quality, more or less of something Exceed current solutions? Features, performance, quality Job or life easier? Create positive consequences? Social (need), business (more sales) Chapter 16. GAIN Importance Rank each gain your product and services create according to its relevance to the customer. </pre> <p><a href="/images/learning/learning_value_proposition_gain_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_gain_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_gain_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_gain_card_deck_back.jpg"></a></p> <hr> <p><strong>Card deck 4 of 6 MVP </strong></p> <pre> Chapter 19. MVP Definition The first instance of your product or service that is delivered to customers. What is it that customers tell us that they will pay for or use right now. It is not a beta, tell customers it is the MVP. Chapter 17. MVP Physical Always invest a day or two building a physical product mockup. Something that customers can see and touch. Chapter 18. MVP Webmobile Build a "low fidelity" app or website to test the problem. This helps you avoid building products no one wants. Chapter 21. The art of the MVP It's based on interaction and iteration and understanding customers jobs, pains and gains. For new markets, don't ask about features, ask "How do they spend their time?" </pre> <p><a href="/images/learning/learning_value_proposition_mvp_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_mvp_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_back.jpg"></a></p> <hr> <p><strong>Card deck 5 of 6 META-Value Prop</strong></p> <pre> Chapter 22. COMMON MISTAKES It's just a feature of someones else's product "It's nice to have" instead of "got to have" Not enough customers care Chapter 23. QUESTIONS: Competition: What do customers do today? Make BMC's for the competition. Technology / Market Insight: Why is the problem so hard to solve? Why is the service not being done by other people? Market size: How big is this problem? Product: How do you make it once you understand the customer needs? Chapter 24: TWO FORMS: Technology insight: Typically applies to hardware, clean tech and biotech. Market insight: Changes in how people work, live, interact and what they expect. Both forms need to solve pains and create gains for the customer. Chapter 25: TYPES Technology Market More efficient lower cost better distribution smaller simpler better bundling faster better branding combine technology and market insights for the sweet spot of value propositions. </pre> <p><a href="/images/learning/learning_value_proposition_meta_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_meta_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_meta_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_meta_card_deck_back.jpg"></a></p> <hr> <p><strong>Card deck 6 of 6 Examples</strong></p> <pre> Technology Insights Ayasdi - topological analysis, solved previously unapproachable problems Inscopix - smaller fluorescence microscope - created new market Market insights Zynga - play more involved games - facebook distribution Twitter - micro-blog more than blog - solved a need JERSEYSQUARE Pains: cheaper way to wear jersey, eliminate risk of owning traded player Gain: provide alternative to purchasing counterfeit jersey Features: single place to rent sports jerseys MVP: website with rental and stock of jerseys OmegaChem Pain: non-renewable petroleum derived feedstock for surfactant industry Gains: Sustainable, bio-based replacement. Higher performance Improved cold temperature tolerance of detergents Features: Bi-functional molecules Flexibility in chain length MVP: chem-mix blue feedstock in 50-gal drums </pre> <p><a href="/images/learning/learning_value_proposition_examples_card_deck_front.jpg"><img alt="Front of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_examples_card_deck_front.jpg"></a> <a href="/images/learning/learning_value_proposition_examples_card_deck_back.jpg"><img alt="Back of Card Deck" src="/images/learning/thumbnails/learning_value_proposition_examples_card_deck_back.jpg"></a></p> <hr> <h2>Execution:</h2> <p>Lessons learned:</p> <p>36 cards with about double the total content of any previous learning stage. Still took linear amounts of time to memorize when grouped into individual card decks. Re-merged with randomization for surprisingly no impact to time required for memorization and incorporation.</p> <p>Now making a new set of business model canvases for various problems I'm working on with these better value proposition ideas.</p> <p>The creation of these bmfiddles is showing many new frustrations and lack of clarity. Especially around the value propositions and customer segments - looking at others briefly from the udacity materials, then will recreate full BMC's for practice. Excellent - that instantly shows you were confused about what goes in the customer segment box. It's the persona, not the matching pains and gains. So execute a series of bmfiddles based on teh various ideas you are working on that include:</p> <ol> <li>A pain solved for customer</li> <li>A gain created for customer</li> <li>Features for pain solved and/or gain created</li> <li>mvp</li> </ol> <p><a href="/images/learning/rain_bmc.png"><img alt="Example BMC" src="/images/learning/thumbnails/rain_bmc.png"></a> <a href="/images/learning/noise_machine_app.png"><img alt="Example BMC" src="/images/learning/thumbnails/noise_machine_app.png"></a> <a href="/images/learning/triangle_innovation.png"><img alt="Example BMC" src="/images/learning/thumbnails/triangle_innovation.png"></a> <a href="/images/learning/data_science_matcher.png"><img alt="Example BMC" src="/images/learning/thumbnails/data_science_matcher.png"></a></p> <div class="panel"> <div class="panel-body"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2017-09-22T00:00:00-04:00"> Fri 22 September 2017</time> </span> <span class="label label-default">Tags</span> <a href="/tag/business-model-canvas.html">business model canvas</a> </footer><!-- /.post-info --> </div> </div> </div> <!-- /.entry-content --> </article> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/content/developerworks/os-userauth-mouse.md Title: Expand your user-authentication options with mouse dynamics Date: 2008-11-25 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-userauth-mouse Use Perl, cnee, and custom algorithms to measure how specific users move the mouse and click buttons. In this article, we discuss how mouse-click hold times, or a combination of keyboard and mouse activity can enable new levels of access-requirements obfuscation. Learn how to apply the open source tools cnee and Perl in applications to measure the characteristic attributes of how users manipulate the mouse. <file_sep>/images/learning/bmfiddle_icons/uniicons/bmfiddle_resource_mailer.sh #!/bin/bash # # bmfiddle_resource_mailer.sh located in: # nathanharrington.github.io/content/images/learning/bmfiddle_icons/uniicons # # Assumes a fully functional mutt configuration. # # Usage: cd to the directory above (with all the folder? entires) # # run the script lke: ./bmfiddle_resource_mailer.sh CANVASID # if [[ $# -eq 0 ]] ; then echo 'You must specify a bmfiddle CANVASID' exit 0 fi CANVASID="$1" EMAIL=<EMAIL> COUNTER=1 while [ $COUNTER -lt 11 ]; do echo "Mail folder$COUNTER group" FILES=$( printf -- '-a %q ' folder${COUNTER}/*.png ) mutt $EMAIL -s 'PNGs ${COUNTER} of 10' $FILES < /dev/null # Change intervals for primitive spam avoidance sleep $COUNTER let COUNTER=COUNTER+1 done <file_sep>/content/pages/gnupg_key.md Title: GPG Key status: hidden Please consider [<NAME>'s comments](http://www.red-bean.com/kfogel/public-key.html) regarding GPG communications. KeyID: F2B4DDFB Key fingerprint = 1<KEY> -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.6 (GNU/Linux) m<KEY> YmBISL57ihl1oYLQ4gcKWAW<KEY>4wWG OWwaxRhdvuSc4Lyr4H1vdJWiVBO9Tp6RiEYEGBECAAYFAjxZSBQACgkQ9gLegvK0 3fvBwgCgiJykVjMRknmll3g7QkzPro0NNdQAmwR+O5AsbT8YjNKt9rqzZoykBATm =YLP+ -----END PGP PUBLIC KEY BLOCK----- <file_sep>/content/developerworks/os-perlgdchart.md Title: Create custom data charting tools using Perl and GD Date: 2007-04-24 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-perlgdchart Create custom data charting tools using Perl and GD, Create professional-looking charts for data visualization using Perl and GD. Move beyond standard pie charts to incorporate annotations, indicators, and layering for enhanced informational delivery. <file_sep>/content/developerworks/os-sndpeek.md Title: Identify speakers with sndpeek Date: 2008-04-15 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-sndpeek Identify speakers with sndpeek, Use sndpeek and custom algorithms to match voices to a pre-recorded library. Create applications to let you know who is speaking in teleconferences, podcasts, and live media events. Build basic assistance programs to help the hearing-impaired identify speakers in a bandwidth-limited context. Demonstration video at [youtube](https://www.youtube.com/watch?v=KRtBKmNUjug).com <file_sep>/content/developerworks/os-whistle.md Title: Control your computer with tones and patterns Date: 2007-01-09 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-whistle Use Linux or Microsoft Windows, the open source sndpeek program,and a simple Perl script to read specific sequences of tonal events - literally whistling, humming, or singing at your computer -- and run commands based on those tones. Give your computer a short low whistle to check your e-mail or unlock your your screensaver with the opening bars of Beethoven's Fifth Symphony. Whistle while you work for higher efficiency. O'Reilly Radar Release 2.0 ['magic'](http://radar.oreilly.com/2007/06/are-we-magicians.html) link. Coverage and comments from [Lifehacker](http://lifehacker.com/271755/whistle-to-control-your-computer) Interesting implementation example at: [perlmonks.org](http://www.perlmonks.org/?node_id=594335) Demonstation video of raising and lowering windows on [youtube](https://www.youtube.com/watch?v=R1gkdILzA_s) IBM developerWorks [podcast](/files/podcasts/twodw-1-9-07.mp3) with [<NAME>](http://scottlaningham.com). <file_sep>/content/developerworks/os-wirelesssitesurvey.md Title: Take your ThinkPad out for a walk to create wireless site surveys. Date: 2008-02-12 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-wirelesssitesurvey Use the accelerometer embedded in a ThinkPad to record your movements while monitoring your network connectivity. Use custom algorithms to extract footstep features from the recorded data, then automatically plot signal strengths on a floor-plan map to determine the best areas of coverage. <file_sep>/content/developerworks/os-viseffects.md Title: Real time visual effects Date: 2006-01-17 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-viseffects Use EffecTV and Simple DirectMedia Layer (SDL) to create your own real-time visual effects on live video. Learn how to integrate geometric primitives, bitmap image loading, and simple motion tracking to create your own games, leading-edge user interfaces, or immersive environments. Explore the EffecTV and SDL architectures, and learn how to harness the power of open source video processing on Linux. Future versions to be published here shortly include more advanced manipulations of the video input to make interesting games. version 0.1 is a simple "ball falling down the screen game" where you have to jump around and duck and dodge. versions 0.2 adds shrinking of your image on the video screen, and occlusion of your head with funny images. <file_sep>/images_README.md Generate the thumbnails by: cd thumbnails pwd # Make sure you are in the thumbnails directory! cp ../*.jpg . morgrify -resize 200x200 *.jpg <file_sep>/content/posts/wasatch_microangio.md Title: MicroAngio - Demonstration interface for the MicroAngio UX project. Date: 2016-05-19 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-38-26.png Clickable, navigatable demonstration of the new user experience design for OCT Angiography. No actual OCT processing is included. See the screenshots below for more detail. One of the primary goals of this system was to create a 'live' demo for faster iteration of design concepts. This demo was based on the [PySideApp](https://github.com/WasatchPhotonics/PySideApp) Uses QT Designer (Qt4), and various styles, layouts and layering to get the desired effects, with much better portability than previous iterations. The [BlueGraph](http://github.com/WasatchPhotonics/BlueGraph) techniques, for example, were heavily influenced by GraphicsView systems with layered SVG controls, that had embedded PNGs. This was fast, and would let you do various graphics effects, at the expense of development time. [![RAW Capture](/images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-37-53.png)](/images/wasatch-images/microangio_screenshots/Screenshot_2016-04-28_09-37-53.png) [![RAW Setup](/images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-38-11.png)](/images/wasatch-images/microangio_screenshots/Screenshot_2016-04-28_09-38-11.png) [![OCT Capture](/images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-38-16.png)](/images/wasatch-images/microangio_screenshots/Screenshot_2016-04-28_09-38-16.png) [![Angio Setup](/images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-38-22.png)](/images/wasatch-images/microangio_screenshots/Screenshot_2016-04-28_09-38-22.png) [![Angio Capture](/images/wasatch-images/microangio_screenshots/thumbnails/Screenshot_2016-04-28_09-38-26.png)](/images/wasatch-images/microangio_screenshots/Screenshot_2016-04-28_09-38-26.png) Available on [GitHub](https://github.com/WasatchPhotonics/MicroAngio) <file_sep>/content/patents/patent_8,175,332.md Title: Upper troposphere and lower stratosphere wind direction, speed and turbidity monitoring using digital imaging and motion tracking Date: 2012-05-08 template: patent patent_number: 8,175,332 The visible sky is monitored by a set of cameras for contrails produced by a high-altitude aircraft. In response to identifying a contrail, the contrail is tracked across the field of view of the camera. Contrail data generated when the contrail is identified and during the tracking of the contrail is stored. The contrail data describes characteristics of the contrail including the spread of the contrail and the movement of the contrail across the field of view of the camera. Coordinates of the high-altitude aircraft are determined and compared with the contrail data to identify wind conditions. <file_sep>/content/posts/wasatch_signing_drivers.md Title: Signing Drivers - Windows 10 and Cypress FX2/FX3 USB Date: 2016-10-17 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/win8_unsigned_inf.png 2016-09-14 16:53 signed windows 10 drivers: The best resource for this process is clearly <NAME>sons [Practical Windows Code and Driver Signing](http://www.davidegrayson.com/signing/) Here are the refined points in that article for aparticular use case: Windows 7 and greater. Installing a driver package without loading a kernel module. ------------- 1. Go to [GlobalSign](https://www.globalsign.com/en/code-signing-certificate/). Use their challenging interface to sign up for the "Code Signing" product. This costs about $219. Do this first as they then have to "verify your identity". For [Wasatch Photonics](http://wasatchphotonics.com), this meant calling us on the phone and telling us that we needed to provide more documentation that we were a real company. This is after I pointed them to the our [NC official records](https://www.sosnc.gov/Search/filings/9737537) showing our phone number. I had to suggest we would move to a competitor certificate service provider before things started to progress. After this is complete, download the .pfx file into the same directory as the drivers to sign. This is the most difficult and time consuming part of the process. 2. Download and install the [Windows Driver Kit](https://developer.microsoft.com/en-us/windows/hardware/windows-driver-kit) 3. Use your INF files of choice. We modified the provided [Cypress FX2/FX3 Drivers](http://www.cypress.com/knowledge-base-article/drivers-ez-usb-fx1-fx2lp-and-fx3-kba94413). 4. Modify the INF files to include your custom Vendor ID and Product ID: %VID_04B4&PID_1000.DeviceDesc%=CyUsb3, USB\VID_04B4&PID_1000 5. Convert the modified INF file into a CAT file: > "C:\Program Files (x86)\Windows Kits\10\bin\x86\inf2cat" > /v > /driver:%~dp0 > /os:XP_X86,Vista_X86,Vista_X64,7_X86,7_X64,8_X86,8_X64,6_3_X86,6_3_X64,10_X86,10_X64 6. From David's instructions: "Be sure to install GlobalSign's R1-R3 cross-certificate on the computer that will be making signatures." This means download the r1cross.cer right click it and select "install certificate", then accept all the defaults. 7. Then run the command to actually sign the drivers: > "C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool" > sign > /v > /f <your pfx file> > /p <password> > /n "<PASSWORD>" > /fd sha1 > /tr http://timestamp.globalsign.com/?signature=sha2 > /td sha256 > cyusb3.cat 8. Then copy the signed files (minus the PFX key and instructions) to the INF_DRIVERS folder distributed as part of the installer build. And example below is included for InnoSetup > Filename: "pnputil"; Parameters: "-i -a > ""{app}\stroker_drivers\Win10\cyusb3.inf"" "; > StatusMsg: "Installing WP drivers (this may take a few seconds) ..."; > Flags: runhidden > <file_sep>/content/patents/patent_8,138,890.md Title: Hybrid ultrasonic and radio frequency identification system and method Date: 2012-03-20 template: patent patent_number: 8,138,890 A radio frequency identification system and method includes a tag reader and radio frequency identification tag. The tag reader includes an ultrasonic transducer capable of transmitting tones at selected ultrasonic frequencies and a radio transmitter capable of transmitting signals at selected radio frequencies. The tag reader includes a radio receiver capable of receiving signals at selected radio frequencies. The tag reader determines if a received radio frequency signal is modulated at a selected ultrasonic frequency. The radio frequency identification tag includes an array of combination resonator/reflectors. Each combination resonator/reflector of the array includes an ultrasonic resonator coupled to a radio reflector. Each resonator/reflector of the array is tuned to a unique pair of selected ultrasonic frequencies and selected radio frequencies. <file_sep>/content/developerworks/os-weathermaps.md Title: Precipitation proximity alerts using WSR-88D radar data. Date: 2007-06-05 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-weathermaps Traditional weather reports will give notice of vague forecasts and severe weather alerts in your general area. The code and tools presented in this article will allow you to create precise detection zones so you can receive a page, SMS, or e-mail a few minutes before a precipitation event is likely to occur at the monitored location. Use GD and Perl for image processing of the NOAA WSR-88D radar data to create your own precipitation alerts for precise areas. Choose your notification method and let users know when the rain will begin and when it will clear. <file_sep>/content/developerworks/os-linuxthinkpad.md Title: Frustration communication for your linux laptop Date: 2006-11-07 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-linuxthinkpad Frustration communication for your linux laptop, Modify the kernel to automatically reset your linux laptop when shaken during a kernel panic. Implement a shake detection algorithm in the kernel and user space to perform automatic shutdowns and restarts when certain kinetic conditions are met. Place your computer on the leading edge of cathartic interfaces. Video on [youtube](https://www.youtube.com/watch?v=6bVGPFLsMcM) <file_sep>/content/developerworks/os-78414-firefox-flash.md Title: How to ungrab Firefox hotkeys from Flash players Date: 2008-12-16 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-78414-firefox-flash Flash players and other embedded applications in Firefox require their own hooks for keyboard and mouse input. For years, Flash has grabbed Firefox keypresses, which stops people from using the keybo ard for navigation, creating new tabs, or even exiting the Flash focus. Learn how to creat e a Perl program that communicates with a Firefox extension and cnee to restore your keyboard functionality. <file_sep>/content/posts/svg_icons_and_windows7.md Title: SVG icons in PySide on Windows 7 Date: 2016-12-20 Category: articles Tags: wasatch photonics Your application icons look great. They are saved in .svg format, loaded into Qt Designer, and distributed with pyinstaller as resource files. Except on windows 7. No error messages, no crashes, no information on why the icons are missing. The issue is the included qsvg4.dll distributed with the application by pyinstaller. It appears to be the wrong file. On your development windows machine, you see the following qsvg4.dll files: ![qsvg4.dll Locations](/images/wasatch-images/qsvg4_locations.png) Not all 22KB files are the same. Look at the file sizes in detail: ![qsvg4.dll sizes](/images/wasatch-images/qsvg4_sizes.png) You must use the 22,016KB version in the runtime distributable. No amount of pyinstaller machinations, includes, or path updates seem to make this possible. You must overwrite the pyinstaller included file at the location: <program files>\<application name>\qt4_plugins\imageformats\ With the qsvg4.dll file that is 22,016KB in size. In [Dash](http://github.com/WasatchPhotonics/Dash), this is done by a directive in the InnoSetup installation file, after the application has been installed. When using appveyor, make sure the environment names match precisely, as you are hard-coding file locations such as: Source: "C:\Miniconda\envs\conda_dash\Library\plugins\imageformats\qsvg4.dll"; \ DestDir: "{app}\dash\qt4_plugins\imageformats"; Flags: recursesubdirs ignoreversion <file_sep>/content/posts/windows_software_test.md Title: Long term testing of windows software in virtualbox Date: 2016-12-01 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/dash_software_test_thumbnail.jpg Requirements: Ensure that the software is stable. Specifically, run the software for weeks, verify that the RAM, CPU and disk usage behaves predictably. Ensure there are no crashes. Prevent windows from invalidating the process by rebooting due to windows updates. The steps below were followed for creating multiple machines running rolling deployments of builds from appveyor for the Dash development testing. The flowchart on this page: [TechNet Licensing](https://technet.microsoft.com/en-us/library/dd981009.aspx) mentions a 120 day grace period. Make sure you add a reminder to rebuild the virtual machines from scratch every 100 days. Procedure: High memory host computer running Fedora Core 24. Guest OS installations of Windows 10, using default parameters in VirtualBox. These systems were built with a NAT network and 2GB RAM each. Start each guest OS, make sure it updates a few times. Set it to auto login. On the Host OS: VBoxManage.exe setextradata "VM-Name" CustomVideoMode1 1920x1080x32 On the Guest OS: Open network adapter properties, change the IpV4 TCP settings to have the DNS point to 10.10.10.10. This way numerically addressed network locations will still function, but windows update will not be able to reach it's servers. This is used to permit mapping of local samba shared where the rolling builds are stored. Map the network drive by IP address. Install [rainmeter](https://www.rainmeter.net/) Use the [Visual Chunk](http://bonsewswesa.deviantart.com/art/Visual-Chunk-1-7-643176812) skin. Place the controls for: SysStats one drive, no power All uptime, rca, tbt, 24hour Set both control groups to Position->Stay Topmost "Choose when to turn off the screen" -> Never Change the display resolution to 1920x1080 Do not use this 'root image'. Make clones of this image. Do not re-initialize the MAC address of each adapter, or you will have to change the DNS entry for each virtual machine as described above. Every day, record the eyeball-averaged readings from the rainmeter display on each guest OS. This is rough, but what you are looking for here is a lack of dramatic changes. What does that look like at Wasatch? ![Dash Software Test](/images/wasatch-images/dash_software_test.jpg) <file_sep>/content/posts/gource_visualizations.md Title: Gource visualizations of source code repositories Date: 2016-10-27 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/dash_gource.gif [gource](http://gource.io/) creates truly outstanding source code development visualizations. Here's the workflow for demonstrating the collaboration over years, without some of the default details. The commands below are designed to produce the visualizations to show collaboration and general activity levels, as well as produce animated gifs and smaller sets of imagery designed for presentations. ./gource ~/wasatch/Software/Dash3 --title "Dash Development" --seconds-per-day 0.01 --file-filter "(famfam|png|jpg|bmp|xcf)" --hide dirnames,filenames,usernames --file-extensions --key -o dash_withkey_gource.ppm Dash version 3 has a set of unique attributes that tend to limit the usefulness of a gource visualization. The command line switches above compensate for: A 5 year set of data (seconds-per-day) Many image files, frequently modified (file-filter) Long file and directory names that do not expire (hide, file-extensions) Show just the key with (key), and save the results to a ppm file. Then the conversion to a video: ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i dash_withkey_gource.ppm -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 dash_withkey_gource.mp4 And finally a conversion to a thumbnail animated gif: ffmpeg -i ../dash_withkey_gource_2015.mp4 -r 5 'frames/frame-%03d.jpg' convert -resize 25% -delay 10 -loop 0 \*.jpg dash_gource.gif If you run through the instructions above verbatim, you will have something close to a 1GB ppm file, a 600MB mp4, and .gif file totally approximately 10GB. To cut that down to something manageable for the web, run: Gource conversion to a ppm with one year of data: ./gource ~/wasatch/Software/Dash3 --title "Dash Development" --seconds-per-day 0.01 --file-filter "(famfam|png|jpg|bmp|xcf)" --hide dirnames,filenames,usernames --file-extensions --key --start-date '2015-01-01' --stop-date '2016-01-01' -o dash_withkey_gource_2015.ppm Conversion to an mp4: ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i dash_withkey_gource_2015.ppm -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 dash_withkey_gource_2015.mp4 Extract each frame into a jpg: mkdir frames ffmpeg -i ../dash_withkey_gource_2015.mp4 -r 5 'frames/frame-%03d.jpg' Shrink and combine into an animated gif: cd frames convert -resize 25% -delay 10 -loop 0 *.jpg dash_gource.gif <file_sep>/content/developerworks/os-gimpmap.md Title: Map people, places and relationships inside a building. Date: 2007-08-14 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-gimpmap Google and MapQuest do a great job of creating maps of the outside world on the fly. But what about our workspaces? This article shows how to define and map places and people inside a building. Search, track, and plot individual cubicles, rooms, employees, or assets. Graph the location of individuals or groups of employees based on job function, or track unused office space visually. <file_sep>/content/posts/libusb_pyinstaller_appveyor.md Title: LibUsb backends using pyinstaller and appveyor Date: 2016-12-21 Category: articles Tags: wasatch photonics With a development machine all set up for communicating in python with pyusb and libusb on Windows 10. The signed drivers are available, the device is communicating on the build machine. Building the installer on the development machine also is successful. Redistributing the installer built on the development machine delivers the expected experience. The problem is when building on a [Continuous Integration](http://www.appveyor.com) environment. PyInstaller builds an exe. InnoSetup builds a distributable installer. The installer is succesful. Then when running the installed application, you'll see the message: Traceback (most recent call last): ... File "site-packages\usb\legacy.py", line 353, in busses File "site-packages\usb\core.py", line 1263, in find usb.core.NoBackendError: No backend available There are many subtle differences between a typical windows 10 build environment and the Appveyor configuration. Here are the changes required to have an installer built on appveyor: In setup.py, manually include pyusb: requires = [ "pytest-qt", ... "pyusb", ] In appveyor configuration, manually include pyusb: install: - "set PATH=%MINICONDA%;%MINICONDA%\\Scripts;%PATH%" ... - pip install pyusb Straightforward to this point. Sure, appveyor should respect the setup.py requirement of pyusb, but for some reason it's not listed in conda list and pip freeze post install section. The workaround is to specify it manually. Again, this works on the windows 10 development machine, but not on appveyor. The no backend available message is still present, but only on the appveyor install. Further googling of the error message shows that this problem has already been [fixed](https://github.com/pyinstaller/pyinstaller/issues/1891). Thanks! So all you need now is the development version of pyinstaller. Instructions say to install the development version of pyinstaller that includes the new usb hook like so: (In appveyor.yml) - pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip The above will cause a +<commit hash> to appear in the pyinstaller version suffix. This in turn will cause a ValueError when pyinstaller is run. But only on appveyor: Traceback (most recent call last): File "C:\Miniconda\envs\conda_dash\Scripts\pyinstaller-script.py", line 6, in <module> from pkg_resources import load_entry_point File "C:\Miniconda\envs\conda_dash\lib\site-packages\pkg_resources.py", line 2850, in <module> working_set.require(__requires__) File "C:\Miniconda\envs\conda_dash\lib\site-packages\pkg_resources.py", line 696, in require needed = self.resolve(parse_requirements(requirements)) File "C:\Miniconda\envs\conda_dash\lib\site-packages\pkg_resources.py", line 566, in resolve requirements = list(requirements)[::-1] # set up the stack File "C:\Miniconda\envs\conda_dash\lib\site-packages\pkg_resources.py", line 2650, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "C:\Miniconda\envs\conda_dash\lib\site-packages\pkg_resources.py", line 2628, in scan_list "Expected ',' or end-of-list in",line,"at",line[p:] ValueError: ("Expected ',' or end-of-list in", 'PyInstaller==3.3.dev0+483c819', 'at', '+483c819') The fix is to strip out the commit hash suffix from the installed version number. Run setup.py with sdist first to insert just the major version number without the commit hash suffix. - pip uninstall -y pyinstaller - git clone https://github.com/pyinstaller/pyinstaller.git - cd pyinstaller - python setup.py sdist - python setup.py install - cd .. This is still not enough. You'll need to include the libusb dll for use by the application. In the InnoSetup configuration file, include the line: Source: "support_files\libusb_drivers\x86\libusb0_x86.dll"; \ DestDir: "{app}\dash\"; Flags: recursesubdirs ignoreversion <file_sep>/content/developerworks/os-keystroke.md Title: Expand your text entry options with keystroke dynamics Date: 2007-12-04 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-keystroke Measure the total time of entry and verify the time between keystrokes to help authenticate a user regardless of the data being entered. Require nonprintable characters, such as backspace and break, in the password to enable new levels of password obfuscation. Learn how to apply the open source tools xev and Perl in keystroke dynamics to measure the more-subtle characteristics of human-computer interaction. <file_sep>/content/pages/about.md Title: About The best way to contact me is through <EMAIL>. Full resume available here: [<NAME>ton Resume RTF](/files/NathanHarrington_Resume.rtf) You can send me encrypted messages using the following: [public key](/pages/gpg-key) You can also reach me by phone at (919) 267-3558 <file_sep>/content/posts/parallella_foreman.md Title: Adapteva Parallella Screener (The Foreman) Date: 2015-08-17 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/foreman_thumbnail.png Wasatch Photonics uses [Adapteva Parallella](http://www.adapteva.com/parallella/) SKU P1601-DK03's as an embedded linux system. Core capabilities required include a USB bus that is available at least 83% of the time on boot up. A [screener](https://github.com/WasatchPhotonics/Foreman) was created to allow us to find the incoming Parallella boards that meet this level of usb availability. This setup consists of 4 Parallella DC adapters connected to a Phidgets software controlled relay. This relay turns on the devices for 35 seconds, issues a 'lsusb' command on each device, and stores the status of the usb availability. The device is then turned off for 75 seconds, then the process is repeated. Available on [GitHub](https://github.com/WasatchPhotonics/Foreman) The forum post is really a great reminder of what not to do when documenting a problem: [USB Issues](https://parallella.org/forums/viewtopic.php?f=50&t=1650&start=40#p13290) You can't just present the data and expect any change. Remember that just because the data is there doesn't mean people will actually read the post, or make any changes. Use this tool to summarize the data into readable graphs: <img src="/images/wasatch-images/foreman_screenshot.png"/> <file_sep>/content/developerworks/os-ldap1.md Title: User Perl and a regular-expression generation to search and display LDAP data (part 1) Date: 2007-02-20 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-ldap1 Use Perl and a regular-expression generator to search for and display LDAP database records (part 1), Find out how to use Perl and a regular-expression generator to search and display records from your Lightweight Directory Access Protocol (LDAP) database using simple keyword-type searches. Search and process your LDAP data without knowing precisely which field the data is in or how it is formatted. Part 2 of this "LDAP search engines" series introduces scoring and metaphone suggestions to the code. IBM developerWorks [podcast](/files/podcasts/twodw032007.mp3) with [<NAME>](http://scottlaningham.com) <file_sep>/content/developerworks/os-linuxmusic.md Title: Monitor your computing environment with machine generated music Date: 2006-11-14 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-linuxmusic Monitor your computing environment with machine generated music, Use Perl and fluidsynth to create a real-time musical composition of your system status. Learn how to integrate various system monitoring data into a harmony producing, midi controlled audio synthesis. Explore audible information methods and configurations to help you monitor and manage your computing environment. Local cached text Audio example with [Hammered Instruments](/files/audio/gpMax_44100_d.wav) (think dulcimer, not intoxicated saxophone), another example with [Electronic Sounds](/files/audio/sciFiExample1.wav), and another with [Simple Orchestral instruments](/files/audio/orchExample1.wav). [Slashdot](https://slashdot.org/story/06/11/15/1628216/monitor-a-linux-box-with-machine-generated-music) discussion. <file_sep>/content/pages/wasatch_work_log_timeline.md Title: Wasatch Work Log Timeline Date: 2016-10-14 Category: About save_as: pages/wasatch_work_log_timeline.html status: hidden 2016-12-14 Start of new work log schedule. Now about demonstrating results instead of documenting efforts. 2016-12-13 holiday party + rest of day. Basic simulation with integration time and laser control linkage in mains. Reset of virtualization setups to have base system with full hd, non-dns resolved network connections for windows update inhibit. Simulated temperatures and noise margins representative of integration time changes. 3fd3562 hardware capture updates with live simulation data ... 77c4e5f tests of 1-10k integration change 2016-12-13 16:30 2016-12-12 07:00 receive and process shipments for loading dock, front area. Update documentation for more efficient processing. website maintenance rule clarification. Setup of dual monitor configuration for 6 visualizations on new primary virtualization machine. VM configuration and appveyor build testing. Laser button stylesheet change. Material simulation with high fidelity noise indicators. 1c745b9 toggle laser button stylesheet change 2016-12-12 16:33 2016-12-09 07:07 performance review, scheduling updates, detailed processing and review of algorithm removal from it systems. Investigation into cigna healthcare changes. Website down detection. Startup page setting on command line. Start with laser communication and command and control queues in multiprocessing simulator. Correction of delay and non-exit with terminate and join in sub processes. afa808c shallow copy 890f1d9 non increasing copy of data d99ce88 startup setting command line ac7779e laser with record setting reading and writing fedaefc strip down of older simulatespectra test cases 2016-12-08 06:24 vtt 1000 manual discovery, it support, processing shipments. Mid-milestone demo of simulatd plug, unplug of device in dash. Determination of valid and invalid firmware configurations on test hardware. Recovery and documentation of Dash.py vs. Dash with no suffix build issue on appveyor machine. Log level case management on command line c2f61a1 recovery of dash.py for pyinstaller aea97ec tests recovered in appveyor bc936d9 case management of log level on command line 858c389 log level in controller 2016-12-08 16:31 2016-12-07 07:12 pw booth review, setup of testing systems for dark current rma validation. Dash runtime error after 2 days investigation on windows 10 and windows 7. Rebuild of appveyor configuration to isolate build flaw and executable non-inclusion. Setup of secondary virtualization system . Validation of appveyor vs. local system build differences. Log-level default to INFO, setup on executable for linux and windows. f701cc6 no tests, just build 24dcd37 dash.py renamed in appveyor builds 664aaf6 corrected log level required for windows tests 398dbbe default log level INFO, runtime assignment 2016-12-07 16:34 2016-12-06 06:42 identification and removal of algorithm storage. Year review plan, plumbing issue recovery. Search for comptabile fonts for the multiprocessing demonstration tests. Specification of data structures and api's for controlling multiple devices with multiprocessing and wasatchusb with libusb drivers, finish power control with web power switch. 195a60f style recovery 2016-12-06 16:15 2016-12-05 06:38 production meeting. adding of send routing rules inhibit to prevent name conflicts. Dash runtime error on windows 7 investigation. Configuration parser, ini file of Dash simulated device control. Testing of simulation script and demo, project planning. a2973d4 restoration of default startup 50ba7a9 name cleanup 2016-12-06 16:30 2016-12-02 06:31 attempting to decipher 401k puzzle, update historical software to support new serial numbers. Setup of new Dash long term executable checks, validation of virtualization setup. Desk reconfigure for simultaneous tests and support e7f14e9 exception handling in css styler 2a32bb3 faded gray on disconnect 0cb345f grayed graphs, stopping 68e61d4 bare bones init file read simulator for connections tatus 75dd852 lower requirements for system simulation speeds 2016-12-02 16:30 2016-12-01 06:34 addition of logging tab. removal of tabwidget which has unsupported hide tab functionality in pyside. Tests to uncover various issues with adding a handler to signal the qt interface for new log entries. Settled on a pygtail implementation with custom stackedwidget control with tab widget sytled buttons. This gets around the repaint events of signals triggered from a handler added to a logging module that has other subprocess handlers. Continued refinment of long term power cycling tests and hardware setups. e371efc test correction 8b9bc0e recover of log queue variable 0b5c9d7 bare switch between hardware and logging simulated tabs 156f848 pygtail integration in appveyor and travis and setup.py b950da7 pygtail integration to text edit control 1bd65b1 pygtail 1e9d346 showing inhibit of qt interface when logging post subprocess setup 0ad10f8 display log text crash 2fffb02 various attempts at signal logging 8a3777e removal of pyside-unsupported qtabwidget, addition of custom button solution layout 2016-12-01 16:30 2016-11-30 06:58 review demo requirements for photonics west, Detailed demo meeting with screenshots. transformation of raman testing platform. Investigation of web power switch reset mechanisms. Milestone updates for next dash demo. Selection and ordering of new testing computer components. Initiation of new test schedule to meet PW requirements. acceef5 slight interface mods 40fa949 new hardware capture layout 2c93fe7 raman capture by default 2016-11-30 17:00 2016-11-29 06:50 it asset system review and investigation. Setup of meeting and communications with customer visit. Debug and testing of csv dictreader failure in sub-process on windows. Switch to raw csv processing with context for simulated raman data. Layout of raman controls and line plots for raman setup screen. 47f690a with raw file load instead of dictreader which was causing a multiprocess exit inhibit 56392be simulated raman data 0c36f41 simulated raman data 0cb1dd6 layout of raman capture controls 8cfaf6f control to defaults for test passing 2016-11-29 18:13 2016-11-28 06:32 manufacturing meeting notes, setup of OCT sample storage area, review of power management options for failed UPS. Find headshots and email. Raman graph layout and placeholders. Addition of setup and capture navigational signals. Default geometry changes, expansion of css loading of runtime components. Multi-os verificationa nd spacing consistencies. 434b24f base level graph placeholders c7e29f7 baseline raman capture placeholder graphs 7b313be through raman capture layout 096e031 techniques in utils ... d13afbe raman setup layout tests with saved area iconagraphy dc8d6df adding controls to setup catpure 657486d partial raman setup capture 2016-11-28 16:33 2016-11-20 06:42 remote software diagnosis and support for Layne Bradley at UGA - addressed with driver signature enforcement disabling. Project planning for Dash releases to coincide with hard dates. Detailed setup and long term testing of newest build deploy level for inter-vacation testing 6700dd0 change right side control layout to have consistent width with left side saved data area da4dd83 upand down icons c7dd0bd upand down icons 6c90b6c hardware setup by defaul d5b7be6 simulated temperatures 249ee6e simulated temperatures 236793c Merge branch 'winmaster' 2da0999 corrected build ordering 2016-11-21 16:30 2016-11-18 06:13 research and location of chevelle product documentation and actual specifications and availablility. reconfiguration of remotetest system to support remote system access and portability. Isolation and correction of build compatability issues 32bit python vs. 64bit python. Put mechanisms in place to force 32bit python in documentation and build environments. Updated iconagraphy names, setup for second long term iteration pass on virtualization tester. 133deab Merge branch 'winmaster' d1578fe designer updates, uic imagery name correction 0186885 uic and designer imagery updates a1dd7cb matching 32bit build instructions ae9014c files renamed 1daf2a7 restoration of expected startup states 4f28096 building updates a22f238 documentation notes, example data 2016-11-18 16:30 2016-11-17 06:48 Interview of ME candidate. Summary of notes and review meeting with team. Sprint demo debug issues with a pure windows installation on actual hardware compared to virutal machine. Traced down to mkl_avx2 and other appveyor custom-build files. Setup virtual machine to verify installation build differentiations. Continued full development through hardware capture and setup. 0ff19b1 with minimum height b34ac5d updated instructions 81f2efb pre-local merge 38c1ac2 rebuilt to merge e5d7ac6 mkl_p4m3.dll and mkl_p4.dll 7c8ac08 mkl_avx2.dll on appveyor aa18d55 appveyor non windowed cc3e7cb temporary removal of windowed parameter for debug 0d16cec through basic hardware setup, updating iconagraphy for buttons and resources 55a6f74 placehodler iamgery 9662f45 hide interface from design time 2016-11-17 17:15 2016-11-16 06:38 bi-weekly engineering update meeting. postfix system management emails for root and non-root accounts. self assesments, mustard tree inventory search. User account management, suspension of report indicated users. Full linkage checks and border layout experiements for hardware capture portion of interface. Simulated and multi-component data. 0a0ea84 second level border removed on hardware capture details 62bb9db geometry on command line 24ba70f deep naming, through hardware capture details layout 55027bc image view included 5405d1d hard border investigation d3d88af hard border investigation 3bd7bfb partial way through hardware setup details layout conversion 55ba8fe defined devices.qrc location, hardware capture layouts 2016-11-16 16:44 2016-11-15 06:33 creation of uptime monitor trackers on cookbook replication system at linode. full reload of database and environment setup. change of firewall rules and prerequisites updates for cookbook instructions. will come back in two weeks to validate. Removal of lambda calls to address segfaults on application exits. Re-insertion of test driven concepts for interface components. 123c529 include stylesheets at runtime ead80ea updated initial state, start of hardware capture realtime graphs 968ad6e control correct close 643231c lambda removed, no more segfaults, now trying to get test control windows to exit after single tests b97f7b5 with lambda enabled 9d91a7c back to seg fault and core dump 6940773 restore of debug log print in devices 799f24d files are important 399bc06 toggle through buttons in operations with style sheets changing f8bc117 through basic load css testing in styles 65077e5 start of styles testing group aca863b populate stylesheets- segfault was in empty function return 2016-11-15 16:30 2016-11-14 06:38 Manufacturing meeting and notes. Segfault on environment reconfiguration onto zenbook with hiDpi display. Various debugging tests with strace and valgrind for isolation. Start of sytlesheet integration and read from file. 2016-11-14 17:00 2016-11-11 06:41 Deeply nested name space alterations. Start of complete build through hardware setup and capture. Full integration and commitment to current build process on appveyor. Linkage and detaile system notes for iteration cycles. Merge with agile tracking structure in asana. 4612f58 start of initial setup a9d51cd move to long polling widget dda1a00 start application maximized f6693a6 start application maximized a4c424d full screen graph layout for tests 2016-11-11 16:30 2016-11-10 06:56 Execution of linode ssd mitigation plan for cookbook failure issues at digital ocean. Start of server replication and outage monitoring setup. Noise isolation options and evaluation. Tracking of long term Dash stability metrics. Transition to longer nomenclature scheme. Testing with runtime generated widgets for saving components. Refinement of user interface complexity. Practice with deeply nested widget options 2016-11-10 16:30 2016-11-09 06:19 Remote support of incorrect board level documentation for FX2 vs. ARM customer development. Detailed evaluation of namespace testing issues and long term repurcusssions for Dash inteface. Tested with various nesting methods and custom widget development schemes. Research into common mechanisms for deeply nested widget interfaces in QT. 2016-11-09 16:30 2016-11-08 06:47 long term timing and visualization setup. Triple visualizer for windows 10, and 7 in place. Built version of Dash straight from appveyor installer on virgin systems in virtualization. Investigation of testing as a service providers. Noise reduction and interruption compensation options and long term plans. 50dcd74 full screen auto timer updates 547df15 autofalloff typo 2016-11-08 16:30 2016-11-07 06:45 UPS system installation for networking and servers. Manufacturing meeting and notes. Setup of Dash long term testing system and virtualization with W530 laptop. rclone encrypted backup recovery and verification. Corrupted disk restorations. Timeline preparations, paystub questions. 2016-11-07 17:00 2016-11-04 07:32 Scheduled system maintenance for battery backup installation. update team on cookbook and dash project management in asana. odrive and backup systems selection and purchase. Collation and assignment of licensing resources. Virtualization attempts at securing environment auto-lock. 2016-11-04 14:30 2016-11-03 07:13 Detailed progress review meeting. Environment distraction reduction plans. Matched replication of autofalloff pyqtgraph and numpy appveyor configuration with new dash codebase. Segmentation of Win10 Dash3 and Win10 Dash4 virtual machine development environments. Communication and sprints, plans, and focus. 7070fed environment typo fixes 0590a2a mkl_avx in appvyeor conda env 42dd55d conda install cle4anup in appvyeor 373f3cb different order of appveyor install fb535a4 pyside with no python version at install 88ac8d8 with conda list and pip freeze 51fa6df init restore 3f262c8 direct copy match of autofalloff appveyor 987fcc3 built with pyqtgraph included fe75d2e documentation updates 77bf625 designer installation notes 2016-11-03 16:35 2016-11-02 07:15 second set of ME prep, setup and ME interview. Staff meetings. Setup and integration of full build on minimal system with appveyor and matching virtualbox win10 development environment with svg support. Established baseline procedures for new system development all the way through svg inclusion, qt designer cross platform development, and completed applications with included libraries. 841a280 with svg and uifile from windows designer ... 76c686a corrected travis, add appveyor 54e4e06 travis update 0b7f47e updated environment in readme ... 65ef3dd rebuild instruction and uic rcc in conda 2016-11-02 18:47 2016-11-01 07:06 prep, setup and review of ME interview. Detailed evaluation and environment match of svg-utilization in python setup for windows and linux cross platform variations. Evaluated back through wheel builds, build from sources for versions 1.2.0, 1.2.1 and 1.2.4. Established baseline functionality for png iconagraphy only 04248f5 package list comparisons 020f5ee png only resource file cb0c86c rebuilt on windows 8573c3c resources file 2016-11-02 17:54 2016-10-31 07:19 detailed mac integration plan for milestone support. Full nested layout tests of qt designer with new dash integration. Start of software test platform recovery plan and integration into production. Beginning of ME addition interview process. VPN setup and zemax remote support. Transmission integration steps 3386581 manual addition of hardware capture 8bbb5e9 recovery of resources 8fdaff0 scroll bars by default with deep named nesting and resource correction 78e6984 names for all hsd components 3621325 start of hardware setup display details 3d5a711 scroll area embedded reverse order for hardware setup 2016-10-31 16:30 2016-10-28 10:12 mac preparation of dash integration. Full project rebuild of dash from pysideapp basics. Recovery of test and integration badges and auto build capability for pysideapp, autofalloff, and Dash 4c6bffc first layer of layout updates ddd748a rebuild check 24d24bd resources specified ae6a970 realignment of filesystem a1ccc27 cleanup 4dfb32b structure files fc36978 cleanup fe30fbe tracking of generated files 4046fcd compensation for pyside-uic failure e66318d asset segmentation 8ab5a06 asset segmentation 4674f16 detailed testing instructions f3e3bf4 corrected badges a2816d0 badgets f4b9a41 build check 6144f4e setup file 414b100 manual conversion structure ddf4da1 cleanup 2016-10-28 16:30 2016-10-27 08:28 Gource visualization of source code repositories. SSD integration and kernel update failure correction for W530. Pysideapp roll back of changes for appveyor support scripts and msvcr include cleanup. MTI product recovery for inventory. Remote supoprt of software locations for customers. (sick day) 2016-10-27 16:30 2016-10-26 06:37 Asana project tracking integration demo meeting. Detailed setup and evaluation of upgrades to customer stray light tracking systems. MTI discussion and recovery of detector options for drop in replacement. 2016-10-26 16:41 2016-10-25 06:26 Investigation into msvcr100.dll missing after appveyor build install. Merge of AutoFallOff back up the chain into a deployable application with no missing dependencies. Spectroscopy training. Recreation of fully deployable application from appveyor with environment required mkl_avx.dll from system in innosetup instead of direct tracking. Training on customer stray light detection systems. 2016-10-25 16:35 2016-10-24 06:38 Createion of placeholder Dash conversion project. Reset of computational environments to support simultaneous virtualization testing. Continued task population and forecasting integration with asana dashboard for Dash development. VPN Support and configuration. Backup power system identification and recovery. 2016-10-24 16:30 2016-10-21 06:38 Detailed setup and training with Asana progress dashboard. Split of milestones and individual components. Preparation for google sheet integration and display on company dashboard. Compensation and work on github outage. 2016-10-21 16:32 2016-10-20 06:26 ISO IT requirements consideration. Test computer resource realignment. Setup of asana task project tracking structure. Review of new postiion candidates. 830 Product updates. Debug and test of SVISNIR-00002 with Transmission software project. 2016-10-20 17:02 2016-10-19 06:27 Transmission setup and coordination for SVIS_0002 recovery at HQ. 401k review and documentation. Printer fixes. OBP firmware load onto 830 product. OceanView training. 2016-10-19 15:30 2016-10-18 06:44 Refinement of asana dashboards and alignment with software roadmap plan. Down select of interface items for new version of Dash. Architecture build and design limitation review. Available IT hardware resources review for accelerated development.A 830 product documentation and deconflict 2016-10-18 18:57 2016-10-17 06:38 Creation of wasatch work log for better production tracking. Review of 401K plan. Reconfiguration of remote systems with hybrid ssd, spinning disk to verify ram or disk lockups. live new dash software demo with Jason. Driver signature process notes refinement and publish. UPS setup and email checks for primary workstation. 2016-10-17 18:00 2016-10-14 06:34 Initial software prototype demonstration with David, Michael, and Chris. c22b999 for demo ee9ac8c light and dark steps navigation bar exmaple 39a0d0e green color status fix 868da8c start of major rework for wider bar at top 5eca8a2 reflance and absorbance clean a28dbf8 loads o iconagraphy and layout updates 2016-10-14 16:30 <file_sep>/content/posts/ibm.md Title: IBM History Date: 2009-03-01 Category: articles tags: ibm thumbnail_image: /images/ibm-images/wearableBBC_full.jpg <div class="container"> <div class="row spaced_rows"> <div class="col-md-8"> Highlights from 8 years at IBM: <ul> <li>35 articles demonstrating new technologies</li> <li>13 patents from RFID to cloud management</li> <li>14 IBM Thanks peer recognition awards</li> <li>IBM Thinkplace Innovator Award</li> <li>38 IBM Bravo/Ovation awards</li> <li>IBM Bravo award for technical achievement</li> <li>19 Invention achievement awards, 5 patent plateau awards</li> <li>Selection to the Early Career Conference</li> </ul> </div> </div> </div> <div class="container"> <div class="row spaced_rows"> <div class="col-md-8"> My first opportunity with <a href="http://www.ibm.com">IBM</a> came as a Co-Op through <a href="http://www.rit.edu">R.I.T</a> with the Personal Computing Division Executive Briefing Center in Research Triangle Park. This was a fantastic opportunity where I helped administer PC's and Laptops representing all of IBM's consumer grade hardware. In addition to technical support, I had the opportunity to demonstrate the Wearable PC to customers. (Photo credit: BBC), more coverage at the <a href="http://news.bbc.co.uk/2/hi/science/nature/538072.stm">BBC</a> and <a href="http://domino.research.ibm.com/library/cyberdig.nsf/0/122b8399b43ea4348525701c0073005a?OpenDocument&Highlight=0,RC23622">IBM Research</a>. This was a great working experience with <a href="https://www.linkedin.com/in/david-laubscher-36639a2?"><NAME></a>, <a href="https://www.linkedin.com/in/jeffrey-walls-1ba0797?"><NAME></a>, <a href="https://www.linkedin.com/in/doug-baldwin-54019a?"><NAME></a> and many others. </div> </div> <div class="row spaced_rows"> <div class="col-md-8"> After the co-op and graduation from R.I.T. I began work with IBM as a full time 'regular' employee with Global Services. I worked closely with <a href="https://www.linkedin.com/in/levandos?"><NAME></a> doing Java programming. Among other projects, I worked on adding multi-threaded support to a data processing application. As part of the Customer Database team, I helped manage the batch processing data identification, matching and cleansing systems. This role focused on managing the Trillium software system on <a href="http://www-03.ibm.com/systems/power/software/aix/">AIX</a> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/fftool-screenshot.jpg"/> </div> <div class="col-md-6"> Managing tens of gigabytes of customer data in a flat file format with the existing tools was inadequate, so I created the 'Flat File Tool', which is useful for managing and visualizing large plain text files with no line delimiters. You can read more about the fftool program at [SourceForge](http://fftool.sourceforge.net/) </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/SametimePlus_logo_110.jpg"/> </div> <div class="col-md-6"> After a few months at IBM, I began work on an instant messaging client using the <a href="http://www-03.ibm.com/software/products/en/ibmsame">Sametime</a> SDK. I wanted many of the features available in other clients, but IBM's internal feature release schedule was not as fast as expected. I used my experiences with Windows Application development in college and at TM Technology to create Sametime Plus. As of March 2009, it still has features not available in the internal IBM Sametime client. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> There was a distinct need for a hardware and software environment local to our administrators instead of in [Ehningen, Germany](https://www.google.com/maps/place/IBM+Ehningen/@48.6502964,8.9364503,2062m/data=!3m1!1e3!4m8!1m2!2m1!1sibm+ehningen+data+center!3m4!1s0x0000000000000000:0x3b35d9ef4bbf614c!8m2!3d48.6519571!4d8.9467496). I created some specifications and acquired IBM-surplus AIX "medium-big iron" for faster processing of data. This project involved the setup of [7017-S80](http://www.coworthtechnologies.com/products/ibm/system-p/rs-6000/ibm-rs-6000-s80)'s and terabytes of storage in a raised floor data center environment. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Setting up systems, applications and database connections with the data quality analysis team gave me unique exposure to IBM's internal customer data. Beyond the challenges of duplication, entity relationship modelling and analysis methods, there were significant data quality issues. I worked with <NAME> and <NAME> to address many of these data quality issues. We created business rules, worked with the data custodians for each geography, and created actionable reports and a web application. IBM'ers worldwide could fix their own mis-entering of data, from typographical errors to business rule violations and placeholder entries. Moreover, violations could be tracked from an individual to mid management and corporate head level, leading to much greater visibility of data quality issues. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Visualizing terabytes of data can be a significant challenge. To address some of these issues I used surplus systems to create a minimalist 'display wall' of 9 monitors. This led to the beginnings of many IBM [developerWorks articles](http://www.ibm.com/developerworks/opensource/library?sort_by=&show_abstract=true&show_all=&search_flag=&contentarea_by=All+Zones&search_by=nathan+harrington&topic_by=-1&industry_by=-1&type_by=All+Types&ibm-search=Search). </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Various steps in the [Trillium](https://www.trilliumsoftware.com/) Batch process respond well to simple parallelization, as their is no shared data between the records. I used surplus systems gathered from the data center environment and custom Perl scripts to automatically divide the processed data amongst servers. Each server would run the parser process on its data, and send the information back to the central processing server. This simple approach reduced the processing time linearly - the more servers you add the faster the overall process. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> An organization as large as IBM exposes the employee to a wide variety of bureaucratic and logistic issues. I worked on various projects in the data center to address these needs. Mapping the locations of people within buildings and creating automatic reporting structure graphs were created for the broader IBM community. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/watchPad_thumbnail0.png"/> </div> <div class="col-md-6"> In addition to world class consumer grade hardware and software, IBM has access to some of the worlds most interesting device prototypes. I contacted IBM Research and asked for access to the WatchPad prototype. [<NAME>](https://in.linkedin.com/in/m-t-raghunath-a98600) and [<NAME>](http://researcher.watson.ibm.com/researcher/view.php?person=us-chandras) were a fantastic help getting me up and running with the IBM WatchPad environment. Working with this hardware was a unique learning experience, which you can read more about on the WatchPad page. I also had experience with the IBM [Tetra](http://archive.linuxgizmos.com/device-profile-cdl-paron-secure-pda/) smart phone, which included a fingerprint reader and lightweight Linux environment. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/soulPad_thumbnail0.png"/> </div> <div class="col-md-6"> After working on the IBM WatchPad, Chandra approached me to consider helping out with the IBM SoulPad. This was another great opportunity to work on a Linux software stack that represented the leading edge of virtualization. you can read more about my experiences with this project on the SoulPad page. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Exposure with management through the success of these and other projects led to my involvement with a wide variety of groups within IBM. Among these were the EBI Innovation Team, Autonomic Technology Cohorts, NC Green Team, and the IGS Invention Development team. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/resourceLocator_thumbnail0.png"/> </div> <div class="col-md-6"> Addressing a sales idea from <NAME> led to the Resource Locator project, and the many successes and awards it produced for the Resource Locator team. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/blueberry_thumbnail0.png"/> </div> <div class="col-md-6"> Expanding on the procedural and technical success of the Resource Locator project was the goal of the BlueBerry enterprise data search application. Click the link above for further details including what a 120+ laptop processing cluster looks like. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> During this time I also worked as a System Administrator for the Central Customer Master System project. In this role I configured and administered dozens of systems in diverse geographical locations for a multi-national team supporting test and development efforts across multiple platforms. I also did a little J2EE development to support features in various releases for the project. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Over the past three years, I have written 38 IBM developerWorks articles, completed patent applications for innovations in 19 different areas, and participated in multiple podcast interviews with Scott Laningham. You can read more about these projects and their associated Awards and Recognition from IBM. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> The successes within IBM described above and on other pages led me to begin the "Innovation that Matters - for your career and your bank account" talk to various organizations within IBM. This presentation was unique in that it would be more than someone just reading slides to you. I'd go through the pages of the Presentation, and tailor the spoken component to the audience. Using some of the tools described on these pages, I would give specific examples of innovation for the organization and individuals of that organization based on the corporate goals and personal skill sets of the listeners. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> </div><!-- container --> <div class="container"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> </div><!-- container --> <file_sep>/content/posts/wasatch_camera_link.md Title: WasatchCameraLink - Bare bones communication with DALSA sapera Date: 2016-01-04 Category: articles Tags: wasatch photonics CameraLink communication with [Wasatch devices](http://wasatchphotonics.com/product-category/optical-coherence-tomography/cobra-oct-spectrometer/) Currently supported cameras with [DALSA framegrabbers](https://www.teledynedalsa.com/imaging/products/fg/OR-X1C0-XLB00/) include: Wasatch Photonics Cobra series with [Awaiba sensors](http://www.awaiba.com/product/dragster-family-overview/) Wasatch Photonics Cobra series with OPTO sensors [Sprint Basler](http://www.baslerweb.com/en/products/cameras/line-scan-cameras/sprint/spl2048-70km) In development cameras, all through DALSA framegrabbers: DALSA [Spyder](http://www.teledynedalsa.com/imaging/products/cameras/line-scan/spyder3/S3-24-02K40/) Sensors Unlimited [GL2048](http://www.teledynedalsa.com/imaging/products/cameras/line-scan/spyder3/S3-24-02K40/) This uses a barebones version of the C# GrabConsole program from the [DALSA Sapera SDK](https://www.teledynedalsa.com/imaging/products/software/sapera/lt/) Available on [GitHub](https://github.com/WasatchPhotonics/WasatchCameraLink) <file_sep>/content/posts/wasatch_i3locksvg.md Title: i3locksvg - branded unlock screens on linux Date: 2016-01-18 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/i3locksvg_thumbnail.gif i3lock has many variations, including [i3lock-fancy](https://github.com/meskarune/i3lock-fancy), the supporting scripts on [i3lock-fancy-multimonitor](https://github.com/guimeira/i3lock-fancy-multimonitor) and many others. [i3lock-svg](https://github.com/ravinrabbid/i3lock-svg) gives you something truly unique. The ability to fully customize the unlock characterizations. This is used on wasatch photonics to create the custom lock screen you see above on linux systems. Makes quite an impression on customers. Check out the wasatch and other branches of the [GitHub Fork](https://github.com/WasatchPhotonics/i3lock-svg) <file_sep>/content/patents/patent_8,515,257.md Title: Automatic announcer voice removal from a sporting event Date: 2013-08-20 template: patent patent_number: 8,515,257 A sound processing circuit divides an audio input signal of a televised sporting event into multiple audio segments. The audio input signal includes crowd noise and announcer commentary. If an audio segment does not exceed a pre-defined amplitude threshold, a voice removal utility adds the audio segment to a recent crowd noise library and stores the segment in an output buffer. If the amplitude of a segment exceeds the threshold, the utility adds the segment to a recent announcer voice library. The sound processing circuit generates an attenuated version of the segment and blends the attenuated version with one or more mixed segments from the recent crowd noise library. The voice removal utility stores the attenuated and blended segment in the output buffer and outputs one or more audio segments from the buffer in a chronological order. <file_sep>/content/developerworks/os-socialtools.md Title: Social-networking open source visualization aids Date: 2009-01-06 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-socialtools Social-networking data analysis can help you understand content, connections, and opportunities for your personal and business associations. This article presents tools and code to extract key components of your social network using the Twitter API to chart, geolocate, and visualize your social-networking data. Local cached text. IBM developerWorks [Podcast](/files/podcasts/feature-010609.mp3) with [<NAME>ham](http://scottlaningham.com) <file_sep>/content/patents/patent_7,545,261.md Title: Automotive collision detection through passive radio analysis Date: 2009-06-09 template: patent category: patents patent_number: 7,545,261 The present invention discloses a vehicular collision alert system which receives signals from devices commonly associated with vehicular use. The direction of the received signals is determined, and a heading of the signal source is also determined and compared with the present location and heading of the vehicle If the comparison indicates a sufficient chance of a collision, and alert is generated to notify the driver of the vehicle of the potential collision. <file_sep>/content/posts/learning_taskwarrior.md Title: Integrate Task Warrior into daily workflow Date: 2017-09-25 Category: articles Tags: productivity The main problem is using google calendar and email as a task management system. Goals: 1. Clear priorities 2. Un-encumbering task list 3. Zero data loss of written tasks. 4. Single place where all tasks are stored 5. Calendar is for scheduling events only. 6. Email is for communication only Given this example email processing workflow: What this is immediately showing is that hyper-task management is not the same as productivity. What the real problem is is you let yourself become task saturated. You know what works the best. Full elimination of everything that does not address the immediate, most important, and life changing goal. Creating, organizing and giving away businesses. Now how does task warrior help you do that? Task warrior provides a faster mechanims for writing notes. task add "read innovators dilemma" vs. create draft in google mail web app, go to body, write "read innovators dilemma", create event in google calendar (pick an appropriate day based on arbitrary rules) add "read innovators dilemma" as the title, click save The lesson here is that it's really about the workflow first, then tool selection. You thought taskwarrior would fix the problems. What it does is help you elucidate what the problem is. You don't want to get things done. You don't want to write down, classify and then track as much work as possible. You want to eliminate as much work as possible in order to focus on what you are here for. For example: Phone call, sharing ideas, written on piece of paper. Come back next day, write them out as separate tasks like: task add "find anne mcgraf book" task add "research kellogg innovation forum" That is just the 'storage' component of this procedure. The second level procedure is you need a task management workflow, just like you have for email. Start the day knowing what the single most important thing to work on is. Make sure your thought patterns are focused on the first most important thing to work on. This does not require task warrior. This should explicitly exclude all task management software. This is the next, key activity required to train in, to practice, to transform into. Maybe it's business model canvas generation. Maybe it's spiritual development. Maybe it's learning a web framework. Whatever it is, do it and stay focused. If during this process you have an idea to capture, issue the command: > task add "new activity to add" As the day progresses and energy wanes, begin the integration of task warrior. The main focus is the same, but you add in 5 minute intervals of other tasks in order to facilitate focus. This is the push through the most difficult mental times in order to achieve the long term goals. If your task warrior list looks like this: ``` ID Age Project Description Urg 2 7d stage_four Value proposition immersion 1.04 1 7d document structure customer discovery 0.04 3 6d django tutorial continue 0.03 4 4d switch to sup insteads of mutt - use erp account for testing 0.02 5 1h find bmc discussion groups 0 6 7min encrypt backup disk 0 7 7min zenbook backup to backup disk 0 8 7min tapemonster backup to backup disk 0 9 7min zenbook, w541 and tapemonster txt fiels to an sd card and a 0 usb disk, encrypted ``` Set the initial item as active: task 2 start Then set the timer on the watch (not the phone!), for every 5 minutes. After the timer is up, switch to the next item on the task list, but leave the primary (task 2) as active. Reset the timer. After another five minutes, go back to the primary. Continue this cycle so the primary task is executed at 50% duty cycle. This provides an effective balance between long term goal work and lower level work. Both are important, but this ensures there is less liklihood of task saturation, and the fatigue is counteracted by the newness and shortness of other tasks. <file_sep>/content/posts/learning_customer_discovery.md Title: Customer Discovery: Interviews Date: 2017-10-25 Category: articles Tags: business model canvas Customer discovery: Interviewing with excellence and artistry **Research of known effective materials:** <NAME> [The tactics of Customer Discovery](https://www.slideshare.net/sblank/customer-discovery-23251533) Login to slideshare/linkedin then download as .docx for offline use Pages 12-17 Startup Weekend [Conducting Customer Interviews](https://www.youtube.com/watch?v=V3syNbgSkwE) Customer Discovery emails: [<NAME>alt's Blog](http://kevindewalt.com/2010/01/12/the-magic-word-in-customer-development-emails/) [Cold connecting through linkedin](https://campuspress.yale.edu/cnspy/2016/03/02/how-to-cold-connect-on-linkedin/) from yale.edu ----------- #### Incorporation: **Card deck 1 of 2 Develop an interview Plan** <pre> Abstract assumptions Generate a list of questions based on your customer segment assumptions. Abstract your questions to disguise what you would otherwise ask directly. Don't ask questions in a manner that can influence a customer's response. Industry Research Become an expert. Search for industry report, establish Google alerts, read scholarly articles, etc. It's not hard to know more than the person across from you about generalized industry trends. Company Research Read the companies website. Person Research Read their linkedin profile From the companies website, read their biography. Starter Questions Build rapport by mentioning something you have discovered from the company website or the personal research. Conversation Prompts If the conversation stalls, fall back to: yeah, but why did (the last thing they said) that's interesting, but how (the last thing they said) Keep communication open Develop a reference story and write a highly professional email getting right to the ASK (which is an interview) Sample Interview Questions Can you tell me a story about that? And then what happened? Why/how did you do that? What did you love/hate about that? If you could have a magic wand, what would it be like? Can you tell me about the experience when ... What are the best/worts parts about ... Can you help me understand more about ... Practice Rehearse the opening approach. The start of the interview, the conversation prompts, and the end ask. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_interview_planning_card_deck_front.jpg)](/images/learning/learning_interview_planning_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_interview_planning_card_deck_back.jpg)](/images/learning/learning_interview_planning_card_deck_back.jpg) -------------------------------------------------- **Card deck 2 of 2 Conducting Interviews** <pre> Customer discovery is an art An intuitive process that relies on your ability to recognize common themes expressed by others. Honesty You have to posses the self control, objectivity and realism to be honest about whether your value proposition can meet their needs or fix their problems. Genuine interest Demonstrate that you are authentically trying to deliver a solution that will eliminate "pains" or create "gains" for the customer. Actually talking with customers The interviews are for gaining empathy and surfacing insight. Ask questions to seek understanding, not to sell an idea. Listen Forget about yourself. Be completely optimisitic and open to listening to the needs of your customers. Seek Stories Find in-depth stories about a users experiences that touch their emotions. Ask "Why" and "How" As you are listening to stories and hear them express a point, always dig deeper and ask why. Ask simple, penetrating inquiries to get them to to describe a deeper need which they may not have understood initially. Immersion - There is simply no better way to gain empathy for a problem a customer experiences than actually living through their experience. Observation - Ask them to physically demonstrate how they are currently solving a problem. Have them draw the process flow of how they are currently performing a specific job. Customer doorways Bold statements Inconsistency between what they say and do Sudden, animated gestures Silence Go through the customer doorway and probe further by asking how and why. Known market Problem Presentation Describe your assumed list of problems, pause and ask the customers what they think the problems are. Where you are missing any problems. Unknown market Seek stories People don't always understand their own problem. Find specific stories about their day to day experiences. A single message left behind: Leave them with the feeling that you are genuinely interested in helping solve their pains and give them gains. It doesn't matter if they never see the prototype as long as they feel that you are trying to help. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_interview_conducting_card_deck_front.jpg)](/images/learning/learning_interview_conducting_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_interview_conducting_card_deck_back.jpg)](/images/learning/learning_interview_conducting_card_deck_back.jpg) -------------------------------------------------- ------------------------------------------------------------------------- ## Execution: Here's a typical workflow: <pre> Search google for "job role [place, technology, company]" Process each link on each google results page. Keep two separate documents: Search terms: A list of all search terms tried Contact and stop list: Identifiers such as names, address and domains grouped into 'has been contacted' and the 'stop list' In the instructions below stop means put the domain in the stop list (unless already contacted) and then close the page and go back to the google search page. Process each link: If the domain is already in the contact list == stop If the domain is already in the stop list == stop Open the web page link If does not load in 10 seconds or has a security warning == stop Do they actually perform [role]? No == stop Do they actually work in [place]? No == stop Are they employed by [company]? No == stop Find email address for that person. Kick off 'find emails' harvester script While that is processing, do the manual search of the persons history, their blog roll, or whatever is topical that you can use to learn more about them. Write a short comment about work they have done - this is the personalization step to show that you have done research and start the process of building rapport. Get the email from the harvester (see below), if none available, go back to the website and look for contact page. The bottom of home page The about page Then instagram Then Twitter Do not look at facebook or pinterest Send email with the subject: "[short comment subject] from your [recent event]" "[short comment subject] from your blog" "[short comment subject] from your website" Email body is pasted from the form connect request below, with personalization. Add email to contact list Go to next link on google page. If at the end of the google page, count the number of new, valid contacts. If at least 3, continue to next page, otherwise iterate the search terms. </pre> ## More excellent resources that were consulted to generate the scripts for cold emailing and calling customers: [Getting Customer Interviews with Cold Emails - Customer Development Labs](http://customerdevlabs.com/2014/02/18/how-to-send-cold-emails/) ## Setup your email for effective communication <pre> Make sure the links in your signature all point to at least a basic landing page on your website. Ensure that your email has a short signature with job title and company logo. </pre> ### Craft an introductory email: <pre> Hi [Persons name] - [Short comment about their work you have done the research on]. I'm the [job title] at [employer], a [company description] trying to improve [job that the customer performs]. I'm not looking to sell anything, but since you have so much expertise with [specific job function], I'd love to get your advice on our product so we don't build the wrong thing. If you're available, I'd love to chat for just 20 minutes - [two-day option] morning? Thanks for any help, [name] </pre> ### If they want more info about the company <pre> Thanks for your willingness to help! I'm [job title] at [company website], where we are trying to solve a problem we think all [customer job title] may have. We're using the Customer Discovery process to work to truly understand our customers, the jobs they perform and their real pains to make sure we don't build the wrong thing. The questions are about talking with you about what your job is, how you go about it on a day to day basis, and what your routines are. </pre> ### If they want more info about company and product <pre> I'm [job title] at [company website], where we are using the Customer Discovery process to work to truly understand our customers, the jobs they perform and their real pains to make sure we don't build the wrong thing. The questions are about talking with you about what your job is, how you go about it on a day to day basis, and what your routines are. It's a software product designed to [basic vague product description] Yes, I'm being specifically vague about the product specifications - this is not be be deceptive, but rather to make sure we understand you - our customer - so we don't build the wrong thing. I'll be glad to send you the full product description if you like, but we like to hold off on that until we discover if we truly understand your needs. If that sounds ok, I'd love to talk with you and get your advice. The [customer community] has been incredibly supportive of our research so far, and I realize that this may be your [busiest time], so I just want to say thanks again for considering helping us! </pre> ### Schedule the interview If the response is 'yes that time will work' or something similar. Pick the closest 1 hour window (starting at :15 after), and create a calendar entry of the type: <pre> Call with [persons full name] at [time] who [interesting note from their linkedin profile or their 'about' section on their webpage] </pre> Then when the call is about to happen, review their name and the interesting note to mention during the opening approach to build rapport. ### Follow up email after connection on linkedin They accepted the connection request on linkedin, and did not respond with a custom message. Find their email address from the linkedin profile, and send: <pre> Hi [persons name] - I'm working with [company name] on building a [product idea] and was hoping to get your advice to make sure we understand the problem. Could I ask you a few questions and get your feedback over a fifteen minute phone call? Maybe [two-day option] morning of next week? Thanks! [name] </pre> ### Follow up email after interview Send this immediately after the interview <pre> [Person's name] - Thanks for speaking with me today! I really value your advice and insight. If you can think of anyone else who might want to talk about [general problem descriptions covered in the meeting], please send them my info: I'm [name] with [company website] and we're trying to solve a problem with think all [customer job title] may have. I'm not selling anything, but would love to get your advice to make sure we don't build the wrong thing. Thanks for any help! - [name] [your email address] </pre> ### Building a reference story email During a customer discovery interview, they mention that you should talk to person X. After the interview, you send the follow up email above. Wait. After the referring person says 'I will forward your info' or 'I will let them know you will be contacting them', send the email below: <pre> To: <NAME> cc: <NAME> Subject: Referral from Joe Smith Hi Don, Joe may have mentioned that I would drop you a quick note to ask for your advice. I'm exploring an [type of) idea around making it easier for [job role] to [perform aspect of their job role]. Joe suggested that I talk to you given your expertise with [same or other job role]. Do you have time for a quick call next week? I'm not selling anything, just looking for advice. Joe, Thanks for your time. You can't imagine how helpful your advice was to me and hopefully you'll let me return the favor. Thanks in advance, [name] </pre> ## Interview Script ### During the interview: Write down the name of the person you are supposed to be talking to. Write down the name of the person you are talking to now. The single most important thing is that they feel you are trying to help. Stop and take every opportunity to explicitly say we're just trying to help understand what your real needs are. ### On the script write in order from top to bottom: <pre> Opening approach: I saw on your profile [interesting note form their profile that you put on the calendar entry] Start of the interview: I'm [name] with [company] and we're trying to solve a problem we think all [customer job title] may have. I'm not selling anything. What I'd like to do today is ask you some questions about your routines to see if I understand the problems that you have. It should only take about 20 minutes. If I do understand, I'd like to share our prototype with you and get your feedback. Does that sound ok? First question: Something extremely straight forward and fundamental that they will be able to immediately answer. This is to get the process flowing and make them feel at ease: What is the first thing you do when you start [job description]? Where are you when you usually have to do [job description]? When was the first time you had to do [job description]? Conversation prompts: When you lose focus for whatever reason, fall back to the: that's interesting, but how [the last thing they said] yes, but why [the last thing they said] Fill in abstracted questions for your customer segment here: (These are highly specific to your customer segment assumptions and the items below are highly generalized examples) How often do you communicate with [other people involved in job]? What do you use to communicate with them? When do you find time to maintain your tools? Can you tell me a story about a time an event happened during the job that was not in your control? What do you love about [specific job]? What are the parts about [specific job] that you hate? What are the worst parts about getting ready to do [specific job]? Can you help me understand more about [specific job]? What apps do you use on your phone to do [specific job]? If you could have a magic wand for [specific job], what would it be like? Do most [peer job description] work that way? The end ask: Would it be ok if I sent you a short description of who we are and what we're working on to make it easier to forward? We'd really love to talk with anyone else you might think has these same problems. Does that sound ok? Express gratitude. Not through just words. Through inflection and a genuine appreciation for their attitude of collaboration and service. This is the single most important part of the entire interview. </pre> ## Questions not to ask The Startup Weekend [Conducting Customer Interviews](https://www.youtube.com/watch?v=V3syNbgSkwE) video says to begin with: "To start off, what are the three biggest problems you deal with in your business?" This was almost a universally consistent conversation killer. Many of these customers were even hesitant to use the word problem. They also did not seem to know what the problems are. What is truly keeping them from the ideal existence. Train yourself to not ask "Is that something you would be interested in?" - that type of question is contra-indicated during the search to gain empathy. Do not ask them what problems they have. It leads to instant flow blockage. It's like the listener has been trained to not recognize the problems. Seek stories. At the end of the interview they should feel that you were generally trying to understand the narrative of their life as they perform a job. It's not a complaining session, it's a shared understanding session. Many of the people willing to speak with you know this implicitly. They are naturally willing to help you because they know that collaboration and learning is always a good experience. When you hear them express a point or describe a problem, do not ask: "Why do you think that is?". Usually if they knew, it would not be a problem, they would be focusing on their steps to execute around the event, not the confusion generated by the event. ## Real world customer discovery notes The above scripts and steps were developed over approximately one week of intense effort. These were to test the assumptions about what constitutes an effective mechanism for building contacts and getting to at least phone interviews with customers that are in your customer segments. Intense effort in this case is about 35 hours of work over a 7 day period, in the midst of all the other daily life activities. For a given one week interval: <pre> 373 potential customers evaluated 150 domains, emails, names in the stop list 223 emails or form submittals in contact list 11 interviews setup and executed during the week 5% response to interview rate during the one week interval 9 interview requests setup and accepted for the subsequent week. If half of those turn into actual phone interviews: 7% response to interview rate total </pre> That actually seems unsustainably low. For 35 hours of work you get about 8 hours of direct communication with potential customers. Memorizing the questions allows you to focus on the process of gaining empathy. Memorizing the flow of the interview and experiencing it allows you to focus on their needs instead of getting the information you want. The search for common themes expressed by the customer requires some structure. Try and ask as many of the same questions in the same order as possible in order to make the data analysis easier. Exactly what was said in the udacity materials is exactly what happened. The customers interviewed eventualy showed what was really important to them. Very little during the performance of one of their specific jobs impacted them. They have mastered the art and craft that is the core of what they do on the day of. The things that really bother them are around the anxieties of where do customers come from? How do they continue to pay their bills so they can focus on what is truly valuable to them? In addition - they will literally tell you exactly how to position the product. The vocabulary and structure of their selected points of expression are exactly what can uniquely position the product during the subsequent phases. This will happen repeatedly, make sure you write it down. ## Custom theHarvester wrapper script To make this easier, use whois records and [theHarvester](https://github.com/laramies/theHarvester) for finding emails: ``` #!/bin/bash # # Run a basic whois and a theHarvester and only print emails # # Usage: find_emails.sh https://yourdomain.com/deep/subtree.html # # Output: email addresses from whois and the harvester # # Expects the user to setup a conda environment with: # conda(2) create --name harvester # source activate harvester # pip install requests # export PATH=/home/nharrington/miniconda2/bin:$PATH source activate harvester if [[ $# -eq 0 ]] ; then echo 'You must specify a domain' exit 0 fi DOMAIN=$1 # To speed this up, comment out the command line above, and just copy # the domain to the system clipboard, then run: #DOMAIN=`xclip -o` # Extremely rough and ready strip of domain details. This is so you can # cut and paste a typical url with any file tree suffix and get just the # bare domain DOMAIN="${DOMAIN//http:\/\//}" DOMAIN="${DOMAIN//https:\/\//}" DOMAIN="${DOMAIN//www./}" DOMAIN="${DOMAIN//.com*/.com}" DOMAIN="${DOMAIN//.org*/.org}" echo "Searching $DOMAIN" # Filter out knowns whois $DOMAIN \ | grep @ \ | grep -vi abuse \ | grep -vi privacy \ | grep -vi domainsbyproxy.com \ | grep -vi domaindiscreet.com \ | grep -vi whoisguard.com python -u theHarvester.py -d $DOMAIN -b all -l 100 \ | grep @ \ | grep -v <EMAIL> ``` <file_sep>/content/developerworks/os-identify.md Title: Identify and verify users based on how they type Date: 2008-03-18 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-identify Modify the GNOME Display Manager (GDM) to support user verification through keystroke-dynamics processing. Create and store a one-way encrypted hash of your keystroke patterns when entering your user name. Add code to GDM to read current keystroke patterns and permit a user to log in when the characteristics are a match. [Slashdot discussion](https://developers.slashdot.org/story/08/04/04/169229/identify-and-verify-users-based-on-how-they-type) <file_sep>/content/developerworks/os-google-earth-perl.md Title: Create time-availability maps with Perl and Google Earth Date: 2008-08-26 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-google-earth-perl Time-availability maps provide a listing of who is most likely to be available for a certain hour in a certain location. Find out how to use Google Earth and a log of your communications to map and identify the time and place when availabilities match. Featured in an IBM developerWorks [podcast](/files/podcasts/feature-082608.mp3) with [Scott Laningham](http://scottlaningham.com). <file_sep>/content/developerworks/os-customsearch-firefox.md Title: Beef up the Find command in Firefox Date: 2008-08-12 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-customsearch-firefox The Find command in Firefox locates the user-specified text in the body of a Web page. The command is an easy-to-use tool that works well enough for most users most of the time. Sometimes, however, a more powerful Find-like tool would make locating text easier. This article shows how to build a tool that isolates relevant text in Web pages faster by detecting the presence and absence of nearby words. <file_sep>/content/pages/example_post_hidden.md Title: Hidden file for demonstration Date: 2015-09-03 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/wasatch_photonics_analyzeiq_thumbnail.png status: hidden <!-- Why is this hidden? As a syntax reminder for how you can apparently embed html in this file, with markdown inside of it. See the spae after the first row below for further comments. --> <div class="container"> <div class="row spaced_rows"> <div class="col-md-8"> <!-- apparently if you leave the line below empty, you get to mix markdown in html like you always wanted. --> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-6"> A custom interface for [AnalyzeIQ Lab](https://www.analyzeiq.com/Products/Analyze-IQ-Lab.html) that will collect data from Wasatch Photonics devices. Analyze IQ is a third party chemometrics solution that can also be used on [Ventana](http://oceanoptics.com/product-category/ventana-series/) devices from [Ocean Optics](http://oceanoptics.com/product/analyze-iq-chemistry-software/) </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-6"> Acquires data from Wasatch Photonics spectrometers, write out in xml format for use in AnalyzeIQ. This uses AnalyzeIQ's stdin/stdout interface, which is more than sufficient for multiple acquisitions per second. Pleasingly straightforward to integrate and test. </div> <!--left side column--> </div><!-- row --> </div><!-- container --> <file_sep>/content/developerworks/os-ghosd-synergy.md Title: Improve focus tracking indicators across multiple monitors Date: 2008-09-09 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-ghosd-synergy Unlike traditional single-screen setups, multi-screen display systems require special consideration for user interfaces (UIs). This article presents tools and code designed to address the acquisition and change of input focus across multiple displays. By enhancing existing X Window System focus information using Ghosd displays and the Synergy debug-level output, multi-screen users can know precisely where their input focus is even on displays 4200x3150 pixels and larger. <file_sep>/content/posts/geforce_gtx_960_fedora_core_24.md Title: GTX 960 with Fedora Core 24 Date: 2016-12-12 Category: articles Use an Nvidia Geforce GTX 960 with Fedora Core 24. There are alot of useful guides: [If Not True Then False](https://www.if-not-true-then-false.com/2015/fedora-nvidia-guide/) [Unixmen](https://www.unixmen.com/install-nvidia-drivers-fedora-24/) [RPMFusion](https://rpmfusion.org/Howto/nVidia) Here are the exact steps followed to use the nvidia card: Go to the [Nvidia Drivers](http://www.nvidia.com/Download/Find.aspx?lang=en-us) page. Select the appropriate product, operating system etc. These steps use: NVIDIA-Linux-x86_64-375.20.run 375.20 (November 18, 2016) sudo dnf -y update #(20 minutes later...) reboot dnf install kernel-devel kernel-headers dnf install gcc dkms acpid echo 'blacklist nouveau' >> /etc/modprobe.d/disable-nouveau.conf echo 'nouveau modeset=0' >> /etc/modprobe.d/disable-nouveau.conf dnf install xorg-x11-drv-nvidia akmod-nvidia "kernel-devel-uname-r == $(uname -r)" dnf update -y chmod +x NVIDIA-Linux-x86_64-375.20.run ./NVIDIA-Linux-x86_64-375.20.run # (Accept defaults) reboot <file_sep>/content/developerworks/os-automatic-shutdown.md Title: Shut down idle computers on your network automatically Date: 2008-10-21 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-automatic-shutdown Recent pushes for "green" technology focus mostly on talk, with little action for the typical home- or small-office environment. Many users leave their systems online continuously through laziness or ignorance, resulting in a significant source of power consumption, as well as an additional vector for malware propagation. The tools and code presented here allow you to find those inactive systems and securely start the shutdown process. With a Linux® box monitoring your network connections using Argus and some custom Perl code, any system that supports Perl can be set to be remotely shut down when a centralized set of inactivity rules are met. <file_sep>/content/developerworks/os-audio.md Title: Make incoming e-mail play custom tunes Date: 2007-01-23 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-audio Use SoX, and a Perl script to do simple keyword matching and create sound files played back upon receipt of e-mail. No more simple ding to indicate the arrival of an e-mail regardless of recipient, sender, or subject. You can now hear a ding-bang-whoosh signifying an e-mail from your manager, or a bell-squawk-chirp to let you know your bank statement is available. Local cached text. Audio example with glasses, sparcle, space2.Another example with glasses, laser, space3. <file_sep>/content/developerworks/os-google-earth-altitude.md Title: Creating altitude attribute-enhanced image overlay maps in Google Earth Date: 2008-09-23 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-google-earth-altitude Recent applications have greatly increased the ease of development and ubiquity of 2-D maps. Tools like Microsoft® Live Search Maps and Google Maps offer a wealth of tools for enhancing these single-plane maps, but often ignore altitude as the third dimension of information. This article presents tools and code to allow you to extract height information based on pixel colors, and apply that height information across the mapping context. The end result is a third dimension of data, showing more information in the same space and opening up new methods of visualization for your map users. <file_sep>/pelicanconf.py #!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'<NAME>' SITENAME = u'<NAME>' SITEURL = '' PATH = 'content' TIMEZONE = 'America/New_York' DEFAULT_LANG = u'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True STATIC_PATHS = ['images', 'files', 'extra/robots.txt', 'extra/favicon.ico', 'extra/custom.css', 'extra/CNAME'] EXTRA_PATH_METADATA = { 'extra/robots.txt': {'path': 'robots.txt'}, 'extra/favicon.ico': {'path': 'favicon.ico'}, 'extra/favicon-16.ico': {'path': 'favicon-16.ico'}, 'extra/favicon-32.ico': {'path': 'favicon-32.ico'}, 'extra/favicon-64.ico': {'path': 'favicon-64.ico'}, 'extra/favicon-96.ico': {'path': 'favicon-96.ico'}, 'extra/favicon-128.ico': {'path': 'favicon-128.ico'}, 'extra/favicon-160.ico': {'path': 'favicon-160.ico'}, 'extra/favicon-192.ico': {'path': 'favicon-192.ico'}, } # Blogroll LINKS = None # Social widget SOCIAL = ( ('github', 'http://github.com/NathanHarrington'), ('linkedin', 'https://www.linkedin.com/in/harringtonnathan'), ('google-plus', 'https://plus.google.com/100412424991063551562'), ) # Don't show generated categories in menu (like manuals) DISPLAY_CATEGORIES_ON_MENU=True ARTICLE_EXCLUDES = ["files/cached_developerworks_html"] DISPLAY_PAGES_ON_MENU=True # Show the colorful banner image on all pages #BANNER = 'images/banner.png' #BANNER_ALL_PAGES = True #BANNER_SUBTITLE = "banner sub" # don't show any of the right side info #HIDE_SIDEBAR=True #BOOTSTRAP_THEME="paper" #HIDE_SITENAME=True HIDE_SIDEBAR=False ARTICLE_URL = 'posts/{slug}.html' ARTICLE_SAVE_AS = 'posts/{slug}.html' GOOGLE_ANALYTICS = "UA-4602287-2" <file_sep>/posts/music-for-working.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>Music for working - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="/posts/music-for-working.html"> <meta name="author" content="<NAME>" /> <meta name="keywords" content="music" /> <meta name="description" content="Goals: Control the external sensory environment. Hardware: Bose QuietControl 30 Bose QuietComfort 30 (pre-google assistant version) Yes, both at the same time. Put the earbuds in, turn up noise cancellation all the way. Play the music through this set. Turn on the over ears, ensure the noise cancellation is on …" /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="article"/> <meta property="og:title" content="Music for working"/> <meta property="og:url" content="/posts/music-for-working.html"/> <meta property="og:description" content="Goals: Control the external sensory environment. Hardware: Bose QuietControl 30 Bose QuietComfort 30 (pre-google assistant version) Yes, both at the same time. Put the earbuds in, turn up noise cancellation all the way. Play the music through this set. Turn on the over ears, ensure the noise cancellation is on …"/> <meta property="article:published_time" content="2017-09-23" /> <meta property="article:section" content="articles" /> <meta property="article:tag" content="music" /> <meta property="article:author" content="<NAME>" /> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li class="active"> <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <article> <div class="entry-content"> <p>Goals: Control the external sensory environment. </p> <p>Hardware:</p> <p><a href="https://www.bose.com/en_us/products/headphones/earphones/quietcontrol-30.html">Bose QuietControl 30</a></p> <p><a href="https://www.bose.com/en_us/products/headphones/over_ear_headphones/quietcomfort-35-wireless-ii.html#v=qc35_ii_black">Bose QuietComfort 30</a> (pre-google assistant version)</p> <p>Yes, both at the same time. Put the earbuds in, turn up noise cancellation all the way. Play the music through this set. Turn on the over ears, ensure the noise cancellation is on full, and put those on over the in-ears. Play no sound through the over-ears, just use noise cancellation. It's 700$ on your head, and it's worth every penny.</p> <p>Using these together means you won't be able to hear yourself type on a mechanical keyboard. You won't hear people have yelling conversations across rooms with your head in the middle. You won't hear door slams and outside vehicles. It's a beautiful thing.</p> <p>Face the wall - eliminate all peripheral vision. Literally add blinders to your glasses if you need to.</p> <p>As of 2021-10-25, the second best choice is a combination of noise isolating (not cancelling) ear buds, and noise cancelling over-ears. This is probably a 90% solution to the Bose setup before, for 1/7th the cost. Neckbands are definetly the way to go, as they have true all day battery life and over ears can fit over them.</p> <p><a href="https://www.amazon.com/gp/product/B086L8WF4D/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&amp;psc=1">SoundCore U2 neckband</a> Put this in with the default silicone covers. Use the full spectrum music and noise generation setup described below.</p> <p><a href="https://www.amazon.com/dp/B07NM3RSRQ?psc=1&amp;ref=ppx_yo2_dt_b_product_details">Soundcore Q20 over ears</a> Just turn these on with noise cancelling enabled, do not play any sound through them.</p> <p>The QuietComfort was no longer available. A comparable 70% solution are these <a href="https://www.amazon.com/gp/product/B019U00D7K/ref=oh_aui_search_detailpage?ie=UTF8&amp;psc=1">COWIN E7 Noise Cancelling Headphones</a> They block significant noise. They are not as configurable. The biggest downside is that they hurt the ears after 2 hours instead of 3+ like the bose. It has nearly the same effect though. It's been about a month living with these as the over ears every day, and the only issue is the discomfort.</p> <p>A much cheaper alternative that will still let in significant outside noise and make your ears hurt after an hour: <a href="https://www.amazon.com/gp/product/B004U4A5RU/ref=oh_aui_search_detailpage?ie=UTF8&amp;psc=1"> Howard Leight by Honeywell Sync Stereo MP3 Earmuff (1030110)</a></p> <p>Put these in-ear plugs in first, then crank up the music through the earmuffs: <a href="https://www.amazon.com/Howard-Leight-Honeywell-Disposable-MAX-1/dp/B0013A0C0Y/ref=sr_1_21?s=hi&amp;ie=UTF8&amp;qid=1507982199&amp;sr=1-21&amp;keywords=ear+plugs"> Howard Leight by Honeywell MAX Disposable Foam Earplugs, 200-Pairs (MAX-1)</a></p> <h2>Find and play music:</h2> <p>What you are looking for is broad spectrum music. Examples are:</p> <p><a href="https://www.youtube.com/watch?v=6c0GqWbCcyg">Best 8-bit electro gaming mix 2016</a> <strong>Do not browse youtube.com</strong> Anything electronic, dubstep, gaming etc. is known for inappropriate imagery. </p> <p>or</p> <p><a href="https://youtube.com/watch?v=6wvrHQ0aDC8">Handel Organ Concertos</a></p> <p>Both of which cover the low, mid and high range of frequencies in typical office environments, continuously. You may want the Goldberg Variations, but there is just simply too much empty space in the music to effectively drown out office environments.</p> <p>Start your search tool. Search one of the url's above. Look at the information for the video. If it's a compilation, search for playlists with the song name, or the artist name, like:</p> <div class="highlight"><pre><span></span><code><span class="c1">//truecolor alchemist</span> <span class="c1">//fadex</span> <span class="c1">//organ concerto</span> </code></pre></div> <p>Then play the entire playlists, and make a note of the non-vocal entires. You're looking for zero vocalizations within the music. 1 minute of words (including the repetition) per 45 minutes of non-vocal music. The Tron Legacy sountrack for example. is a great example of what you are looking for.</p> <p>Select music by the following criteria: You're looking for pieces with a minimum of 100k views, with at least a 4 to 1 like to dislike ratio.</p> <p>More ideas for finding music non-vocal broad spectrum music: Fadex is almost perfect in what you are looking for. Look up their web presence and check for entries on their spotify favorites, playlists, and punch those names into playlists on mpsyt. </p> <h2>Brown noise + Pink noise</h2> <p>Alternatively or additionally if required, add in brown (low frequency) and pink (high frequency) noise overlaid on top of the music. If you must have the Goldberg Variations, for example, start the goldberg variations, then add in:</p> <p><a href="https://youtube.com/watch?v=GSaJXDsb3N8">Brown noise</a> and <a href="https://youtube.com/watch?v=ZXtimhT-ff4">Pink noise</a> at about 60% music volume. It may seem loud at first, but it will blend in after a few minutes and you will realize later that it fills in the variability of office environment sounds resulting in increased focus.</p> <p>Preferrably, use sox for audio generation with one of these options:</p> <pre> play -c 2 -n synth [brownnoise|whitenoise|pinknoise] </pre> <h2>Search tools</h2> <div class="highlight"><pre><span></span><code><span class="w"> </span><span class="c1"># on Fedora core 29</span> <span class="w"> </span><span class="c1"># Download and install conda3, make sure to use python version 3.7</span> <span class="w"> </span><span class="n">dnf</span><span class="w"> </span><span class="n">install</span><span class="w"> </span><span class="n">mplayer</span> <span class="w"> </span><span class="n">conda</span><span class="w"> </span><span class="n">create</span><span class="w"> </span><span class="o">--</span><span class="n">name</span><span class="w"> </span><span class="n">mpsyt_py37</span><span class="w"> </span><span class="n">python</span><span class="o">=</span><span class="mf">3.7</span> <span class="w"> </span><span class="n">source</span><span class="w"> </span><span class="n">activate</span><span class="w"> </span><span class="n">mpsyt_py37</span><span class="w"> </span> <span class="w"> </span><span class="n">pip</span><span class="w"> </span><span class="n">install</span><span class="w"> </span><span class="n">mps</span><span class="o">-</span><span class="n">youtube</span> <span class="w"> </span><span class="n">pip</span><span class="w"> </span><span class="n">install</span><span class="w"> </span><span class="n">youtube_dl</span> <span class="w"> </span><span class="c1"># If that doesn&#39;t work, or it starts skipping files in playlists, or</span> <span class="w"> </span><span class="c1"># otherwise won&#39;t play large swaths of youtube, you may need to</span> <span class="w"> </span><span class="c1"># create an environment and load from source:</span> <span class="w"> </span><span class="c1"># pip install --upgrade \</span> <span class="w"> </span><span class="c1"># https://github.com/mps-youtube/mps-youtube/archive/develop.zip</span> <span class="w"> </span><span class="n">Start</span><span class="w"> </span><span class="n">mpyst</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">conda3</span><span class="w"> </span><span class="n">environment</span><span class="p">,</span><span class="w"> </span><span class="n">then</span><span class="w"> </span><span class="n">issue</span><span class="p">:</span> <span class="w"> </span><span class="o">&gt;</span><span class="n">set</span><span class="w"> </span><span class="n">player</span><span class="w"> </span><span class="n">mplayer</span> <span class="w"> </span><span class="o">&gt;</span><span class="n">set</span><span class="w"> </span><span class="n">columns</span><span class="w"> </span><span class="n">user</span><span class="p">:</span><span class="mi">14</span><span class="w"> </span><span class="n">date</span><span class="w"> </span><span class="n">likes</span><span class="w"> </span><span class="n">dislikes</span><span class="w"> </span><span class="n">views</span> </code></pre></div> <p>Select music from by configuring the columns. You're looking for a minimum of 100k views, with at least a 4 to 1 like to dislike ratio.</p> <p>As of 2018-02-05 13:54, you'll also need to change the download command to make use of chunk sizing to prevent youtube throttling. Start mpsyt then issue the command below (newlines are for readability)</p> <div class="highlight"><pre><span></span><code><span class="w"> </span><span class="n">set</span><span class="w"> </span><span class="n">download_command</span><span class="w"> </span> <span class="w"> </span><span class="n">youtube</span><span class="o">-</span><span class="n">dl</span><span class="w"> </span><span class="o">--</span><span class="n">user</span><span class="o">-</span><span class="n">agent</span><span class="w"> </span>\ <span class="w"> </span><span class="s2">&quot;Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0&quot;</span><span class="w"> </span>\ <span class="w"> </span><span class="o">--</span><span class="n">http</span><span class="o">-</span><span class="n">chunk</span><span class="o">-</span><span class="n">size</span><span class="w"> </span><span class="mi">10</span><span class="n">M</span> <span class="w"> </span><span class="o">--</span><span class="n">extract</span><span class="o">-</span><span class="n">audio</span><span class="w"> </span><span class="o">%</span><span class="n">u</span><span class="w"> </span><span class="o">-</span><span class="n">o</span><span class="w"> </span><span class="s1">&#39;</span><span class="si">%F</span><span class="s1">&#39;</span> </code></pre></div> <h2>Phone configuration</h2> <p>Playing the music through cmus or mpsyt on the linux desktop is the best option. You still want podcasts and network connectivity through the phone as well. What you don't want is the various bose headsets announcing the calls and disrupting flow.</p> <p>These instructions are for a 2016 era Motorola Moto E Black (2nd Generation) on Ting wireless running Android 5.1.</p> <p>Connect the bluetooth headsets as Media audio, no phone audio, no contact sharing.</p> <p>Get a google voice number For the regular cell phone number, set</p> <p>Settings -&gt; Sound and notification -&gt; Interruptions</p> <p>When calls and notifications arrive: Allow only priority interrputions</p> <p>Priority interruptions: Events and reminders: on Calls: on Messages: on</p> <p>Calls/message from: contacts only</p> <p>Create a contact that has the google voice number called Google voice.</p> <p>Now you give out the google voice number to everyone, and it will automatically forward the calls to the actual phone number. Tell all your important contacts that you are letting everything go straight to voicemail on the google voice number. If they must reach you immediately, dial the main number.</p> <p>The phone will still light up, it will still vibrate for google voice calls. It will still light up for any other call that goes to the actual number as well, but only if it's already in your contact list.</p> <h2>Deploying</h2> <p>Use mpsyt as the primary music browser. As you find entries that meet the requirements, download them as 128k files. After downloading files, move them into subfolders. Change to each sub folder and run the conversion and sanitize names script to make sure they play on google music on android:</p> <div class="highlight"><pre><span></span><code><span class="ch">#!/bin/bash</span> <span class="c1">#</span> <span class="c1"># Convert downloaded files from mpsyt into mp3s</span> <span class="c1"># Sanitize the filenames so they will play on google play</span> <span class="c1">#</span> <span class="c1"># Run this in the directory of downloaded files</span> <span class="c1">#</span> <span class="k">for</span><span class="w"> </span>i<span class="w"> </span><span class="k">in</span><span class="w"> </span>*.webm <span class="k">do</span> ffmpeg<span class="w"> </span>-i<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span><span class="w"> </span>-ab<span class="w"> </span>128k<span class="w"> </span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">i</span><span class="p">%webm</span><span class="si">}</span><span class="s2">mp3&quot;</span> rm<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span> <span class="k">done</span> <span class="k">for</span><span class="w"> </span>i<span class="w"> </span><span class="k">in</span><span class="w"> </span>*.m4a <span class="k">do</span> ffmpeg<span class="w"> </span>-i<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span><span class="w"> </span>-ab<span class="w"> </span>128k<span class="w"> </span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">i</span><span class="p">%m4a</span><span class="si">}</span><span class="s2">mp3&quot;</span> rm<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span> <span class="k">done</span> <span class="k">for</span><span class="w"> </span>i<span class="w"> </span><span class="k">in</span><span class="w"> </span>*.ogg <span class="k">do</span> ffmpeg<span class="w"> </span>-i<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span><span class="w"> </span>-ab<span class="w"> </span>128k<span class="w"> </span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">i</span><span class="p">%ogg</span><span class="si">}</span><span class="s2">mp3&quot;</span> rm<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span> <span class="k">done</span> <span class="k">for</span><span class="w"> </span>i<span class="w"> </span><span class="k">in</span><span class="w"> </span>*.opus <span class="k">do</span> ffmpeg<span class="w"> </span>-i<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span><span class="w"> </span>-ab<span class="w"> </span>128k<span class="w"> </span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">i</span><span class="p">%opus</span><span class="si">}</span><span class="s2">mp3&quot;</span> rm<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span> <span class="k">done</span> <span class="k">for</span><span class="w"> </span>i<span class="w"> </span><span class="k">in</span><span class="w"> </span>*.mp4 <span class="k">do</span> ffmpeg<span class="w"> </span>-i<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span><span class="w"> </span>-ab<span class="w"> </span>128k<span class="w"> </span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">i</span><span class="p">%mp4</span><span class="si">}</span><span class="s2">mp3&quot;</span> rm<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$i</span><span class="s2">&quot;</span> <span class="k">done</span> <span class="c1"># From:</span> <span class="c1"># https://odoepner.wordpress.com/2011/10/13/bash-script-to-\</span> <span class="c1"># recursively-sanitize-folder-and-file-names/</span> sanitize<span class="o">()</span><span class="w"> </span><span class="o">{</span> <span class="w"> </span><span class="nb">shopt</span><span class="w"> </span>-s<span class="w"> </span>extglob<span class="p">;</span> <span class="w"> </span><span class="nv">filename</span><span class="o">=</span><span class="k">$(</span>basename<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$1</span><span class="s2">&quot;</span><span class="k">)</span> <span class="w"> </span><span class="nv">directory</span><span class="o">=</span><span class="k">$(</span>dirname<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$1</span><span class="s2">&quot;</span><span class="k">)</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename</span><span class="p">//+([^[:</span><span class="nv">alnum</span><span class="p">:]_-</span><span class="se">\.</span><span class="p">])/_</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="c1"># The idea is this is easier to read</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\:</span><span class="p">/_</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\!</span><span class="p">/_</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\?</span><span class="p">/_</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\é</span><span class="p">/e</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\è</span><span class="p">/e</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ü</span><span class="p">/u</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ô</span><span class="p">/o</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ç</span><span class="p">/c</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ñ</span><span class="p">/n</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\å</span><span class="p">/a</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\æ</span><span class="p">/ae</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\Œ</span><span class="p">/oe</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ø</span><span class="p">/o</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="nv">filename_clean</span><span class="o">=</span><span class="s2">&quot;</span><span class="si">${</span><span class="nv">filename_clean</span><span class="p">//</span><span class="se">\ß</span><span class="p">/B</span><span class="si">}</span><span class="s2">&quot;</span> <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="o">(</span><span class="nb">test</span><span class="w"> </span><span class="s2">&quot;</span><span class="nv">$filename</span><span class="s2">&quot;</span><span class="w"> </span>!<span class="o">=</span><span class="w"> </span><span class="s2">&quot;</span><span class="nv">$filename_clean</span><span class="s2">&quot;</span><span class="o">)</span> <span class="w"> </span><span class="k">then</span> <span class="w"> </span>mv<span class="w"> </span>-v<span class="w"> </span>--backup<span class="o">=</span>numbered<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$1</span><span class="s2">&quot;</span><span class="w"> </span><span class="s2">&quot;</span><span class="nv">$directory</span><span class="s2">/</span><span class="nv">$filename_clean</span><span class="s2">&quot;</span> <span class="w"> </span><span class="k">fi</span> <span class="o">}</span> <span class="nb">export</span><span class="w"> </span>-f<span class="w"> </span>sanitize find<span class="w"> </span><span class="nv">$1</span><span class="w"> </span>-depth<span class="w"> </span>-exec<span class="w"> </span>bash<span class="w"> </span>-c<span class="w"> </span><span class="s1">&#39;sanitize &quot;$0&quot;&#39;</span><span class="w"> </span><span class="o">{}</span><span class="w"> </span><span class="se">\;</span> </code></pre></div> <p>Move them to a folder on an external micro-sd card, then put the card in the phone. Play directly from the phone over bluetooth to the Bose in-ears. Don't even connect the over ears to bluetooth anything, just leave them as noise cancelling. As you come across entries on the phone that don't meet the criteria, delete them directly on the phone.</p> <div class="panel"> <div class="panel-body"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2017-09-23T00:00:00-04:00"> Sat 23 September 2017</time> </span> <span class="label label-default">Tags</span> <a href="/tag/music.html">music</a> </footer><!-- /.post-info --> </div> </div> </div> <!-- /.entry-content --> </article> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/files/cached_developerworks_html/os-perlgdchart.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><title>Create custom data charting tools using Perl and GD</title><meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <link rel="schema.DC" href="http://purl.org/DC/elements/1.0/" /> <link rel="SHORTCUT ICON" href="http://www.ibm.com/favicon.ico" /> <meta name="Owner" content="dW Information/Raleigh/IBM" /> <meta name="DC.Language" scheme="rfc1766" content="en-US" /> <meta name="IBM.Country" content="ZZ" /> <meta name="Security" content="Public" /> <!-- <meta name="IBM.SpecialPurpose" content="SP001" /> <meta name="IBM.PageAttributes" content="sid=1003"/> --> <meta name="Source" content="Based on v14 Template Generator, Template 14"/> <meta name="Abstract" content="Create professional-looking charts for data visualization using Perl and GD. Move beyond standard pie charts to incorporate annotations, indicators, and layering for enhanced informational delivery." /><meta name="Description" content="Create professional-looking charts for data visualization using Perl and GD. Move beyond standard pie charts to incorporate annotations, indicators, and layering for enhanced informational delivery.f " /><meta name="Keywords" content="Perl, GD, graphs, image manipulation, <NAME>, open source, tttosca" /><meta name="DC.Date" scheme="iso8601" content="2007-04-24" /><meta name="DC.Type" scheme="IBM_ContentClassTaxonomy" content="CT316" /><meta name="DC.Subject" scheme="IBM_SubjectTaxonomy" content="" /><meta name="DC.Rights" content="Copyright (c) 2007 by IBM Corporation" /> <meta name="Robots" content="index,follow" /><meta name="IBM.Effective" scheme="W3CDTF" content="2007-04-24" /><meta name="Last update" content="02052007<EMAIL>" /><!-- STYLESHEETS/SCRIPTS --> <!-- for tables --> <link rel="stylesheet" type="text/css" media="screen,print" href="//www.ibm.com/common/v14/table.css" /> <!-- end for tables --> <script language="JavaScript" src="/developerworks/js/dwcss14.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="//www.ibm.com/common/v14/main.css" /> <link rel="stylesheet" type="text/css" media="all" href="//www.ibm.com/common/v14/screen.css" /> <link rel="stylesheet" type="text/css" media="print" href="//www.ibm.com/common/v14/print.css" /> <script language="JavaScript" src="//www.ibm.com/common/v14/detection.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/js/dropdown.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/email/grabtitle.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/email/emailfriend2.js" type="text/javascript"></script><script language="JavaScript" src="/developerworks/js/urltactic.js" type="text/javascript"></script><script language="JavaScript" type="text/javascript"> <!-- setDefaultQuery('opensourceart'); //--> </script> <!--START RESERVED FOR FUTURE USE INCLUDE FILES--><script language="javascript" src="/developerworks/js/ajax1.js" type="text/javascript"></script><script language="javascript" src="/developerworks/js/searchcount.js" type="text/javascript"></script><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><script language="JavaScript" type="text/javascript">var emailAbstract = "Create professional-looking charts for data visualization using Perl and GD. Move beyond standard pie charts to incorporate annotations, indicators, and layering for enhanced informational delivery."; </script></head><BR><BR>This is an archived cached-text copy of the developerWorks article. Please consider viewing the original article at: <a href="http://www-128.ibm.com/developerworks/library/os-perlgdchart">IBM developerWorks</a><BR><BR><BR><BR><body><!--MASTHEAD_BEGIN--><table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td class="bbg" width="110"><a href="http://www.ibm.com/"><img alt="IBM&reg;" border="0" height="52" src="//www.ibm.com/i/v14/t/ibm-logo.gif" width="110"/></a></td> <td class="bbg"><img src="//www.ibm.com/i/c.gif" width="1" height="1" border="0" alt="" /></td> <td align="right" class="mbbg" width="650"> <table border="0" cellpadding="0" cellspacing="0" align="right" > <tr class="cty-tou"> <td rowspan="2" width="17" class="upper-masthead-corner"><a href="#main"><img src="//www.ibm.com/i/c.gif" border="0" width="1" height="1" alt="Skip to main content"/></a></td> <td align="left"> <table border="0" cellpadding="0" cellspacing="0" align="left"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span><b class="country">Country/region</b><span class="spacer">&nbsp;[</span><a class="ur-link" href="http://www.ibm.com/developerworks/country/">select</a><span class="spacer">]</span></td> <td width="29" class="upper-masthead-divider">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td align="left"><a class="ur-link" href="http://www.ibm.com/legal/">Terms of use</a></td> </tr> </table> </td> <td width="40">&nbsp;</td> </tr> <tr> <td class="cty-tou-border" height="1" colspan="2"><img src="//www.ibm.com/i/c.gif" alt="" height="1" width="1"/></td> </tr> <tr> <td colspan="3"><img alt="" height="8" src="//www.ibm.com/i/c.gif" width="1"/></td> </tr> <tr> <td>&nbsp;</td> <td align="center" colspan="2"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <form method="get" action="//www.ibm.com/developerworks/search/searchResults.jsp" id="form1" name="form1"><input type="hidden" name="searchType" value="1"/><input type="hidden" name="searchSite" value="dW"/> <td width="18"><label for="q"><img src="//www.ibm.com/i/c.gif" width="1" height="1" alt="Search in:"/></label></td> <td align="right"><select id="sq" name="searchScope" class="input-local" size="1"> <label for="sq"><option value="dW" selected>All of dW</option> <option value="dW">-----------------</option> <option value="aixunix">&nbsp;&nbsp;AIX and UNIX</option> <option value="eserver">&nbsp;&nbsp;IBM Systems</option> <option value="db2">&nbsp;&nbsp;Information Mgmt</option> <option value="lotus">&nbsp;&nbsp;Lotus</option> <option value="rdd">&nbsp;&nbsp;Rational</option> <option value="tivoli">&nbsp;&nbsp;Tivoli</option> <option value="WSDD">&nbsp;&nbsp;WebSphere</option> <option value="dW">-----------------</option> <option value="archZ">&nbsp;&nbsp;Architecture</option> <option value="acZ">&nbsp;&nbsp;Autonomic computing</option> <option value="gridZ">&nbsp;&nbsp;Grid computing</option> <option value="javaZ">&nbsp;&nbsp;Java technology</option> <option value="linuxZ">&nbsp;&nbsp;Linux</option> <option value="opensrcZ">&nbsp;&nbsp;Open source</option> <option value="paZ">&nbsp;&nbsp;Power Architecture</option> <option value="webservZ">&nbsp;&nbsp;SOA &amp; Web services</option> <option value="webarchZ">&nbsp;&nbsp;Web development</option> <option value="xmlZ">&nbsp;&nbsp;XML</option> <option value="dW">-----------------</option> <option value="forums">&nbsp;&nbsp;dW forums</option> <option value="dW">-----------------</option> <option value="aW">alphaWorks</option> <option value="dW">-----------------</option> <option value="all">All of IBM</option> </label></select></td> <td width="7" align="right"><label for="q"><img src="//www.ibm.com/i/c.gif" width="1" height="1" alt="Search for:"/></label>&nbsp;&nbsp;</td> <td align="right"><input class="input" id="q" maxlength="100" name="query" size="15" type="text" value=""/> </td> <td width="7">&nbsp; </td> <td width="90"><input alt="Search" name="Search" src="//www.ibm.com/i/v14/t/search.gif" type="image" value="Search" /></td> <!-- <td width="20">&nbsp;</td> --> </form> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td class="blbg" colspan="3"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span></td> <td><a class="masthead-mainlink" href="http://www.ibm.com/">Home</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/products/">Products</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/servicessolutions/">Services &amp; industry solutions</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/support/">Support &amp; downloads</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/account/">My IBM</a></td> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <script src="//www.ibm.com/common/v14/pmh.js" language="JavaScript" type="text/javascript"></script><!--MASTHEAD_END--><!-- CMA ID for this content is: 210043 --> <table id="v14-body-table" border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><!--LEFTNAV_BEGIN--><td id="navigation" width="150"><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="left-nav-spacer"><a href="http://www.ibm.com/developerworks" class="left-nav-overview"> </a></td></tr></table><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td colspan="2" class="left-nav-overview"><a href="http://www.ibm.com/developerworks" class="left-nav-overview">developerWorks</a></td></tr></table><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td colspan="2" class="left-nav-highlight"><a href="#" class="left-nav">In this article:</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10059" class="left-nav-child">Requirements</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10078" class="left-nav-child">Building the super-pie base</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N100CE" class="left-nav-child">compositePieIndicators.pl -- GD annotation</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N1014D" class="left-nav-child">Further modifications</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10180" class="left-nav-child">Conclusion</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#download" class="left-nav-child">Download</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#resources" class="left-nav-child">Resources</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#author" class="left-nav-child">About the author</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#rate" class="left-nav-child">Rate this page</a></td></tr><tr class="left-nav-last"><td width="14"><img class="display-img" alt="" height="1" width="14" src="//www.ibm.com/i/c.gif"/></td><td width="136"><img class="display-img" alt="" height="19" width="136" src="//www.ibm.com/i/v14/t/left-nav-corner.gif"/></td></tr></table><br /><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="related" colspan="2"><b class="related">Related links</b></td></tr><tr class="rlinks"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/rl-bullet.gif"/></td><td><a class="rlinks" href="http://www.ibm.com/developerworks/views/opensource/library.jsp">Open source technical library</a></td></tr><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- No content currently --><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><tr><td width="14"><img class="display-img" alt="" height="1" width="14" src="//www.ibm.com/i/c.gif"/></td><td width="136"><img class="display-img" alt="" height="19" width="136" src="//www.ibm.com/i/c.gif"/></td></tr></table><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- Next Steps Area: Start --> <!-- Commented out the include call in the dwmaster version of this file to prevent ajax calls being made during article previews and testing. Live site has uncommented copy of this file (jpp) --> <!-- Call Next Steps Servlet --> <script language="JavaScript" type="text/javascript"> <!-- /* * ajaxInclude makes a call to the url and render the results in the div tag specified in divId */ function ajaxInclude(url, divId) { var req = newXMLHttpRequest(); if (req) { req.onreadystatechange = getReadyStateHandler(req, function (result) { var contents = document.getElementById(divId); if (result != null && result.length > 0 && contents != null) { contents.innerHTML = result; } }); req.open("GET", url, true); req.send(""); } } //--> </script> <!-- Display Next Steps Result --> <div id="nextsteps"></div> <!-- Initiate Next Steps Call --> <script language="JavaScript" type="text/javascript"> <!-- ajaxInclude("/developerworks/niagara/jsp/getNiagaraContent.jsp?url="+window.location.href,"nextsteps"); //--> </script> <!-- Next Steps Area: End --><!--END RESERVED FOR FUTURE USE INCLUDE FILES--></td><!--LEFTNAV_END--><td width="100%"><table id="content-table" border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td width="100%"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td><a name="main"><img border="0" alt="skip to main content" height="1" width="592" src="//www.ibm.com/i/c.gif"/></a></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td height="18" width="10"><img alt="" height="18" width="10" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><img alt="" height="6" width="1" src="//www.ibm.com/i/c.gif"/><br /><a href="http://www.ibm.com/developerworks/" class="bctl">developerWorks</a><span class="bct">  &gt;  </span><a class="bctl" href="http://www.ibm.com/developerworks/opensource/">Open source</a><span class="bct">  &gt;</span><img alt="" height="1" width="1" src="//www.ibm.com/i/c.gif"/><br /><h1>Create custom data charting tools using Perl and GD</h1><p id="subtitle"><em>Deliver professional-looking graphs and visualizations automatically</em></p><img alt="" height="6" width="1" src="//www.ibm.com/i/c.gif" class="display-img"/></td><td class="no-print" width="192"><a href="http://www.ibm.com/developerworks/"><img alt="developerWorks" border="0" height="18" width="192" src="/developerworks/i/dw.gif"/></a></td></tr></table></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><table class="no-print" border="0" width="160" cellspacing="0" cellpadding="0" align="right"><tr><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="v14-header-1-small">Document options</td></tr></table><table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td class="no-padding" width="150"><table width="143" cellspacing="0" cellpadding="0" border="0"><script language="JavaScript" type="text/javascript"> <!-- document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img alt="Set printer orientation to landscape mode" height="16" src="//www.ibm.com/i/v14/icons/printer.gif" width="16" vspace="3" /></td><td width="122"><p><b><a class="smallplainlink" href="javascript:print()">Print this page</a></b></p></td></tr>'); //--> </script> <noscript></noscript><script language="JavaScript" type="text/javascript"> <!-- 5.6 10/24 llk: added cdata around the subdirectory path of email gif--> <!-- document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="Email this page" /></td><td width="122"><p><a class="smallplainlink" href="javascript:void newWindow()"><b>E-mail this page</b></a></p></td></tr>'); //--> </script><noscript><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td width="16"><img alt="" width="16" height="16" src="//www.ibm.com/i/c.gif"/></td><td class="small" width="122"><p><span class="ast">Document options requiring JavaScript are not displayed</span></p></td></tr></noscript><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td width="16"><img alt="" vspace="3" border="0" width="16" height="16" src="//www.ibm.com/i/v14/icons/dn.gif"/></td><td width="122"><p><a href="#download" class="smallplainlink"><b>Sample code</b></a></p></td></tr></table></td></tr></table><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- 11/28/07 refreshed by gem, per MOC --> <!--<br /><table border="0" cellpadding="0" cellspacing="0" width="150"><tr><td class="v14-header-2-small">New forum features</td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="v14-gray-table-border"><tr><td width="150" class="no-padding"><table border="0" cellpadding="0" cellspacing="0" width="143"><tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td><img src="//www.ibm.com/i/v14/icons/fw_bold.gif" height="16" width="16" border="0" vspace="3" alt=""/></td><td width="125"><p><a href="http://www.ibm.com/developerworks/community/forum/?S_TACT=105AGX01&amp;S_CMP=LEAF" class="smallplainlink">Try private messaging, read-tracking, and more </a> </p></td></tr></table></td></tr></table>--><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><br /><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="v14-header-2-small">Rate this page</td></tr></table><table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td class="no-padding" width="150"><table width="143" cellspacing="0" cellpadding="0" border="0"><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td><img alt="" vspace="3" border="0" width="16" height="16" src="//www.ibm.com/i/v14/icons/d_bold.gif"/></td><td width="125"><p><a href="#rate" class="smallplainlink"><b>Help us improve this content</b></a></p></td></tr></table></td></tr></table><br /></td></tr></table><p>Level: Intermediate</p><p><a href="#author"><NAME></a> (<a href="mailto:<EMAIL>?subject=Create custom data charting tools using Perl and GD"><EMAIL></a>), Programmer, IBM<br /></p><p> 24 Apr 2007</p><blockquote>Create professional-looking charts for data visualization using Perl and GD. Move beyond standard pie charts to incorporate annotations, indicators, and layering for enhanced informational delivery.</blockquote><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><script language="JavaScript" type="text/javascript"> <!-- if (document.referrer&&document.referrer!="") { // document.write(document.referrer); var q = document.referrer; var engine = q; var isG = engine.search(/google\.com/i); var searchTerms; //var searchTermsForDisplay; if (isG != -1) { var i = q.search(/q=/); var q2 = q.substring(i+2); var j = q2.search(/&/); j = (j == -1)?q2.length:j; searchTerms = q.substring(i+2,i+2+j); if (searchTerms.length != 0) { searchQuery(searchTerms); document.write("<div id=\"contents\"></div>"); } } } //--> </script><!--END RESERVED FOR FUTURE USE INCLUDE FILES--> <p>More than just another "pie-graphs-with-GD" tutorial, this article describes techniques you can use to create new levels of usefulness in your dynamically generated charts. Cook up some automatically generated graphs for your organizational meetings or live enterprise directory data. Annotate the charts with readable text that delivers more information than the standard pie chart.</p> <p>Perl and the GD modules have been used together for many years to create useful dynamic charts and graphics for Web sites and presentations. This article shows how to use these tools to create professional-looking, focused, and highly informative charts in near real time for your organizational needs.</p> <p>Using a modified version of the GD::Pie.pm module, we will build custom charts, then use the acquired data points to create indicators and text annotations. Additionally, we show a method of layering geometric primitives and using transparent pass-throughs to create separate channels of information inside the charts.</p> <p>The techniques described allow you to create complex charts and use the GD tools as starting points for creating your own programs.</p> <p><a name="N10059"><span class="atitle">Requirements</span></a></p> <p><a name="N1005F"><span class="smalltitle">Hardware</span></a></p> <p>Any PC manufactured after 2000 should provide enough horsepower for compiling and running the code. The layering and annotation processes are CPU-intensive, so if you plan to create many of these charts on the fly on a Web server, faster and multiple processors offer better user experiences. </p> <p><a name="N10068"><span class="smalltitle">Software</span></a></p> <p>Assuming your operating environment of choice contains a recent version of Perl, you'll need to download and install the <a href="http://search.cpan.org/~lds/GD-2.35/">GD Perl module</a>. You might also consider using a fast and simple image viewer application like <i>feh</i>.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N10078"><span class="atitle">Building the super-pie base</span></a></p> <p><a name="N1007E"><span class="smalltitle">buildPie.pl program</span></a></p> <p>The first component of the advanced chart creation process is to build a relatively unmodified pie chart. Users of the GD::Pie module may be familiar with its requirements for data and labels when plotting. The plot subroutine of the GD::Pie module expects an array of arrays (labels and data values). For example, Listing 1 shows an input file that will be used to build the charts in this article.</p> <br /><a name="N1008B"><b>Listing 1. test.pie.data example data file</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> #50#Alpha# #30#Baker# #20#Charlie# #60#Delta# #10#Echo Echo# </pre></td></tr></table><br /> <p>The buildPie.pl program reads this data file and generate a simple chart using a modified version of GD::Pie. Listing 2 shows the buildPie.pl program.</p> <br /><a name="N10098"><b>Listing 2. buildPie.pl</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> #!/usr/bin/perl -w # buildPie.pl - build a simple pie chart using modified GD::Pie.pm use strict; use lib qw(./); use customPie; if( @ARGV != 1 ){ die "specify an output filename" } my( @name, @ratio ) = (); my $filename = $ARGV[0]; chomp($filename); while(&lt;STDIN&gt;){ my @parts = split "#", $_; push @name, " "; #add the names later push @ratio, $parts[1]; }#while stdin my $mygraph = GD::Graph::pie-&gt;new(600,600); # colors of the pie slices $mygraph-&gt;set( dclrs =&gt; [ "#A8A499","#685E3F","#6C7595","#D8E21F", "#D19126","#B5B87D","#B7C8E2","#DFE3E1" ] ); # color of pie divisors $mygraph-&gt;set( accentclr =&gt; '#0000ff'); $mygraph-&gt;set( '3d' =&gt;'0'); my @togr = ( [@name], [@ratio] ); my $myimage = $mygraph-&gt;plot(\@togr) or die $mygraph-&gt;error; open(IMG, "&gt; $filename.pie.png") or die $1; binmode IMG; print IMG $myimage-&gt;png; close(IMG); </pre></td></tr></table><br /> <p>This code reads the data file as shown in the test.pie.data file. Only the data values are recorded at this point, as the labels will be applied later in the chart-generation process. After the data values have been read, a 600x600 charting canvas is created, and the pie colors are defined. Note that the color selection is important because these colors will be used later in the process for transparency creation. </p> <p>The chart is then plotted after turning 3-D drawing off and specifying blue for the pie divisors color. Run the program with the command <code>cat test.pie.data | perl buildPie.pl step1 &gt; triangle.vertices</code>. You can use your image viewer to look at the step1.pie.png graphic, but it won't be any more impressive than a regular pie chart at this point. The key to note is the fact that <code>STDOUT</code> is being redirected to the triangle.vertices file. These vertices for the triangle indicators are created in our modified version of GD::Pie.</p> <p><a name="N100AC"><span class="smalltitle">customPie.pm</span></a></p> <p>The GD::Pie module does the bulk of the work of calculating proportional pie slices, labeling the slices and filling the pies with color. The modifications below only change the width of the pie divisor lines and compute the approximate locations of a polygon centered around the edges of the pie slices for later annotation. Copy the existing pie.pm file into your local directory with the command <code>cp /usr/lib/perl5/site_perl/5.8.5/GD/Graph/pie.pm ./customPie.pm</code>.</p> <table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> # Draw the lines on the front of the pie $self-&gt;{graph}-&gt;line($xe, $ye, $xe, $ye + $self-&gt;{pie_height}, $ac) if in_front($pa) &amp;&amp; $self-&gt;{'3d'}; </pre></td></tr></table><br /> <p>For our modifications to be effective, replace the lines in customPie.pm shown above (starting at line number 270) with the code below.</p> <br /><a name="N100C5"><b>Listing 3. customPie.pm new lines</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> # Give the pie slices a nice wide divider $self-&gt;{graph}-&gt;setThickness(5); $self-&gt;{graph}-&gt;line($self-&gt;{xc}, $self-&gt;{yc}, $xe, $ye, $ac); # inward facing point of the triangle my ($newxe, $newye) = cartesian( 3 * $self-&gt;{w}/6.5, ($pa+$pb)/2, $self-&gt;{xc}, $self-&gt;{yc}, $self-&gt;{h}/$self-&gt;{w} ); # first corner my $tangle = (($pa+$pb)/2) + 5; my ($corn1xe, $corn1ye) = cartesian( 3 * $self-&gt;{w}/5.5, $tangle, $self-&gt;{xc}, $self-&gt;{yc}, $self-&gt;{h}/$self-&gt;{w} ); # second corner $tangle = (($pa+$pb)/2) - 5; my ($corn2xe, $corn2ye) = cartesian( 3 * $self-&gt;{w}/5.5, $tangle, $self-&gt;{xc}, $self-&gt;{yc}, $self-&gt;{h}/$self-&gt;{w} ); print "polygon: $newxe,$newye $corn1xe,$corn1ye $corn2xe,$corn2ye\n"; </pre></td></tr></table><br /> <p>The five-pixel line divisor will be overwritten later as a white separator between pie slices in the image. Three roughly defined corner edges are then acquired that define an approximately equilateral triangle pointed at the center of the image. To facilitate modification and annotation of the image, the triangle coordinates are printed out to be applied to the image later.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N100CE"><span class="atitle">compositePieIndicators.pl -- GD annotation</span></a></p> <p>While the buildPie.pl program is set up to create a simple pie graph with our modified pie.pm, the further work of modification and annotation is done in <code>compositePieIndicators.pl</code>. Recall that you used <code>buildPie.pl</code> to create a simple pie chart like that shown under Step 1 in Figure 1. We want to take that pie chart and transform it into the Step 2 graphic from Figure 1.</p> <br /><a name="fig1"><b>Figure 1. Step pie diagrams</b></a><br /> <img alt="Step pie diagrams" height="286" src="pie_step1_step2.gif" width="572"/> <br /> <br /> <p>After reading in the Step 1 pie chart, polygons specified by the triangle vertices file are drawn on the Step 1 chart. The edge of the new pie chart is smoothed, the pie radial divisors are colored white, and the interior of the pie chart is made white. Following this process, a black ring is drawn around inside of the graph, and text indicators are added near the various pie slices. </p> <p>Let's break apart the <code>compositePie.pl</code> program into three main chunks and cover how each of these steps is done in detail.</p> <br /><a name="N100FE"><b>Listing 4. compositePieIndicators.pl Section 1 -- Reading image, polygon coordinates</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> #!/usr/bin/perl -w # compositePieIndicators.pl - build super pie graphics use strict; use GD; die "usage: compositePieIndicators.pl image_file " . "vertices_file &lt;main title&gt; &lt;sub title&gt; data_file output_file" unless @ARGV == 6; my $pieImg = newFromPng GD::Image( $ARGV[0] ); my $white = $pieImg-&gt;colorAllocate(255,255,255); my @textLocs = (); # draw the pie slices open( POLYFILE, "$ARGV[1]" ) or die "can't open vertices file $ARGV[1]"; while( my $polyLine = &lt;POLYFILE&gt; ) { my (undef, @polyParts ) = split " ", $polyLine; my $poly = new GD::Polygon; my $textPos = 0; for ( @polyParts ){ my( $px, $py ) = split ","; $poly-&gt;addPt( $px,$py ); next unless $textPos == 0; push @textLocs, "$px, $py"; $textPos = 1; }#for each polygon part $pieImg-&gt;filledPolygon( $poly, $white ); }#polyCoords close(POLYFILE); </pre></td></tr></table><br /> <p>Section 1 of the <code>compositePieIndicators.pl</code> program covers the usage statement and reading in the base pie image, as well as the triangle.vertices file. Defining the color white on line 10 is important to ensure that the various drawing commands complete as expected. GD requires explicit color establishment in some cases, and by defining white, we can ensure that the image is processed correctly. </p> <p>The next step is to draw all the triangles as specified in the <code>triangle.vertices</code> file. Each point of the polygon is added to the temporary shape on line 23, and if it's the first point in the polygon, its location is recorded as the placement for the text annotating that piece.</p> <br /><a name="N10116"><b>Listing 5. compositePieIndicators.pl Section 2 -- Drawing shapes, text</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> my $whiteImg = new GD::Image(1000,1000); my $secWhite = $whiteImg-&gt;colorAllocate(255,255,255); my $black = $whiteImg-&gt;colorAllocate(0,0,0); $whiteImg-&gt;copy( $pieImg, 200,200, 0,0, 600,600 ); # now build a squarish border to hide the drawing artifacts my $circleImg = new GD::Image( 600,600 ); my $circlewhite = $circleImg-&gt;colorAllocate(255,255,255); my $circleblack = $circleImg-&gt;colorAllocate(0,0,0); $circleImg-&gt;filledArc(300,300, 580,580, 0,360,$black); $circleImg-&gt;transparent($circleblack); $whiteImg-&gt;copy($circleImg,200,200,0,0,600,600); # make the pie radial divisor arms white $whiteImg-&gt;fill(500,500,$secWhite); # draw center white circle area for text $whiteImg-&gt;filledArc( 500,500, 440,440, 0,360, $secWhite ); # draw black border around text area - with line arc $whiteImg-&gt;setThickness(4); $whiteImg-&gt;arc( 500,500, 425,425, 0,360, $black ); # main title $whiteImg-&gt;stringFT( $black, './Vera.ttf', 45,0,350,470, "$ARGV[2]" ); # sub title $whiteImg-&gt;stringFT( $black, './Vera.ttf', 32,0,370,560, "$ARGV[3]" ); </pre></td></tr></table><br /> <p>The first part of Section 2 of <code>compositePieIndicators.pl</code> creates a new image of 1,000 pixels square. After defining some colors, the base pie image is loaded into the center of the new image (by creating a 200-pixel border around the entire image, effectively expanding a 600x600 image to 1,000x100 without stretching the original). This is essential for allowing extended text annotations to remain within the image area without clipping. </p> <p>To cut the leading edge of the pie slices in a simple circle pattern, an image is created with a transparent circle in the middle. After copying this onto the existing image, the radial divisor arms are colored white with a simple fill command specified to begin at the center of the image, where all of the divisor arms meet. Next, the center of the pie is erased by drawing a white circle, and another arc is drawn to provide a visual border between the interior circle and the peripheral pie slices. The main title and subtitle for the graph are then drawn in the center of the image. The Vera.ttf font file is available in the <a href="#downloads">Downloads</a> package, or you can use another TrueType font available on your system. </p> <p>Listing 6 shows the code required to annotate the various pie slices.</p> <br /><a name="N10131"><b>Listing 6. compositePieIndicators.pl Section 3 -- Annotating slices</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> # draw the labels for the pie slices open( DATAFILE, "$ARGV[4]" ) or die "can't open data file "; my $arrayPos = 0; while( my $line = &lt;DATAFILE&gt; ) { my( undef, undef, $text ) = split '#', $line; my( $posx, $posy ) = split ',', $textLocs[$arrayPos]; print "text $text at pos $textLocs[$arrayPos] \n"; # the kludge text alignment zone $posx += 200; $posy += 200; my $ptSize = 18; if( $posx &lt;= 500 ){ if( $posy &lt;= 500 ){ # nudge left, up if upper left $posx -= 70; $posy -= 20; }else{ # nudge left, down if upper left $posx -= 100; $posy += 20; } }else{ if( $posy &lt;= 500 ){ # nudge left, down if upper right $posy -= 20; $posx += 10; }else{ # nudge right, down if lower right $posy += 20 ; $posx += 25 ; } }#if left or right of image # nudge text down if right enough if( $posy &gt; 600 ){ $posy += 10 } $whiteImg-&gt;stringFT( $black, './Vera.ttf', $ptSize,0,$posx,$posy, "$text" ); $arrayPos++; }#while data file line close(DATAFILE); open( TILEOUT,"&gt; $ARGV[5]") or die "can't write out file "; print TILEOUT $whiteImg-&gt;png; close(TILEOUT); </pre></td></tr></table><br /> <p>Recall from Section 1 of <code>compositePieIndicators.pl</code> that the location of the text is defined as the first set of polygon coordinates on a line from the <code>triangle.vertices</code> file. This x,y value is stored in the textLocs array and is extracted for the respective text annotation line as defined in the data file. It turns out that accurately placing text aligned vertically and horizontally around the perimeter of a circle is somewhat complicated, so a simple trial-and-error approach is shown on lines 80-107. Although a bit clumsy, it's s simple way to have each of the text annotations appear in a reasonably close proximity to their appropriate pie slices. </p> <p>Once the text coordinate acquisition kludge is complete, the text is written to the image, and the image as shown under Step 2 in Figure 1 is written out. Run <code>compositePieIndicators.pl</code> with the command <code>perl compositePieIndicators.pl test.pie.png triangle.vertices Managers 'Top 5 People' test.pie.data test.compout.png</code>.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N1014D"><span class="atitle">Further modifications</span></a></p> <p>You now have the capability for automatically generated, efficient, and professional pie chart graphs you can plug in to any number of applications. There's another layer of modification that can provide a lot of interest to the boring old pie chart: tiled slices. </p> <p>Create a large image made up of smaller tiles that comprise a subject related to the pie slice. For example, if we know Manager <i>Delta</i> works extensively with Linux&#174;, we can create a background tile image of many forms of Tux and replace the Delta pie slice colors with the tiled images. Continuing on through the pie slices, each component piece can be replaced with a different set of tile images. Figure 2 shows a completed example of what this can look like.</p> <br /><a name="fig2"><b>Figure 2. Mosaic pie diagrams</b></a><br /> <img alt="Mosaic pie diagrams" height="363" src="pie2_mosaic_600x600.jpg" width="402"/> <br /> <br /> <p>Each pie sliced is, in turn, set to transparent, and the mosaic background image is then applied to the pie graph. Listing 7 shows the sequence of commands used to produce the image in Figure 2. (See <a href="#resources">Resources</a> for more information about generating background mosaic images automatically.)</p> <br /><a name="N1017A"><b>Listing 7. Tiled image pie slice compositing</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> convert -transparent "#A8A499" test.compout.png lev1.png composite -compose over lev1.png backgrounds/back_big_linux.png lev2.png convert -transparent "#685E3F" lev2.png lev3.png composite -compose over lev3.png backgrounds/back_big_db2.png lev4.png convert -transparent "#6C7595" lev4.png lev5.png composite -compose over lev5.png backgrounds/back_big_diskdrive.png lev6.png convert -transparent "#D8E21F" lev6.png lev7.png composite -compose over lev7.png backgrounds/back_bigLinux.png lev8.png convert -transparent "#D19126" lev8.png lev9.png composite -compose over lev9.png backgrounds/back_big_micro.png completed_pie.png </pre></td></tr></table><br /> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N10180"><span class="atitle">Conclusion</span></a></p> <table align="right" border="0" cellspacing="0" cellpadding="0" width="150"><tr><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td><table border="1" cellspacing="0" cellpadding="5" width="100%"><tr><td bgcolor="#eeeeee"> <a name="N10189"><b>Share this...</b></a><br /> <p> <table border="0" cellpadding="0" cellspacing="0" width="135"><tr><td colspan="2"> <img alt="" border="0" height="5" src="http://www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"> <a href="http://digg.com/submit?phase=2&amp;url=http://www.ibm.com/developerworks/opensource/library/os-perlgdchart"> <img alt="digg" border="0" height="10" src="http://www.ibm.com/i/v14/icons/10x10-digg-thumb.gif" width="10"/> </a> </td><td> <a href="http://digg.com/submit?phase=2&amp;url=http://www.ibm.com/developerworks/opensource/library/os-perlgdchart">Digg this story</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="http://www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"> <a href="http://del.icio.us/post" onClick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=700,height=400'); return false;"> <img alt="del.icio.us" border="0" height="10" src="http://del.icio.us/static/img/delicious.small.gif" width="10"/> </a> </td><td> <a href="http://del.icio.us/post" onClick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=700,height=400'); return false;">Post to del.icio.us</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="http://www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"> <a href="javascript:location.href='http://slashdot.org/bookmark.pl?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title)"> <img alt="Slashdot" border="0" height="16" src="/developerworks/i/slashdot-favicon.gif" width="16"/> </a> </td><td> <a href="javascript:location.href='http://slashdot.org/bookmark.pl?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title)">Slashdot it!</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="http://www.ibm.com/i/c.gif" width="1"/> </td></tr></table> </p> </td></tr></table></td></tr></table> <p>Using the power of GD and Perl, you can link various data and images together to create sophisticated charts that will help bring visual interest to your applications. Using this program allows you to present charts with much greater informational density than is available with plain GD::Pie. Consider combining the charts you've created with geographical data plots or personnel images, or hit count data from your Web site. You can create many interesting diagrams with the code presented here, and you can use these techniques for further advancing your abilities with GD's processing options.</p> <br /><br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><span class="atitle"><a name="download">Download</a></span></p><table width="100%" class="data-table-1" cellspacing="0" cellpadding="0" border="0"><tr><th scope="col">Description</th><th scope="col">Name</th><th align="right" scope="col">Size</th><th scope="col">Download method</th></tr><tr><th class="tb-row" scope="row">Scripts and files</th><td nowrap="nowrap">os-perlgdchart_01.zip</td><td align="right" nowrap="nowrap">41KB</td><td nowrap="nowrap"><a class="fbox" href="http://www.ibm.com/developerworks/views/download.jsp?contentid=210043&amp;filename=os-perlgdchart_01.zip&amp;method=http&amp;locale=worldwide"><b>HTTP</b></a></td></tr></table><table cellspacing="0" cellpadding="0" border="0"><tr valign="top"><td colspan="5"><img alt="" width="12" height="12" border="0" src="//www.ibm.com/i/c.gif"/></td></tr><tr><td><img alt="" height="16" width="16" src="//www.ibm.com/i/v14/icons/fw.gif"/></td><td><a class="fbox" href="/developerworks/library/whichmethod.html">Information about download methods</a></td><td><img alt="" height="1" width="50" src="//www.ibm.com/i/c.gif"/></td></tr></table><br /><br /><p><a name="resources"><span class="atitle">Resources</span></a></p><b>Learn</b><br /><ul><li> Linux Gazette has a great article about <a href="http://linuxgazette.net/issue83/padala.html">GD Charts</a> of various kinds.<br /><br /></li><li> <NAME> wrote a GD::Graph::Pie how-to on <a href="http://www.wdvl.com/Authoring/Languages/Perl/Weave/chart1-4.html">Web Developers Virtual Library</a>.<br /><br /></li><li> The mosaic images are created using the build_background.pl program from "<a href="http://www.ibm.com/developerworks/library/os-mosaic/index.html">Create mosaic images with Perl and ImageMagick</a>" on developerWorks.<br /><br /></li><li> Read the author's article titled "<a href="http://www.ibm.com/developerworks/opensource/library/os-perlgdplot/">Create geographical plots of your data using Perl, GD, and plot-latlong</a>" to learn more about GD.<br /><br /></li><li> And see the author's "<a href="http://www.ibm.com/developerworks/opensource/library/os-mosaic/">Create mosaic images with Perl and ImageMagick</a>" to learn more about writing Perl scripts that automate image manipulation and text creation.<br /><br /></li><li> Browse all the <a href="http://www.ibm.com/developerworks/views/opensource/libraryview.jsp?">open source content</a> on developerWorks.<br /><br /></li><li> Stay current with developerWorks' <a href="http://www.ibm.com/developerworks/offers/techbriefings/?S_TACT=105AGX03&amp;S_CMP=art">Technical events and webcasts</a>.<br /><br /></li><li> Check out upcoming conferences, trade shows, webcasts, and other <a href="http://www.ibm.com/developerworks/views/opensource/events.jsp">Events</a> around the world that are of interest to IBM open source developers.<br /><br /></li><li> Visit the developerWorks <a href="http://www.ibm.com/developerworks/opensource">Open source zone</a> for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.<br /><br /></li></ul><br /><b>Get products and technologies</b><br /><ul><li> CPAN hosts the <a href="http://search.cpan.org/~lds/GD-2.35/">GD Image Processing</a> Perl module.<br /><br /></li><li> Innovate your next open source development project with <a href="http://www.ibm.com/developerworks/downloads/?S_TACT=105AGX44">IBM trial software</a>, available for download or on DVD.<br /><br /></li><li> Download <a href="http://www.ibm.com/developerworks/downloads/?S_TACT=105AGX01&amp;S_CMP=ART">IBM product evaluation versions</a>, and get your hands on application development tools and middleware products from DB2&#174;, Lotus&#174;, Rational&#174;, Tivoli&#174;, and WebSphere&#174;.</li></ul><br /><b>Discuss</b><br /><ul><li> Participate in <a href="http://www.ibm.com/developerworks/blogs">developerWorks blogs</a> and get involved in the developerWorks community.<br /><br /></li></ul><br /><br /><p><a name="author"><span class="atitle">About the author</span></a></p><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td colspan="3"><img alt="" width="100%" height="5" src="//www.ibm.com/i/c.gif"/></td></tr><tr align="left" valign="top"><td><p/></td><td><img alt="" width="4" height="5" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><p><NAME> is a programmer at IBM currently working with Linux and resource-locating technologies.</p></td></tr></table><br /><br /><br /><p class="no-print"><span class="atitle"><a name="rate">Rate this page</a></span></p><span class="no-print"><form action="http://www-128.ibm.com/developerworks/utils/RatingsHandler" method="post"><input value="1" name="SITE_ID" type="hidden"/><input value="Create custom data charting tools using Perl and GD" name="ArticleTitle" type="hidden"/><input value="Open source" name="Zone" type="hidden"/><input value="http://www.ibm.com/developerworks/thankyou/feedback-thankyou.html" name="RedirectURL" type="hidden"/><input value="210043" name="ArticleID" type="hidden"/><input value="04242007" name="publish-date" type="hidden"/><input type="hidden" name="author1-email" value="<EMAIL>" /><input type="hidden" name="author1-email-cc" value="" /><script language="javascript" type="text/javascript">document.write('<input type="hidden" name="url" value="'+location.href+'" />');</script><img width="100%" src="//www.ibm.com/i/v14/rules/gray_rule.gif" height="1" alt=""/><br /><table width="100%" class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td width="100%"><table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3"><p>Please take a moment to complete this form to help us better serve you.</p></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Goal">Did the information help you to achieve your goal?</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><input value="Yes" id="Goal" name="Goal" type="radio"/>Yes</td><td><input value="No" id="Goal" name="Goal" type="radio"/>No</td><td><input value="Don't know" id="Goal" name="Goal" type="radio"/>Don't know</td></tr></table></td><td width="100%"> </td></tr><tr><td colspan="3"><img alt="" height="12" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Comments">Please provide us with comments to help improve this page:</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><textarea class="iform" cols="35" rows="5" wrap="virtual" id="Comments" name="Comments"> </textarea></td></tr></table></td><td width="100%"> </td></tr><tr><td colspan="3"><img alt="" height="12" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Rating">How useful is the information?</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td align="left" width="60"><input value="1" id="Rating" name="Rating" type="radio"/>1</td><td align="left" width="60"><input value="2" id="Rating" name="Rating" type="radio"/>2</td><td align="left" width="60"><input value="3" id="Rating" name="Rating" type="radio"/>3</td><td align="left" width="60"><input value="4" id="Rating" name="Rating" type="radio"/>4</td><td align="left" width="63"><input value="5" id="Rating" name="Rating" type="radio"/>5</td></tr><tr><td align="left" width="60"><span class="greytext">Not</span><br /><span class="greytext">useful</span></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="63"><span class="greytext">Extremely<br />useful</span></td></tr></table></td><td width="100%"> </td></tr></table></td></tr></table><table class="v14-gray-table-border" width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3"><img alt="" height="8" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td colspan="3"><input alt="Submit" height="21" width="120" border="0" src="//www.ibm.com/i/v14/buttons/submit.gif" type="image"/></td></tr><tr><td colspan="3"><img alt="" height="8" width="8" src="//www.ibm.com/i/c.gif"/></td></tr></table></form><br /></span><span class="no-print"><table cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /></span></td><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td></tr></table></td></tr></table><!--FOOTER_BEGIN--><br /> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="bbg" height="19"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span><a class="mainlink" href="http://www.ibm.com/ibm/">About IBM</a></td> <td class="footer-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="mainlink" href="http://www.ibm.com/privacy/">Privacy</a></td> <td class="footer-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="mainlink" href="http://www.ibm.com/contact/">Contact</a></td> </tr> </table> </td> </tr> </table> <script type="text/javascript" language="JavaScript1.2" src="//www.ibm.com/common/stats/stats.js"></script> <noscript><img src="//stats.www.ibm.com/rc/images/uc.GIF?R=noscript" width="1" height="1" alt="" border="0" /></noscript><!--FOOTER_END--><!--XSLT stylesheet used to transform this file: dw-document-html-5.8.xsl--></body></html> <file_sep>/content/posts/learning_tactics.md Title: What are the tactics to learn this material? Date: 2017-09-15 Category: articles Tags: business model canvas What are your tactics used to achieve this? Perform the research, incorporation, execution cycle for each stage. <pre> Research: Stay focused on the strategies from the known effective materials. Read them backwards and forwards, and at different times of day. Incorporation: Part 1: Write card stack for the subject. Memorize the cards precisely, with no higher order thinking. Part 2: Verify full, random order memorization. Part 3: Enter the mind gym. (See resources below) Visualize who you are becoming with the integration of these skills after the completion of part 4. Exit the mind gym. Part 4: Change the venue, and pick a random card. Perform self-talk with the contents of the card based on your current circumstances and goals. Repeat for all cards. Execution: Use the tactics from the known effective materials. Perform the key activities for the current stage. </pre> ** Card Deck Images** [![Front of Card Deck](/images/learning/thumbnails/learning_res_inc_exc_card_deck_front.jpg)](/images/learning/learning_res_inc_exc_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_res_inc_exc_card_deck_back.jpg)](/images/learning/learning_res_inc_exc_card_deck_back.jpg) Resources for the mind gym: [The Way of the Seal](https://www.amazon.com/Way-SEAL-Think-Warrior-Succeed/dp/1621451097), by Mark Divine page 30 [SealFIT blog](https://sealfit.com/sealfit-blog-visualizing-success-part-3-plus-a-peak-performance-exercise/) <file_sep>/images/learning/bmfiddle_icons/convert_svg_to_png.sh #!/bin/bash for i in *.svg do convert -background none "$i" "${i%svg}png" done # Now convert them to thumbnails for i in *.png do convert -resize 50x50 "$i" "thumbnails/$i" done <file_sep>/content/developerworks/wa-googlecal.md Title: Integrate encryption into Google Calendar with Firefox extensions Date: 2008-07-15 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: wa-googlecal Provide basic encryption support for user data in one of the most popular online calendar applications. Building on the incredible flexibility of Firefox extensions and the Gnu Privacy Guard, this article shows you how to store only encrypted event descriptions in Google's Calendar application, while displaying a plain text version to anyone with the appropriate decryption keys. [Slashdotted](yro.slashdot.org/yro/08/07/20/1955243.shtml) <file_sep>/content/posts/darktable_workflow.md Title: Darktable image processing workflow Date: 2018-05-08 Category: articles Tags: productivity Instructions for using Darktable on a Linux system for digital photo processing. <pre> Camera: Nikon D3000 (2009) Laptop: Lenovo U430 Touch (2014) Storage: Microsd card in SD card adapter Eject card from Camera, place in laptop. Create the folder ~/Pictures/<timestamp> Copy just .NEF from SD Card/DCIM/100D3000/ to ~/Pictures/<timestamp> Start Darktable, press F11 to full screen Make sure you are in "Lighttable" mode Import -> folder Click folder: ~/Pictures/<timestamp> Click open Set 3-thumbnail view on bottom slider Make a first pass in Lighttable view, clicking the red x on any that are clearly rejects, out of focus, etc. Look through the entire roll for any corruption, other weirdness. You may have no rejects, and that is ok, this is partly just a sanity check so you can verify the local copy. Switch to darkroom mode, view all except rejected Now go through each image, and give a star level of 3 if acceptable. If you're unsure, don't reject, just give it a 1-2 star rating Feel free to keep all or mark as rejects all. The point is to go through and look at each photo for at least 1 second. The best way to do this is to keep the mouse cursor over the thumbnail at the bottom, then use the keys 1-5 for star rating. Then push space to go to the next image. Make sure the mouse cursor stays over the center thumbnail. Now View all 3 stars and above. Mark as leel 5 if it's the appropriate quality. Now View all 5 stars and above. Then do further refinements, editing, color balancing. To remove a photo, just give it a <5 star rating and it will disappear from the thumbnail list at the bottom. Remember to have your mouse over the photo you want to assign a star rating. </pre> <pre> Export to disk the selected images: Switch back to Lighttable view Choose 5 stars and above. Shift-Select all of the 5 star images. On the right side, go to Export Selected The default options are: Target storage: File on Disk $(FILE_FOLDER)/darktable_exported/$(FILE_NAME) jpeg 8-bit quality 95 Click export. </pre> <pre> Post on google workflow: With <EMAIL> go to: http://photos.google.com Click upload Choose all files from darktable exported jpg above. After upload is complete Click "Shared album" Click "New shared album" Give it a title, click share, click google plus Create a new post in the 'public' area </pre> <pre> Add to first-gen ipad screensaver picture workflow: Go to the darktable exported folder, for example: cd ~/Pictures/<timestamp>/darktable_exported/ mkdir smaller cd smaller cp ../*.jpg . mogrify -resize 50% *.jpg python -m http.server (python3) On the ipad, open safari, go to 192.168.0.70:8000 where 192.168.0.70 is the ip address of the computer running the python httpserver Click each file, after it loads hold-click, then 'save image' </pre> <pre> After images have been copied to the laptop, uploaded to google, and placed on the ipad: remove the sd card, place it back in the camera. Format the card when placed in the camera. </pre> <file_sep>/content/developerworks/os-mosperl.md Title: Create mosaic movies with Perl, ImageMagick and MPlayer Date: 2006-07-11 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-mosperl Movie mosaics with Perl, ImageMagick and mplayer, building on the photo mosaic article above, use Perl, ImageMagick and mplayer to create photo mosaic movies. <file_sep>/content/posts/learning_stage3.md Title: Stage Three: Meta-Business Model Canvas. Date: 2017-09-17 Category: articles Tags: business model canvas Third Stage: Meta-BMC - what makes a good business model canvas? **Research of known effective materials:** Udacity course: How to Build a Startup, Lesson 4: [Business Models and Customer Development]( https://classroom.udacity.com/courses/ep245/lessons/48726358/concepts/483919610923) 1. Hypothesis Or Guesses 5. Hypothesis testing Strategyzer: [Business model canvas instruction manual]( https://assets.strategyzer.com/assets/resources/the-business-model-canvas-instruction-manual.pdf) Strategyzer: [Designing crystal clear business model canvases]( https://assets.strategyzer.com/assets/resources/designing-crystal-clear-business-model-canvases.pdf) Strategyzer: [Business model design space card deck]( https://assets.strategyzer.com/assets/resources/the-business-model-design-space-card-deck.pdf) [Christian Doll Copy of the Business model design space card deck]( http://bicdo.de/wp-content/uploads/2014/03/Environment_Cards.pdf) <NAME>igneur Slide deck for [Disruptive Business Model](https://www.slideshare.net/ypigneur/disruptive-business-model-presentation) Strategyzer: [The business model canvas one page pdf:]( https://assets.strategyzer.com/assets/resources/the-business-model-canvas.pdf) [Google docs Template for the business model canvas]( https://docs.google.com/drawings/d/102mOZQmMxs0CslmNsPZ5KCNQwAIh9rh4baYgT0VWNAA/template/preview?usp=drive_web) Make sure to view the entire canvas here - there are sticky notes 'outside' the document. [Business Model Canvas "Fiddle"](https://bmfiddle.com/f/#/) ----------- #### Incorporation: **Card deck one of two: Meta Business Model Canvas** <pre> The business model canvas is just one tool. It has a place in the continuum of broad view and narrowly focused resources for modelling businesses. The business model canvas is shaped by four areas: Left is industry forces, Top is key trends, right is market forces, bottom is macro-economic trends Zooming in gives us customer development and agile engineering. A good business model canvas stays within it's boundaries. Sketch out new business ideas or visualize existing businesses. Used corporately as shared language to have better strategic conversations. Individually used to structure your thinking. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_meta_bmc_card_deck_front.jpg)](/images/learning/learning_meta_bmc_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_meta_bmc_card_deck_back.jpg)](/images/learning/learning_meta_bmc_card_deck_back.jpg) ** Card deck two of two: What makes a good business model canvas?** <pre> Coarse grained visual indicators: A large rectangle, suitable for the environment and the participants. Regular size 3x3" post it notes Black only, standard sharpie Ground rules for physical and virtual canvases: Don't write on the canvas. Keep things flexible with mobile ideas on stickys. Move things on and off the canvas. Include text and imagery on each sticky. Do not use a white board, as it will encourage writing on the canvas directly, diluting it's effectiveness. As we find insights, we will change the canvas by moving stickys off or adding new ones. One idea per sticky Don't make bullet points on stickys. Use two sticky notes to describe two different concepts. Like physical store sales and your companys web-store. It is supposed to be dynamic. This approach allows you to play with the elements of the business model to gain understanding. Use these same concepts for physical and virtual canvases Whether a paper on the wall or the business model canvas fiddle, follow the same concepts of what makes a good business model canvas. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_what_makes_a_good_bmc_card_deck_front.jpg)](/images/learning/learning_what_makes_a_good_bmc_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_what_makes_a_good_bmc_card_deck_back.jpg)](/images/learning/learning_what_makes_a_good_bmc_card_deck_back.jpg) ------------------------------------------------------------------------- ## Execution: Print out many of the business model canvases, then draw your iconagraphy and start populating based on the questions at the current level. Don't worry about perfection, but do start with a real value proposition you want to test. Do focus on meeting the standards of the tool. That is, don't dig deep into the business model canvas book or the value proposition detailed questions yet. Stay focused on just the highest level for right now, then stage 4 and 5 of the program overview will allow you to get hyper focused when you are ready. Specifically, as you develop business model canvases, don't get distracted by the detailed components of what makes a key partner for example. Just answer the top level questions: "What key partners and suppliers are neccessary to make the busines model work?" and "Who are your customers, and why would they buy?" Here is a [simple SVG business model canvas](../images/learning/business_model_canvas_template.svg) created in inkscape. It will not print correctly from inkscape, but looks close enough when printed from Firefox on linux to a HP OfficeJet PRO X576DW MFP. ------------------------------------------ Lessons learned: Meta-BMC cards took 10 minutes for straight through memorization What makes a good BMC cards to 27 minutes for straight through memorization It's so powerful. It's so encouragingly effective. Actually went through this research, incorporation stages, and I am transformed through the study and knowledge. Now for the execution part. Now to make a business model canvas according to the known effective execution materials from the Steve Blank resources: Links to the exact materials used: A large rectangle, suitable for the environment and the participants: [24" x 36" Heavyweight poster board]( http://www.officedepot.com/a/products/978039/Office-Depot-Brand-Heavyweight-Poster-Board/) [Regular size 3x3" post it notes]( http://www.officedepot.com/a/products/877664/Post-it-Pop-Up-Notes-3/) [Black only, standard sharpie]( http://www.officedepot.com/a/products/203349/Sharpie-Permanent-Fine-Point-Markers-Black/) **Example canvases** [![Example one] (/images/learning/thumbnails/Large_canvas_example_one.jpg)](/images/learning/Large_canvas_example_one.jpg) [![Example two](/images/learning/thumbnails/Large_canvas_example_two.jpg)](/images/learning/Large_canvas_example_two.jpg) **2018-03-09 16:11 Second pass.** More than 20 BMC's created on a variety of materials and formats. Lessons learned: [Fine point sharpie marker](http://a.co/9M1SSjj) is the one you want: Do not get ultra fine or wide tip. Do not get different colors. The text+imagery on each sticky should all be the same color, black. The stickys themselves can be a wide variety of colors. Small option: ------------- Use the [![8.5x11 canvas](/images/learning/thumbnails/business_model_canvas_template_no_numbers_icons.png)](/images/learning/business_model_canvas_template_no_numbers_icons.svg) 8.5x11 canvas with iconagraphy for tabletop, individual education sessions that are impromptu or otherwise restricted by context. Use a 'regular' pen or whatever fully functional tool you have on hand. Non-smearing is ideal. Use the 2"x1.5" stickies in a vertical orientation. Off-brand 2.5x1.5" stickies: [Link: http://a.co/i8XPLlI](http://a.co/i8XPLlI) Mid range option: ----------------- Use the Office Depot 20"x23" Self-stick tabletop easel pad with [2" square stickies](http://a.co/4q0Dde2). This is the default size that will function for most contexts. Draw the canvas on the top half of the paper while still mounted in the easel pad. Tear off the paper and hang on the wall, then fold up and put out of sight the easel pad. This is to discourage writing on an easel pad - it's like candy - hide it. This approach gives you a dedicated tool that is self contained. The 2"x1.5" stickies are slightly too small for sharpie work, but are fine for good for a single piece of paper because they work vertically. Large size option: ------------------ For 13+ feet viewing distance, or more than 8 participants, use the office depot 22"x28" White poster board with 'regular' stickies. [Regular size 3x3" post it notes]( http://www.officedepot.com/a/products/877664/Post-it-Pop-Up-Notes-3/) Bring a role of blue masking tape to hang up the poster board. 3M Scotch-Blue 2090 60 yds Length x 2" Width [Amazon](http://a.co/6yrsPBB) On both the mid, and large scale, use a Standard, fine-point sharpie. **2018-03-15 09:37 Third pass** The Business Model Fiddle website (with the [modifications described](http://nathanharrington.info/posts/bmfiddlecom-user-interface-modifications.html) is still truly excellent. The learning points here are that there is real value in both approaches. Experientially, the physical movement of the stickies on and off a paper canvas is far superior to the digital equivalent. There are many contexts in which the digital canvas excels: such as a presentation with live updates. (Vimimum on chrome with bmfiddle.com is very fast and straight forward). As a portable tool, the digital version is unsurpassed. For the initial capturing as well as 'snapshots' to track progress is also faster with the bmfiddle. The core concepts of what makes a good BMC can be applied across both physical and digital mediums effectively. Action items: Any business model canvas training program should have both parts. It should have a primarily physical component and a secondary digital component. A split of about 80/20 by default, but can change drastically based on the audience. Both are required, as they complement each other and enhance the immersion of the training and the overall effectiveness of the tool. <file_sep>/content/posts/learning_stage2.md Title: Stage Two: What used to be done, what we now know. Date: 2017-09-16 Category: articles Tags: business model canvas What used to be done, what we now know, and the top level of the business model canvas. **Research of known effective materials:** Udacity course: [How to Build a Startup](https://classroom.udacity.com/courses/ep245) Lesson 1: [Before you get started](https://classroom.udacity.com/courses/ep245/lessons/48743167/concepts/487500570923) Lesson 2: [What we now know]( https://classroom.udacity.com/courses/ep245/lessons/48696636/concepts/487540090923) Lesson 3: [Business Models and Customer Development](https://classroom.udacity.com/courses/ep245/lessons/48722304/concepts/487162750923) [Lean startup](http://theleanstartup.com/book) by <NAME> ----------- #### Incorporation: **Card deck one of three: What used to be done?** <pre> Why are you here? What does it take to go from an idea to a business? For the last 20 years, the answer from educators and investors used to be: go write a business plan and then you will know everything possible to start and run your business. ##### Education ##### Dutch east indies company in 1602 was the first organization that resembled what modern companies look like today. By 1850's with railroads spanning the entire country, corporations needed more sophisticated organizations. The first org chart was in 1856 just to manage organizations By early 20th century educators realized there was a need for an educated management class to administer and execute these corporations. The Harvard MBA curriculum was designed to provide managers and administrators with the tools they needed to run existing and growing companies. Accounting, leadership, organizational behavior etc. This stack of tools is incredibly important for the growth of large companies. ##### Strategy ##### Start with an operating plan and finanical model. If i thought hard enough and was smart enough, and did all the research in the library. then if i put the 5 year plan in the back all i need to do is hire the people and execute the plan. ##### Process ##### Product management + waterfall engineering Concept -> Seed funding -> Development -> Testing -> Launch All the features at one time at first customer ship. That was the canonical way to manage the process for startups for 40 years. Many processes to manage engineering risk. No processes to manage customer risk. ##### Organization ##### Functional organizations from day 1. Silos for marketing, sales and engineering because that's the way large companies were structured. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_what_used_to_be_done_card_deck_front.jpg)](/images/learning/learning_what_used_to_be_done_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_what_used_to_be_done_card_deck_back.jpg)](/images/learning/learning_what_used_to_be_done_card_deck_back.jpg) --------------------------- **Card deck two of three: What we now know** <pre> ##### Education ##### We now know something we didn't know before, the right way to build startups. Eventually if you are succesful you will need to know everything an MBA knows. But at first you need a different set of skills that never existed before. Large companies do execution, new ventures do search. Use the business model canvas to 1. Organize our thinking 2. Get out of the building, turn hypothesis into facts ##### Strategy ##### Use the business model canvas to capture the hypothesis for our model. The canvas will become a scorecard for how much we have learned. More startups fail from a lack of customers than from a failure of product development. 80-90% of software features are unwanted or unneeded by customers. Waterfall development makes sense in a large company with existing products and customers but is wrong for startups. Find the model first, then write the operating plan. Real facts before forecasts. ##### Process ##### The process that searches for the business model is: Customer development coupled with an agile engineering process. Incrementally and interatively build each portion of the product and make sure it has a home outside the building. Once you have found the model, of course you want to do product management in a formal process like agile or waterfall development, but not before you do the planning before the planning. ##### Organization ##### For new ventures, Customer development team is the right way to organize. Founder -> Get out of the building Startups are not a smaller version of a large company Startups do search, large companies focus on execution </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_what_we_now_know_card_deck_front.jpg)](/images/learning/learning_what_we_now_know_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_what_we_now_know_card_deck_back.jpg)](/images/learning/learning_what_we_now_know_card_deck_back.jpg) ------------------------------ **Card deck three of three: Top level of business model canvas** <pre> What is a business model? How a company creates value for itself while delivering products or services for customers. In the old days a company was defined by it's functional organization. You would draw an org chart. Now we draw a very different diagram. We draw a canvas that shows how to think about all the pieces of a business. 1. Value proposition: What are you building and for who? It's not about your idea or product, it's about solving a need or a problem for a customer. 2. Customer segments: Who are your customers, and why would they buy? Your customers do not exist to buy. You exist for them. Create a picture on the wall of the customer archetype. 3. Channels: How does your product or service get to your customer? Physical or web? Understand the relationship between them. 4. Customer relationships: How does a company get, keep & grow customers? 5. Revenue streams: How does the company make money from each customer segment? What value is the customer paying for? 6. Key Resources: What are the most important assets required to make the business model work? 7. Key Partners: Who are the key partners and suppliers needed to make the business model work? 8. Key Activities: What are the most important things the company must do to make the business model work? 9. Costs What are the costs to operate the business model? </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_top_level_bmc_card_deck_front.jpg)](/images/learning/learning_top_level_bmc_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_top_level_bmc_card_deck_back.jpg)](/images/learning/learning_top_level_bmc_card_deck_back.jpg) ------------------------------------------------------------------------- ## Execution: Lessons learned: Metrics on memorization: First and second half of "What used to be done" card stack took approximately 1.5 hours spread over a 7 hour interval with many interruptions. During this process, it is possible to augment the memorization by writing the cards out. By presenting the front of the cards and then typing the contents in the text file. This approach can facilitate memorization where speaking out loud is distracting to others. First half of "what we now know" card stack from education through strategy took 25 minutes for initial pass memorization. Second half in 13 minutes. Combined review: 2:45 first pass correct. 40 minutes for the 11 cards in the "what we now know" card stack. Card deck three "Top level business model canvas" took 19 minutes for full in-order memorization. Then put all three card stacks in random order for memorization. Made 4-5 passes with 1 or 2 of the same cards having a failure mode. That's about a 3% card failure rate. Performed self-talk part on a 2+ hour drive on route 64 west, starting immediately after eating first meal of the day at 10:30. The surprising thing here was the challenge of refinement of the lecture materials into a set of one-page groupings. I expected some difficulty, but the number of iterations and the time required to select and refine the core concepts was longer than anticipated. This was the goal however. It was supposed to take however long it took until you could create memorization entries as part one of incorporation section of the research, incorporation, and execution cycle. Also a surprise was the time required to physically write out the cards. In addition, it has become evident that the order of the cards provides a narrative capability that has value. Memorize them in order at first, then verify the full random order memorization. Random order memorization is essential for interrogative response. Knowing the cards backwards and forwards is essential to bridging the gap between intellectual and intuitive knowledge. However, for certain environments the full memorization of the cards in order provides a story-based approach that has unique value. Also learned was the documentation of how the one page components were split out into cards. For ease of re-creation and consistency, the cards are photographed front and back in order of memorization. If you lose a card stack or they get out of order, consult the images here for recreation of how the content of the text above is split into card stacks. <file_sep>/content/developerworks/os-mosaic.md Title: Create Mosaic images with Perl and ImageMagick Date: 2006-01-24 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-mosaic Photo mosaics with Perl and ImageMagick, use simple Perl scripts to automate the image manipulation, text creation, and compositing of arbitrary mosaic images. Learn how to use ImageMagick, GD, and The Gimp to create your own mosaic images suitable for static display and dynamic content. Explore the capabilities of ImageMagick and open source graphical editing tools. <file_sep>/content/developerworks/os-ldap2.md Title: User Perl and a regular-expression generation to search and display LDAP data (part 2) Date: 2007-03-20 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-ldap2 Use Perl and a regular-expression generator to search for and display LDAP database records (part 2), Learn how to add a scoring system to the search engine described in Part 1 of this "LDAP search engines" series. Develop your own metaphone-matching techniques for spelling corrections, query. IBM developerWorks [podcast](/files/podcasts/twodw032007.mp3) with [Scott Laningham](http://scottlaningham.com) <file_sep>/content/posts/patent_links.md Title: Patents at IBM Date: 2009-03-01 Category: articles tags: ibm ### View the full list of <a href="/category/patents.html">patents developed while at IBM</a> <file_sep>/content/posts/transformative_virtual_assistant_development.md Title: Transformative Virtual Assistant Development Date: 2017-12-13 Category: articles Tags: productivity Read this from top to bottom to find a path to success built on a pillar of failure. You are busy. You are valuable to the organization. There are things that you are uniquely good at. This process will help you focus on those things. Invest in freeing your time, and reap huge benefits as your productivity increases through the systemization of your repetitive tasks. Goal: Create a transformative experience that increases your productivity 80%. For any information related task, find a mechanism to discover information workers, assign the work, and get 80% of the quality of results in 20% of the time of doing each step manually yourself. There are many resources espousing the benefits and mechanisms for finding a virtual assistant. Some of the best: [4HWW](https://tim.blog/2010/11/02/virtual-assistants/) [Outsource Entrepreneur](https://www.entrepreneur.com/article/245561) This document is about the specific tactics used to find a virtual assistant to help with biotechnology research related tasks. The main assumption to be tested is that the search, identification and collation of data can be outsourced. The first step is to identify a goal, and then walk through each portion of the creation step manually. Then, once the variation in research paths has been reduced to a known set of states, (including an 'unknown' state), apply quantification metrics to each end state. Communicate the exact process to potential candidates, and then evaluate their performance quantitatively. Here's a quick example of what *not* to do: Go into a local life sciences research library funded by the state's biotech program. Ask for help finding market research reports on diffraction gratings. Watch as they type in 'defraction grading' into a life sciences database search tool and get zero results. This is not their fault - this is your fault. This is an under specification of search requirements, coupled with poor communication on your part. A better example is: -------------------- <pre> Search google for "diffraction grating" with quotes Click the company page Click products Find any diffraction grating none available? -> Go to next google result At least one available? Create a new google doc for that company Append every diffraction grating specification of size, lpmm, center wavelength and cost on a new row in the google spreadsheet Add the company name to the main diffraction grating research document. Add a link to the company specific google doc to the main diffraction grating research document. </pre> Understand that this level of verbosity is not demeaning. This specification of exact work products and steps to achieve them is exactly what is required for effective collaboration. They have deep, valuable skills in interpreting difficult to read web pages and understanding where to find the information you are looking for. Leverage their capabilities by first establishing a highly detailed set of rules for building a shared language of activities. The goal here is to eliminate the task as a variable. You're looking to refine your candidates by spending approximately 500$ and 80 hours collectively. What you're testing here is not your ability to write a coherent task, but rather which candidates can communicate effectively immediately. Then you take it to phase two where you interview them in person and share more of the strategic direction to see what level of insight they can provide. <pre> Day 1: Post job, invite candidates Day 2: Screen candidate responses Day 3: Screen candidate responses, evaluate estimates Day 4: Screen candidate responses, evaluate estimates Day 5: Qualify results </pre> At the end of day 5, you'll have a list of all the companies that make volume phase holographic gratings. Ideally they will have found new companies, if not you've at least had a bunch of eyes searching for the same thing. They also have a spreadsheet that lists all of the diffraction gratings from the company, along with costs and size and lpmm, etc. This is the data on which you can build your knowledge. You're strategic goals are to understand the direct competitors. What you will then be in a unique position to do is look at the competitors and see where their products compare directly in specification to ours. That's the analysis you will do. The theory here is that because I will outsource the collection, it will be faster than if I do it myself. Then instead of a countless iteration of manually checking websites to collate the data and fighting off fatigue, I'm meeting with people and utilizing my unique strengths. Details for actual posting on upwork.com Write the full job text first: <pre> Title: Find the names and product listing of transmission diffraction grating companies. Follow the steps below and stop after 3 hours and share your results. Search google for "transmission diffraction grating" without the quotes Ignore google scholar links. Ignore google image links. Ignore 'people also ask' links. The Stop List, Found List, and gratings list is available on this google doc: https://goo.gl/zhbi3v 1. Select the next link of the google results 2. Is link in 'Stop list'? Yes -> Go back to step 1. No -> go to step 3 3. Is link in the 'Found list' Yes -> Go to back to step 1 No -> Go to step 4 4. Add the link to the Found List: Open the 'Found List' tab of the google sheet. Add the company name and the url Continue to step 5 5. Find a list of transmission gratings on the links' website. For each grating found, update the "Gratings List" tab of the spreadsheet. Equivalents for lpmm column include: lines/mm, l/mm, groove density. Equivalents for diffraction efficiency column include: efficiency, absolute efficiency. If the links website is not a company (for example an education page about gratings), add to the 'Stop List' and go back to step 1. If the links website is a company, but does not have gratings for sale, add to the 'Stop List' and go back to step 1. If the links website is a company with gratings for sale but does not have one of the fields of specification, fill in the value with NA. 7. If this is link 1-39 processed, go back to step 1. Otherwise, continue to step 8. 8. If this is the 40th link processed, stop the entire process, share results. The first example of the results populated are shown in the google drive document. Edmund optics is a good example because it lists the required fields for each grating. These gratings are all transmission gratings, not reflective gratings. Only include transmission gratings in the document. Here are examples of reflective gratings, do not include these or any like them: https://www.edmundoptics.com/optics/gratings/reflective-ruled-diffraction-gratings/ https://www.newport.com/f/plane-holographic-reflection-gratings Stop after 3 hours and share your results. Thank you for your fastest reply. </pre> Posting the job --------------- <pre> Go to upwork.com Jobs -> Post a job Create a new job post More specifc -> Market Research -> Competitive market research Name job posting: Find the names and product listing of transmission diffraction grating companies. Describe work to be done: The full job post from above No Attachments On-going projects I need to hire more than one freelancer, select 5. Select start date today Pay by the hour Entry level Make sure the job is not-weekly. That is, it starts and then it ends and does not repeat on a weekly basis. Less than 1 week Less than 30 hours a week Only freelancers I have invited can view job Yes, require a cover letter Add a screening question of: Please respond with what you plan to do to get started and when you will stop and share your results. Click "Post Job" </pre> Search for candidates: ---------------------- <pre> Search for a keyword from an education field that would include the subject, for example "physics". Set the filters to the following settings: Hourly rate: $10 and below Earned amount: 1K+ Freelancer type: Independent freelancer Location: Asia Look through each candidates short biography. If they contain any of the keywords listed below, invite them to the job: Data Entry Technical report writing Academic writing information extraction attention to detail graduate of BS physics (anything indicating an actual Physics degree, has to be BS or higher) </pre> At first pass, this has produced about a 90% invite rate. Have invited 26 out of the first 30 entries. This did not produce good results. This was a failure. The best results you had was a cut and paste job from Susil 3 hours at 6$/hour that would have taken you maybe 1 hour at most. Well, maybe it wasn't a failure. It just feels like it's the wrong person. That it's not an ultra-refined process so you need to spend alot more, but you don't have a budget for alot more. Hmm.. If my time is worth 50/hour, then every hour I save at 45/hour is still coming out ahead. Failure of upwork process due to lake of refinement --------------------------------------------------- 2017-12-26 13:15 I'm not clear enough about what is plain processing according to rules, and what requires inuitive savvy that truly represents your value. Working backward - the face to face interaction with innovation professionals, spectroscopists and potential customers is the place where you can bring unique value. Everything else is a task that needs to be automated to serve this purpose. The following are the steps required to create these rules. This is inspired primarily by: [Email system that saved my life](http://hackthesystem.com/blog/the-email-management-system-that-saved-my-life/) and the [partner video](https://www.youtube.com/watch?v=4QNnxkrJGW8&feature=youtu.be) The goal here is to create a flow chart image for sharing. The time should be spent on rules, not on moving the components around or manual edge labelling. Use graphviz to create a directed graph that will catch every email. The initial strategy is to setup a framework and have the discipline to categorize all of the emails. Write down the exact decision making process for each email. This is the core skill that will take time up front, but will pay off very quickly for you, and whomever you outsource your email to. Start with this general framework. ::python /* Workflow for processing email. The goal here is a portable set of rules that anyone can be trained to follow. */ digraph { bgcolor=black; node [color=green, fontcolor=green]; edge [color=green, fontcolor=green]; 1.0 [shape=diamond; label="Inbox empty?"] 2.0 [label="Update email processed worksheet, stop"] 3.0 [label="Open oldest email in inbox"] 4.0 [label="Label as Handle this Nathan"] 99.0 [label="Archive"] rankdir=LR; rank=same {1.0, 2.0, 3.0 }; 1.0 -> 2.0 [label=yes] 1.0 -> 3.0 [label=no] // Iterate here - always go from 3.0 to a new rule, and end up at // labelling as Handle this Nathan for new rule creation 3.0 -> 4.0 // Create rule always updates this flow chart 4.0 -> 99.0 99.0 -> 1.0 [color=red] // always go back to inbox } Download the graphviz wrapper script from the [BioWize](https://biowize.wordpress.com/2011/03/11/text-wrapping-with-dot-graphviz/) blog entry: ::python #!/usr/bin/perl use strict; my $usage = "setdotlabelwidth [char-width] < [dotfile]"; my $width = shift() or die("Usage: $usage $!"); while(<STDIN>) { if(m/label="(.*?)"/) { my $labeltext = (; my @words = split(/ /, $labeltext); my @newtext = (); my $newline = ""; foreach my $word(@words) { if( length($newline) > 0 and length($newline) + length($word) > $width ) { push(@newtext, $newline); $newline = ""; } $newline .= " " if( length($newline) > 0 ); $newline .= $word; } push(@newtext, $newline) if( length($newline) > 0 ); my $newlabel = join("\\n", @newtext); s/label=".*?"/label="$newlabel"/; } print; } On linux, run this shell script at every test iteration: ::python #!/usr/bin/bash # # render_show_flowchart.sh - push the provided dot language file through # the newline label insertion tool, then render and display in eye of # gnome full screen if [[ $# -ne 2 ]] ; then echo "You must specify a dot language filename, width" exit 0 fi FILENAME=( LINEWIDTH=[ OUTFILE="${FILENAME/.gv/newlines.gv}" OUTPNG="${FILENAME/.gv/.png}" cat ${FILENAME} | perl setdotlabelwidth.pl $LINEWIDTH > ${OUTFILE} if [[ $? -ne 0 ]] ; then echo "Problem running line converter" exit 0 fi cat ${OUTFILE} | dot -Tpng -o ${OUTPNG} if [[ $? -ne 0 ]] ; then echo "Problem running png maker" exit 0 fi eog -f $OUTPNG]) In practice it looks like: <pre> (Make a change to the workflow graph) ./render_show_flowchart.sh email_workflow.gv 5 (tweak, repeat) </pre> Implementation Narrative ------------------------ You're probably thinking - that's nice, but who wants that level of process and abstraction impinging on my productivity? If you're a person like me - hugely vulnerable to visual distractions, you desparately want to live with the wrongness of the dot language edge routing. You explicitly do not want to use ASCII art by hand, LibreOffice Draw, or google sheets to position boxes. You want logical flow only in text mode so you can rapidly iterate through the real value add: The exact creation of a workflow to make email processing faster: Step 1: Follow the workflow document. Step 2: When an email arrives that does not meet any rules, iterate through the creation of a rule at this position: [![Iterate rules here](/images/thumbnails/email_workflow_startup.jpg)](/images/email_workflow_startup.jpg) Email Results ------------- This search for a virtual assistant rapidly transitioned to refining your own processes. The good news is email is now one-touch, one shot response. Everything has a rule to follow and takes much less time to process. By following the steps above, keeping that virtual assistant in mind, a ultra-refined set of rules were processed to drastically reduce email processing time. Mid-2018 search for a virtual assistant --------------------------------------- I want help setting appointments, scheduling follow ups, and doing other customer discovery related tasks. The above approach went right to a single product research tabulation task in detail. This approach is about selecting a virtual assistant first, then quantifying their results, then selecting the best option. I tried reaching out to a variety of virtual assistants on linkedin that were local to Raleigh, NC. I tried connecting with a few offshore organizations. The results were poor. Back to direct connections through upwork. This is based heavily on the strategies from [The Virtual Hub](https://www.thevirtualhub.com/blog/hiring-a-virtual-assistant/) Post the job first: Job Title: Virtual assistant with LinkedIn experience Cordince LLC is looking for a virtual assistant with linkedin experience to complete clerical projects that are anticipated to require around 10-15 hours per week for 3 weeks. The work will include the following tasks: Linkedin research Coordinating and setting appointments Product research Calling potential customers to verify contact information The following skills are a must: Great communication skills via phone, email and chat Expertise in linkedin Strong knowledge of google docs and google calendar Some knowledge of tele-sales (phone and email) Experience with customer discovery a big plus We're looking for a great communicator who can help us be more effective. We know you have great ideas about how to be more effective, and we want to work together to achieve them. If you're interested, please send some examples of your work as a virtual assistant. Thanks for your time! Invite freelancers: ------------------- Search for "virtual assistant" Ensure U.S. Only is checked Earned amount 10k+ Hourly rate 10 and below Any job success Or, just go to this [upwork summary page]( https://www.upwork.com/hire/virtual-assistants/) and then sort by 10$ and under. This helped a lot too: https://medium.com/@neocody/outsourcing-101-hiring-your-first-virtual-assistant-b81b97702665 Upwork notes ------------ I wanted to continue this process with upwork.com. I tried signing up through Cordince, LLC with <EMAIL> It said cordince.com was not a valid email. I communicated through cordince.com with their tech support to resolve this. They disappeared. On to other providers. Hubstaff specific notes --------------------- Rejection criteria: Target 4$ an hour or less offshore 10$ or less on shore, with native english and perfect writing Offshore: 2 punctuation or grammatical errors in first response Pay rate 2x the target or more What is the cut off you need? For 8320 per year, you can have a full time 4$ an hour phillipine assistant. Or at 8$ an hour for 20 hours a week, 4 hours per weekday, which should be plenty. Are you going cheap or not? Phillipines definetly. Hubstaff talent definetly. Do two experiments, one 4$ an hour one 8$ an hour 2018-07-11 19:36 Set up 4 calls with Phillipines contractors only. People who responded to the job posting and included examples of their work or email contact directly. All of these are probably just cut and pasters. Sent email requests for a phone conversation. First one was for Maributh at 19:30 - which she made it sound like she was going to call me on phone number at 19:30 eastern on July 11th. Double checked and it was clear. This is a good test - if they can't figure that out then it's probably not worth pursuing. My guess is she's still asleep because she sent the initial response at 9:00 am her time. I triple checked, and it's easy to find out what time it is here. So that first entry is a bust. No follow up emails from her, no contact after she accepted the phone call request. Also contacted three local, college educated US citizen virtual assistants. All of whom have not responded days later. Made another pass through the hubstaff interface and directly invited others to the job. It's saturday in the philippines, waiting to hear back on monday. Well finally, got somebody on the phone. He wants western union. He wants to send me a list of managers. That seems so shady. Like he's got a list and wants to send it - 4$ an hour sounded great to him. You said you would look into western union and send him some draft proposals. If he will actually do the work then fine, otherwise this is a giant frustration. In humility, you may not be understanding him correctly. You are new to this and you may be just simply not communicating effectively or mis-applying your cultural norms. The plan is to let that relationship sit and see what others say below: 2018-07-17 13:58 Well the lack of communiation has been seriously frustrating. This page says that is to be expected: [staff.com VA](https://blog.staff.com/how-to-hire-a-virtual-assistant-from-the-philippines-for-2-50-to-5-50-per-hour/) Now go through all the hubstaff entries of people who have applied and people who you invited. Look for: <pre> The next step is to filter out the qualified applicants from those that are unqualified.. In most cases, Rawson says, you can easily eliminate about 70% of the applicants based on poor quality English, a weak resume, or entry level experience. Once you have determined the most qualified applicants, you provide each one with a test; each examination depends on the tasks of the job. The test can range between 15 minutes (unpaid) to as much as three hours (paid). At the end, you peruse the test, evaluate them and you are left with just a few prospects. </pre> So go through each entry and read their response: Do not filter out based on cost, only based on poor quality english (more than 2 grammatical or punctuation errors) a weak resume no resume posted (no high school, no exact experience with technology mentioned) or entry level experience. (not enough of the target experience) That means connect with all the on-shore entries, all the offshore entries that meet the criteria. This is worth it - if you can find a VA even at 1/3 the cost if it's truly transformative then it's will pay for itself quickly. Specifically, click the first application. If they fail the criteria above, click the 'thumbs down' button. If they pass the criteria above, click the 'thumbs up' button, then click contact and send: Hi (Their name) - Thanks for your willingness to help! Our hiring process goes through the following stages: 1. Skills test (approximately 15 minutes) 2. Functional test (approximately 2 hours, paid) 3. Phone interview (approximately 20 mintues) Our skills test starts simple, can you please read the document linked to below, and send your response to <EMAIL>? Skills Test instructions: https://tinyurl.com/yabu3llj Thanks for your work on this! Then click the arrow to the next candidate. ## Contents of the skills test document: <pre> Skills test (should take about 15 minutes): 1. Create a google sheets document 2. Put the time you started this process in the first row 3. Google search for: "medical device company" near Raleigh, NC -jobs 4. For each link in the first page of results, put the company website in the first column, then the name of the CEO in the second column. 5. Put the CEO's linkedin profile page link in the fourth column Please stop after 15 minutes, or after the first page of results has been processed. Put the time you stopped in the last row Send the google sheets link in an email: To: <EMAIL> Subject: Skills test complete (your name) Body: Google sheets link: (link to your google sheet) Thanks for taking the skills test! </pre> This test is designed to be variable and specific. Make sure: They email you a link in an email. They put the linkedin profile of the ceo in the fourth column They list start and end times. If any of those are not met, add to stop list, with brief reason for failure. Respond to their email: Thanks <person name>, we will let you know when we are ready to work together further. Otherwise send the initial task by replying to their response email with: <pre> Thanks for your work on this! The next stage of our interview process is the paid functional test. Our current preferred payment method is Ria Money transfer. The hourly rate for this job is: USD If Ria Money transfer is not OK, please respond with your preferred payment mechanism. If Ria money transfer is acceptable, please follow the instructions here: https://docs.google.com/document/d/1pqgxE_Kp-zO4Nx8cRjki32pSWAJzENQpi2AH-ZFlRqY/edit?usp=sharing Upon completion of the task, payment will be sent via Ria Money Transfer. Thank you for your help, and we look forward to being more successful together! Payment sent email: ################## Thanks for your help with this! Payment has been sent. I will review the results and get back to you on the next steps. Thanks again! </pre> On hubstaff talent: 343 Views of job post 41 applicants (does that include people you invited?) 18 of those are cut and paste rejects 23 of those I sent follow ups to 4 passed the skills test 3 failed the skills test (including the M.S. who works for oracle) Not really enough data, but replicatable. The rates are between 4 and 25 dollars US. In the phillipines, india and los angeles. 2018-07-21 12:30 Sent 4 Functional tests Results: Nobody uses RIA - everybody wanted paypal Applicants PP - did not respond immediately saying what he would do. Stopped at 2.5 hours according to his documentation Actual document produced has 8 companies 29 people, some of which are good, some have 'regional sales manager' and 'regional sales specialist' That was 8$ USD per hour. Sent 16 dollars through paypal The general feel from this doc is that formatting and making it look pretty makes it easier to read and leaves a good impression. TR - did not respond immediately saying what would be done. No indicators of how much time was spent (but didn't ask for any) Actual document produced has 19 companies, 41 people. Some of the companies are resellers of xrays, some are not medical device companies at all. To be fair that may be a specialized piece of knowledge to differentiate between a company like orthotools which distributes hundreds of medtech devices and looks like a medtech device company. Sent an email in between to follow up about paypal that was not seen. That was 25$ USD per hour for on shore. The general feel from this doc was it was the bare minimum done in anger. KB - did respond immediately, kind of. Actual document produced has about 50 companies, the first and last are not even in the state, nor do they have a location in the state. Nor are they even medical device companies. Not even close. Law firms in there too. Shockingly bad results. That was for 8$ USD per hour india. Well that sucks. 3 total responses. Minimum cost is 8$ an hour, and is of the quality I was expecting at 4$ an hour or less. If you remove the paypal exercise in frustration it wasn't that bad. 2018-07-23 12:39 8/hr just feels too expensive. It's too much. That's 16k per year. 4$ hour seems more reasonable at 8k per year. So the plan is to talk with PP just to finish the procedure. Ask him these questions in the interview: Then decide if you want to move forward with a few-week contract of a group of tasks that you want to see done. Now is not a good time for you actually because you're feeling lazy. Because you're ready to just pack it in and check out. Just like they will feel sometimes. Lead yourself. 2018-07-23 12:48 A friend posted on "Women of Hope Community Church" facebook page a request for virtual assistant help. Within a few days 4 contacts of varying backgrounds. <pre> Hi (Their name) - Thanks for your willingness to help! Cordince LLC is looking for a virtual assistant with linkedin experience to complete clerical projects that are anticipated to require around 10-15 hours per week for 3 weeks. The work will include the following tasks: Linkedin research Coordinating and setting appointments Product research Calling potential customers to verify contact information The following skills are a must: Great communication skills via phone, email and chat Expertise in linkedin Strong knowledge of google docs and google calendar Some knowledge of tele-sales (phone and email) Experience with customer discovery a big plus Does that sound like something you would be interested in? If so, please let me know how much time you may have to work on projects like this for the next 3-4 weeks. If you're not interested, or you don't think you'll have enough time, can you please forward this note to someone you trust? Thanks for any help! - Nathan </pre> 2018-08-03 15:51 None of those women of help references were successful either. Did get a very long delayed response by following the referall chain from virtual assistants, ultimately went with that on-shore approach. <file_sep>/pages/wasatch_work_log_timeline.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>Wasatch Work Log Timeline - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="/pages/wasatch-work-log-timeline.html"> <meta name="author" content="<NAME>" /> <meta name="description" content="2016-12-14 Start of new work log schedule. Now about demonstrating results instead of documenting efforts. 2016-12-13 holiday party + rest of day. Basic simulation with integration time and laser control linkage in mains. Reset of virtualization setups to have base system with full hd, non-dns resolved network connections for windows update …" /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="article"/> <meta property="og:title" content="Wasatch Work Log Timeline"/> <meta property="og:url" content="/pages/wasatch-work-log-timeline.html"/> <meta property="og:description" content="2016-12-14 Start of new work log schedule. Now about demonstrating results instead of documenting efforts. 2016-12-13 holiday party + rest of day. Basic simulation with integration time and laser control linkage in mains. Reset of virtualization setups to have base system with full hd, non-dns resolved network connections for windows update …" /> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li > <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content" class="body"> <h1 class="entry-title">Wasatch Work Log Timeline</h1> <div class="entry-content"> <p>2016-12-14 Start of new work log schedule. Now about demonstrating results instead of documenting efforts.</p> <p>2016-12-13 holiday party + rest of day. Basic simulation with integration time and laser control linkage in mains. Reset of virtualization setups to have base system with full hd, non-dns resolved network connections for windows update inhibit. Simulated temperatures and noise margins representative of integration time changes.</p> <div class="highlight"><pre><span></span><code><span class="mf">3</span><span class="n">fd3562</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">updates</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">live</span><span class="w"> </span><span class="n">simulation</span><span class="w"> </span><span class="kd">data</span> <span class="mf">...</span> <span class="mf">77</span><span class="n">c4e5f</span><span class="w"> </span><span class="n">tests</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="mf">1</span><span class="o">-</span><span class="mf">10</span><span class="n">k</span><span class="w"> </span><span class="nb">int</span><span class="n">egration</span><span class="w"> </span><span class="n">change</span> </code></pre></div> <p>2016-12-13 16:30</p> <p>2016-12-12 07:00 receive and process shipments for loading dock, front area. Update documentation for more efficient processing. website maintenance rule clarification. Setup of dual monitor configuration for 6 visualizations on new primary virtualization machine. VM configuration and appveyor build testing. Laser button stylesheet change. Material simulation with high fidelity noise indicators.</p> <div class="highlight"><pre><span></span><code><span class="mf">1</span><span class="n">c745b9</span><span class="w"> </span><span class="kr">to</span><span class="n">ggle</span><span class="w"> </span><span class="n">laser</span><span class="w"> </span><span class="n">button</span><span class="w"> </span><span class="n">stylesheet</span><span class="w"> </span><span class="n">change</span> </code></pre></div> <p>2016-12-12 16:33</p> <p>2016-12-09 07:07 performance review, scheduling updates, detailed processing and review of algorithm removal from it systems. Investigation into cigna healthcare changes. Website down detection. Startup page setting on command line. Start with laser communication and command and control queues in multiprocessing simulator. Correction of delay and non-exit with terminate and join in sub processes.</p> <div class="highlight"><pre><span></span><code>afa808c shallow copy 890f1d9 non increasing copy of data d99ce88 startup setting command line ac7779e laser with record setting reading and writing fedaefc strip down of older simulatespectra test cases </code></pre></div> <p>2016-12-08 06:24 vtt 1000 manual discovery, it support, processing shipments. Mid-milestone demo of simulatd plug, unplug of device in dash. Determination of valid and invalid firmware configurations on test hardware. Recovery and documentation of Dash.py vs. Dash with no suffix build issue on appveyor machine. Log level case management on command line</p> <div class="highlight"><pre><span></span><code><span class="nv">c2f61a1</span><span class="w"> </span><span class="nv">recovery</span><span class="w"> </span><span class="nv">of</span><span class="w"> </span><span class="nv">dash</span>.<span class="nv">py</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="nv">pyinstaller</span> <span class="nv">aea97ec</span><span class="w"> </span><span class="nv">tests</span><span class="w"> </span><span class="nv">recovered</span><span class="w"> </span><span class="nv">in</span><span class="w"> </span><span class="nv">appveyor</span> <span class="nv">bc936d9</span><span class="w"> </span><span class="nv">case</span><span class="w"> </span><span class="nv">management</span><span class="w"> </span><span class="nv">of</span><span class="w"> </span><span class="nv">log</span><span class="w"> </span><span class="nv">level</span><span class="w"> </span><span class="nv">on</span><span class="w"> </span><span class="nv">command</span><span class="w"> </span><span class="nv">line</span> <span class="mi">858</span><span class="nv">c389</span><span class="w"> </span><span class="nv">log</span><span class="w"> </span><span class="nv">level</span><span class="w"> </span><span class="nv">in</span><span class="w"> </span><span class="nv">controller</span> </code></pre></div> <p>2016-12-08 16:31</p> <p>2016-12-07 07:12 pw booth review, setup of testing systems for dark current rma validation. Dash runtime error after 2 days investigation on windows 10 and windows 7. Rebuild of appveyor configuration to isolate build flaw and executable non-inclusion. Setup of secondary virtualization system . Validation of appveyor vs. local system build differences. Log-level default to INFO, setup on executable for linux and windows.</p> <div class="highlight"><pre><span></span><code><span class="n">f701cc6</span><span class="w"> </span><span class="n">no</span><span class="w"> </span><span class="n">tests</span><span class="p">,</span><span class="w"> </span><span class="n">just</span><span class="w"> </span><span class="n">build</span> <span class="mh">24</span><span class="n">dcd37</span><span class="w"> </span><span class="n">dash</span><span class="p">.</span><span class="n">py</span><span class="w"> </span><span class="n">renamed</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="n">appveyor</span><span class="w"> </span><span class="n">builds</span> <span class="mh">664</span><span class="n">aaf6</span><span class="w"> </span><span class="n">corrected</span><span class="w"> </span><span class="n">log</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="n">required</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">windows</span><span class="w"> </span><span class="n">tests</span> <span class="mh">398</span><span class="n">dbbe</span><span class="w"> </span><span class="k">default</span><span class="w"> </span><span class="n">log</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="n">INFO</span><span class="p">,</span><span class="w"> </span><span class="n">runtime</span><span class="w"> </span><span class="n">assignment</span> </code></pre></div> <p>2016-12-07 16:34</p> <p>2016-12-06 06:42 identification and removal of algorithm storage. Year review plan, plumbing issue recovery. Search for comptabile fonts for the multiprocessing demonstration tests. Specification of data structures and api's for controlling multiple devices with multiprocessing and wasatchusb with libusb drivers, finish power control with web power switch.</p> <div class="highlight"><pre><span></span><code><span class="mf">195</span><span class="n">a60f</span><span class="w"> </span><span class="n">style</span><span class="w"> </span><span class="n">recovery</span> </code></pre></div> <p>2016-12-06 16:15</p> <p>2016-12-05 06:38 production meeting. adding of send routing rules inhibit to prevent name conflicts. Dash runtime error on windows 7 investigation. Configuration parser, ini file of Dash simulated device control. Testing of simulation script and demo, project planning.</p> <div class="highlight"><pre><span></span><code>a2973d4 restoration of default startup 50ba7a9 name cleanup </code></pre></div> <p>2016-12-06 16:30</p> <p>2016-12-02 06:31 attempting to decipher 401k puzzle, update historical software to support new serial numbers. Setup of new Dash long term executable checks, validation of virtualization setup. Desk reconfigure for simultaneous tests and support</p> <p>e7f14e9 exception handling in css styler 2a32bb3 faded gray on disconnect 0cb345f grayed graphs, stopping 68e61d4 bare bones init file read simulator for connections tatus 75dd852 lower requirements for system simulation speeds</p> <p>2016-12-02 16:30</p> <p>2016-12-01 06:34 addition of logging tab. removal of tabwidget which has unsupported hide tab functionality in pyside. Tests to uncover various issues with adding a handler to signal the qt interface for new log entries. Settled on a pygtail implementation with custom stackedwidget control with tab widget sytled buttons. This gets around the repaint events of signals triggered from a handler added to a logging module that has other subprocess handlers. Continued refinment of long term power cycling tests and hardware setups.</p> <div class="highlight"><pre><span></span><code><span class="n">e371efc</span><span class="w"> </span><span class="n">test</span><span class="w"> </span><span class="n">correction</span> <span class="mi">8</span><span class="n">b9bc0e</span><span class="w"> </span><span class="n">recover</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="nb">log</span><span class="w"> </span><span class="n">queue</span><span class="w"> </span><span class="n">variable</span> <span class="mi">0</span><span class="n">b5c9d7</span><span class="w"> </span><span class="n">bare</span><span class="w"> </span><span class="n">switch</span><span class="w"> </span><span class="n">between</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">logging</span><span class="w"> </span><span class="n">simulated</span><span class="w"> </span><span class="n">tabs</span> <span class="mi">156</span><span class="n">f848</span><span class="w"> </span><span class="n">pygtail</span><span class="w"> </span><span class="n">integration</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">appveyor</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">travis</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">b950da7</span><span class="w"> </span><span class="n">pygtail</span><span class="w"> </span><span class="n">integration</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">text</span><span class="w"> </span><span class="n">edit</span><span class="w"> </span><span class="n">control</span> <span class="mi">1</span><span class="n">bd65b1</span><span class="w"> </span><span class="n">pygtail</span> <span class="mf">1e9</span><span class="n">d346</span><span class="w"> </span><span class="n">showing</span><span class="w"> </span><span class="n">inhibit</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">qt</span><span class="w"> </span><span class="n">interface</span><span class="w"> </span><span class="n">when</span><span class="w"> </span><span class="n">logging</span><span class="w"> </span><span class="n">post</span><span class="w"> </span><span class="n">subprocess</span> <span class="n">setup</span> <span class="mi">0</span><span class="n">ad10f8</span><span class="w"> </span><span class="n">display</span><span class="w"> </span><span class="nb">log</span><span class="w"> </span><span class="n">text</span><span class="w"> </span><span class="n">crash</span> <span class="mi">2</span><span class="n">fffb02</span><span class="w"> </span><span class="n">various</span><span class="w"> </span><span class="n">attempts</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="k">signal</span><span class="w"> </span><span class="n">logging</span> <span class="mi">8</span><span class="n">a3777e</span><span class="w"> </span><span class="n">removal</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">pyside</span><span class="o">-</span><span class="n">unsupported</span><span class="w"> </span><span class="n">qtabwidget</span><span class="p">,</span><span class="w"> </span><span class="n">addition</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">custom</span> <span class="n">button</span><span class="w"> </span><span class="n">solution</span><span class="w"> </span><span class="n">layout</span> </code></pre></div> <p>2016-12-01 16:30</p> <p>2016-11-30 06:58 review demo requirements for photonics west, Detailed demo meeting with screenshots. transformation of raman testing platform. Investigation of web power switch reset mechanisms. Milestone updates for next dash demo. Selection and ordering of new testing computer components. Initiation of new test schedule to meet PW requirements.</p> <div class="highlight"><pre><span></span><code>acceef5 slight interface mods 40fa949 new hardware capture layout 2c93fe7 raman capture by default </code></pre></div> <p>2016-11-30 17:00</p> <p>2016-11-29 06:50 it asset system review and investigation. Setup of meeting and communications with customer visit. Debug and testing of csv dictreader failure in sub-process on windows. Switch to raw csv processing with context for simulated raman data. Layout of raman controls and line plots for raman setup screen.</p> <div class="highlight"><pre><span></span><code><span class="mi">47</span><span class="n">f690a</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">raw</span><span class="w"> </span><span class="n">file</span><span class="w"> </span><span class="nb">load</span><span class="w"> </span><span class="n">instead</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">dictreader</span><span class="w"> </span><span class="n">which</span><span class="w"> </span><span class="n">was</span><span class="w"> </span><span class="n">causing</span><span class="w"> </span><span class="n">a</span> <span class="w"> </span><span class="n">multiprocess</span><span class="w"> </span><span class="n">exit</span><span class="w"> </span><span class="n">inhibit</span> <span class="mi">56392</span><span class="n">be</span><span class="w"> </span><span class="n">simulated</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">data</span> <span class="mi">0</span><span class="n">c36f41</span><span class="w"> </span><span class="n">simulated</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">data</span> <span class="mi">0</span><span class="n">cb1dd6</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">controls</span> <span class="mi">8</span><span class="n">cfaf6f</span><span class="w"> </span><span class="n">control</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">defaults</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">test</span><span class="w"> </span><span class="n">passing</span> </code></pre></div> <p>2016-11-29 18:13</p> <p>2016-11-28 06:32 manufacturing meeting notes, setup of OCT sample storage area, review of power management options for failed UPS. Find headshots and email. Raman graph layout and placeholders. Addition of setup and capture navigational signals. Default geometry changes, expansion of css loading of runtime components. Multi-os verificationa nd spacing consistencies.</p> <div class="highlight"><pre><span></span><code><span class="mf">434</span><span class="n">b24f</span><span class="w"> </span><span class="n">base</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="n">graph</span><span class="w"> </span><span class="n">placeholders</span> <span class="n">c7e29f7</span><span class="w"> </span><span class="n">baseline</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">placeholder</span><span class="w"> </span><span class="n">graphs</span> <span class="mf">7</span><span class="n">b313be</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">layout</span> <span class="mf">096</span><span class="n">e031</span><span class="w"> </span><span class="n">techniques</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="n">utils</span> <span class="mf">...</span> <span class="n">d13afbe</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="n">tests</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="kr">save</span><span class="n">d</span><span class="w"> </span><span class="n">area</span><span class="w"> </span><span class="n">iconagraphy</span> <span class="n">dc8d6df</span><span class="w"> </span><span class="n">adding</span><span class="w"> </span><span class="kr">cont</span><span class="n">rols</span><span class="w"> </span><span class="kr">to</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">catpure</span> <span class="mf">657486</span><span class="n">d</span><span class="w"> </span><span class="n">partial</span><span class="w"> </span><span class="n">raman</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">capture</span> </code></pre></div> <p>2016-11-28 16:33</p> <p>2016-11-20 06:42 remote software diagnosis and support for Layne Bradley at UGA - addressed with driver signature enforcement disabling. Project planning for Dash releases to coincide with hard dates. Detailed setup and long term testing of newest build deploy level for inter-vacation testing</p> <div class="highlight"><pre><span></span><code><span class="mf">6700</span><span class="n">dd0</span><span class="w"> </span><span class="n">change</span><span class="w"> </span><span class="n">right</span><span class="w"> </span><span class="n">side</span><span class="w"> </span><span class="kr">cont</span><span class="n">rol</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="kr">to</span><span class="w"> </span><span class="n">have</span><span class="w"> </span><span class="n">consistent</span><span class="w"> </span><span class="n">width</span> <span class="n">with</span><span class="w"> </span><span class="n">left</span><span class="w"> </span><span class="n">side</span><span class="w"> </span><span class="kr">save</span><span class="n">d</span><span class="w"> </span><span class="kd">data</span><span class="w"> </span><span class="n">area</span> <span class="n">da4dd83</span><span class="w"> </span><span class="n">upand</span><span class="w"> </span><span class="n">down</span><span class="w"> </span><span class="n">icons</span> <span class="n">c7dd0bd</span><span class="w"> </span><span class="n">upand</span><span class="w"> </span><span class="n">down</span><span class="w"> </span><span class="n">icons</span> <span class="mf">6</span><span class="n">c90b6c</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">by</span><span class="w"> </span><span class="kd">def</span><span class="n">aul</span> <span class="n">d5b7be6</span><span class="w"> </span><span class="n">simulated</span><span class="w"> </span><span class="n">temperatures</span> <span class="mf">249</span><span class="n">ee6e</span><span class="w"> </span><span class="n">simulated</span><span class="w"> </span><span class="n">temperatures</span> <span class="mf">236793</span><span class="n">c</span><span class="w"> </span><span class="n">Merge</span><span class="w"> </span><span class="n">branch</span><span class="w"> </span><span class="err">&#39;</span><span class="n">winmaster</span><span class="err">&#39;</span> <span class="mf">2</span><span class="n">da0999</span><span class="w"> </span><span class="n">corrected</span><span class="w"> </span><span class="n">build</span><span class="w"> </span><span class="ow">or</span><span class="n">dering</span> </code></pre></div> <p>2016-11-21 16:30</p> <p>2016-11-18 06:13 research and location of chevelle product documentation and actual specifications and availablility. reconfiguration of remotetest system to support remote system access and portability. Isolation and correction of build compatability issues 32bit python vs. 64bit python. Put mechanisms in place to force 32bit python in documentation and build environments. Updated iconagraphy names, setup for second long term iteration pass on virtualization tester.</p> <div class="highlight"><pre><span></span><code><span class="mf">133</span><span class="n">deab</span><span class="w"> </span><span class="n">Merge</span><span class="w"> </span><span class="n">branch</span><span class="w"> </span><span class="err">&#39;</span><span class="n">winmaster</span><span class="err">&#39;</span> <span class="n">d1578fe</span><span class="w"> </span><span class="n">designer</span><span class="w"> </span><span class="n">updates</span><span class="p">,</span><span class="w"> </span><span class="n">uic</span><span class="w"> </span><span class="n">imagery</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="n">correction</span> <span class="mf">0186885</span><span class="w"> </span><span class="n">uic</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">designer</span><span class="w"> </span><span class="n">imagery</span><span class="w"> </span><span class="n">updates</span> <span class="n">a1dd7cb</span><span class="w"> </span><span class="n">matching</span><span class="w"> </span><span class="mf">32</span><span class="n">bit</span><span class="w"> </span><span class="n">build</span><span class="w"> </span><span class="n">instructions</span> <span class="n">ae9014c</span><span class="w"> </span><span class="n">files</span><span class="w"> </span><span class="n">renamed</span> <span class="mf">1</span><span class="n">daf2a7</span><span class="w"> </span><span class="n">restoration</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="nb">exp</span><span class="n">ected</span><span class="w"> </span><span class="n">startup</span><span class="w"> </span><span class="n">states</span> <span class="mf">4</span><span class="n">f28096</span><span class="w"> </span><span class="n">building</span><span class="w"> </span><span class="n">updates</span> <span class="n">a22f238</span><span class="w"> </span><span class="n">documentation</span><span class="w"> </span><span class="ow">not</span><span class="n">es</span><span class="p">,</span><span class="w"> </span><span class="n">example</span><span class="w"> </span><span class="kd">data</span> </code></pre></div> <p>2016-11-18 16:30</p> <p>2016-11-17 06:48 Interview of ME candidate. Summary of notes and review meeting with team. Sprint demo debug issues with a pure windows installation on actual hardware compared to virutal machine. Traced down to mkl_avx2 and other appveyor custom-build files. Setup virtual machine to verify installation build differentiations. Continued full development through hardware capture and setup.</p> <div class="highlight"><pre><span></span><code><span class="mf">0</span><span class="n">ff19b1</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">minimum</span><span class="w"> </span><span class="n">height</span> <span class="n">b34ac5d</span><span class="w"> </span><span class="n">updated</span><span class="w"> </span><span class="n">instructions</span> <span class="mf">81</span><span class="n">f2efb</span><span class="w"> </span><span class="n">pre</span><span class="o">-</span><span class="n">local</span><span class="w"> </span><span class="n">merge</span> <span class="mf">38</span><span class="n">c1ac2</span><span class="w"> </span><span class="n">rebuilt</span><span class="w"> </span><span class="kr">to</span><span class="w"> </span><span class="n">merge</span> <span class="n">e5d7ac6</span><span class="w"> </span><span class="n">mkl_p4m3</span><span class="mf">.</span><span class="n">dll</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">mkl_p4</span><span class="mf">.</span><span class="n">dll</span> <span class="mf">7</span><span class="n">c8ac08</span><span class="w"> </span><span class="n">mkl_avx2</span><span class="mf">.</span><span class="n">dll</span><span class="w"> </span><span class="kr">on</span><span class="w"> </span><span class="n">appveyor</span> <span class="n">aa18d55</span><span class="w"> </span><span class="n">appveyor</span><span class="w"> </span><span class="n">non</span><span class="w"> </span><span class="n">windowed</span> <span class="n">cc3e7cb</span><span class="w"> </span><span class="n">temporary</span><span class="w"> </span><span class="c1">removal of windowed parameter for debug</span> <span class="mf">0</span><span class="n">d16cec</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">basic</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">setup</span><span class="p">,</span><span class="w"> </span><span class="n">updating</span><span class="w"> </span><span class="n">iconagraphy</span><span class="w"> </span><span class="kr">for</span><span class="w"> </span><span class="n">buttons</span> <span class="ow">and</span><span class="w"> </span><span class="n">resources</span> <span class="mf">55</span><span class="n">a6f74</span><span class="w"> </span><span class="n">placehodler</span><span class="w"> </span><span class="n">iamgery</span> <span class="mf">9662</span><span class="n">f45</span><span class="w"> </span><span class="n">hide</span><span class="w"> </span><span class="nb">int</span><span class="n">erface</span><span class="w"> </span><span class="n">from</span><span class="w"> </span><span class="n">design</span><span class="w"> </span><span class="n">time</span> </code></pre></div> <p>2016-11-17 17:15</p> <p>2016-11-16 06:38 bi-weekly engineering update meeting. postfix system management emails for root and non-root accounts. self assesments, mustard tree inventory search. User account management, suspension of report indicated users. Full linkage checks and border layout experiements for hardware capture portion of interface. Simulated and multi-component data.</p> <div class="highlight"><pre><span></span><code><span class="mf">0</span><span class="n">a0ea84</span><span class="w"> </span><span class="n">second</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="n">border</span><span class="w"> </span><span class="c1">removed on hardware capture details</span> <span class="mf">62</span><span class="n">bb9db</span><span class="w"> </span><span class="n">geometry</span><span class="w"> </span><span class="kr">on</span><span class="w"> </span><span class="n">command</span><span class="w"> </span><span class="n">line</span> <span class="mf">24</span><span class="n">ba70f</span><span class="w"> </span><span class="n">deep</span><span class="w"> </span><span class="n">naming</span><span class="p">,</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">details</span><span class="w"> </span><span class="n">layout</span> <span class="mf">55027</span><span class="n">bc</span><span class="w"> </span><span class="n">image</span><span class="w"> </span><span class="n">view</span><span class="w"> </span><span class="n">included</span> <span class="mf">5405</span><span class="n">d1d</span><span class="w"> </span><span class="n">hard</span><span class="w"> </span><span class="n">border</span><span class="w"> </span><span class="n">investigation</span> <span class="n">d3d88af</span><span class="w"> </span><span class="n">hard</span><span class="w"> </span><span class="n">border</span><span class="w"> </span><span class="n">investigation</span> <span class="mf">3</span><span class="n">bd7bfb</span><span class="w"> </span><span class="n">partial</span><span class="w"> </span><span class="n">way</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">details</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="n">conversion</span> <span class="mf">55</span><span class="n">ba8fe</span><span class="w"> </span><span class="kd">def</span><span class="n">ined</span><span class="w"> </span><span class="n">devices</span><span class="mf">.</span><span class="n">qrc</span><span class="w"> </span><span class="n">location</span><span class="p">,</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">layouts</span> </code></pre></div> <p>2016-11-16 16:44</p> <p>2016-11-15 06:33 creation of uptime monitor trackers on cookbook replication system at linode. full reload of database and environment setup. change of firewall rules and prerequisites updates for cookbook instructions. will come back in two weeks to validate. Removal of lambda calls to address segfaults on application exits. Re-insertion of test driven concepts for interface components.</p> <div class="highlight"><pre><span></span><code><span class="mi">123</span><span class="n">c529</span><span class="w"> </span><span class="n">include</span><span class="w"> </span><span class="n">stylesheets</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="n">runtime</span> <span class="n">ead80ea</span><span class="w"> </span><span class="n">updated</span><span class="w"> </span><span class="n">initial</span><span class="w"> </span><span class="n">state</span><span class="p">,</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">capture</span><span class="w"> </span><span class="n">realtime</span><span class="w"> </span><span class="n">graphs</span> <span class="mi">968</span><span class="n">ad6e</span><span class="w"> </span><span class="n">control</span><span class="w"> </span><span class="n">correct</span><span class="w"> </span><span class="n">close</span> <span class="mi">643231</span><span class="n">c</span><span class="w"> </span><span class="n">lambda</span><span class="w"> </span><span class="n">removed</span><span class="p">,</span><span class="w"> </span><span class="n">no</span><span class="w"> </span><span class="n">more</span><span class="w"> </span><span class="n">segfaults</span><span class="p">,</span><span class="w"> </span><span class="n">now</span><span class="w"> </span><span class="n">trying</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">get</span><span class="w"> </span><span class="n">test</span> <span class="n">control</span><span class="w"> </span><span class="n">windows</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">exit</span><span class="w"> </span><span class="n">after</span><span class="w"> </span><span class="n">single</span><span class="w"> </span><span class="n">tests</span> <span class="n">b97f7b5</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">lambda</span><span class="w"> </span><span class="n">enabled</span> <span class="mi">9</span><span class="n">d91a7c</span><span class="w"> </span><span class="n">back</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">seg</span><span class="w"> </span><span class="n">fault</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">core</span><span class="w"> </span><span class="n">dump</span> <span class="mi">6940773</span><span class="w"> </span><span class="n">restore</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">debug</span><span class="w"> </span><span class="nb">log</span><span class="w"> </span><span class="nb">print</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">devices</span> <span class="mi">799</span><span class="n">f24d</span><span class="w"> </span><span class="n">files</span><span class="w"> </span><span class="n">are</span><span class="w"> </span><span class="n">important</span> <span class="mi">399</span><span class="n">bc06</span><span class="w"> </span><span class="n">toggle</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">buttons</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">operations</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">style</span><span class="w"> </span><span class="n">sheets</span><span class="w"> </span><span class="n">changing</span> <span class="n">f8bc117</span><span class="w"> </span><span class="n">through</span><span class="w"> </span><span class="n">basic</span><span class="w"> </span><span class="nb">load</span><span class="w"> </span><span class="n">css</span><span class="w"> </span><span class="n">testing</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">styles</span> <span class="mf">65077e5</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">styles</span><span class="w"> </span><span class="n">testing</span><span class="w"> </span><span class="n">group</span> <span class="n">aca863b</span><span class="w"> </span><span class="n">populate</span><span class="w"> </span><span class="n">stylesheets</span><span class="o">-</span><span class="w"> </span><span class="n">segfault</span><span class="w"> </span><span class="n">was</span><span class="w"> </span><span class="ow">in</span><span class="w"> </span><span class="n">empty</span><span class="w"> </span><span class="n">function</span><span class="w"> </span><span class="k">return</span> </code></pre></div> <p>2016-11-15 16:30</p> <p>2016-11-14 06:38 Manufacturing meeting and notes. Segfault on environment reconfiguration onto zenbook with hiDpi display. Various debugging tests with strace and valgrind for isolation. Start of sytlesheet integration and read from file.</p> <p>2016-11-14 17:00</p> <p>2016-11-11 06:41 Deeply nested name space alterations. Start of complete build through hardware setup and capture. Full integration and commitment to current build process on appveyor. Linkage and detaile system notes for iteration cycles. Merge with agile tracking structure in asana.</p> <div class="highlight"><pre><span></span><code><span class="mf">4612</span><span class="n">f58</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">initial</span><span class="w"> </span><span class="n">setup</span> <span class="n">a9d51cd</span><span class="w"> </span><span class="n">move</span><span class="w"> </span><span class="kr">to</span><span class="w"> </span><span class="n">long</span><span class="w"> </span><span class="n">polling</span><span class="w"> </span><span class="n">widget</span> <span class="n">dda1a00</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">application</span><span class="w"> </span><span class="n">maximized</span> <span class="n">f6693a6</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">application</span><span class="w"> </span><span class="n">maximized</span> <span class="n">a4c424d</span><span class="w"> </span><span class="n">full</span><span class="w"> </span><span class="n">screen</span><span class="w"> </span><span class="n">graph</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="kr">for</span><span class="w"> </span><span class="n">tests</span> </code></pre></div> <p>2016-11-11 16:30</p> <p>2016-11-10 06:56 Execution of linode ssd mitigation plan for cookbook failure issues at digital ocean. Start of server replication and outage monitoring setup. Noise isolation options and evaluation. Tracking of long term Dash stability metrics. Transition to longer nomenclature scheme. Testing with runtime generated widgets for saving components. Refinement of user interface complexity. Practice with deeply nested widget options</p> <p>2016-11-10 16:30</p> <p>2016-11-09 06:19 Remote support of incorrect board level documentation for FX2 vs. ARM customer development. Detailed evaluation of namespace testing issues and long term repurcusssions for Dash inteface. Tested with various nesting methods and custom widget development schemes. Research into common mechanisms for deeply nested widget interfaces in QT.</p> <p>2016-11-09 16:30</p> <p>2016-11-08 06:47 long term timing and visualization setup. Triple visualizer for windows 10, and 7 in place. Built version of Dash straight from appveyor installer on virgin systems in virtualization. Investigation of testing as a service providers. Noise reduction and interruption compensation options and long term plans.</p> <div class="highlight"><pre><span></span><code><span class="mf">50</span><span class="n">dcd74</span><span class="w"> </span><span class="n">full</span><span class="w"> </span><span class="n">screen</span><span class="w"> </span><span class="n">auto</span><span class="w"> </span><span class="n">timer</span><span class="w"> </span><span class="n">updates</span> <span class="mf">547</span><span class="n">df15</span><span class="w"> </span><span class="n">autofalloff</span><span class="w"> </span><span class="n">typo</span> </code></pre></div> <p>2016-11-08 16:30</p> <p>2016-11-07 06:45 UPS system installation for networking and servers. Manufacturing meeting and notes. Setup of Dash long term testing system and virtualization with W530 laptop. rclone encrypted backup recovery and verification. Corrupted disk restorations. Timeline preparations, paystub questions.</p> <p>2016-11-07 17:00</p> <p>2016-11-04 07:32 Scheduled system maintenance for battery backup installation. update team on cookbook and dash project management in asana. odrive and backup systems selection and purchase. Collation and assignment of licensing resources. Virtualization attempts at securing environment auto-lock. </p> <p>2016-11-04 14:30</p> <p>2016-11-03 07:13 Detailed progress review meeting. Environment distraction reduction plans. Matched replication of autofalloff pyqtgraph and numpy appveyor configuration with new dash codebase. Segmentation of Win10 Dash3 and Win10 Dash4 virtual machine development environments. Communication and sprints, plans, and focus.</p> <div class="highlight"><pre><span></span><code><span class="mf">7070</span><span class="n">fed</span><span class="w"> </span><span class="n">environment</span><span class="w"> </span><span class="n">typo</span><span class="w"> </span><span class="n">fixes</span> <span class="mf">0590</span><span class="n">a2a</span><span class="w"> </span><span class="n">mkl_avx</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="n">appvyeor</span><span class="w"> </span><span class="n">conda</span><span class="w"> </span><span class="n">env</span> <span class="mf">42</span><span class="n">dd55d</span><span class="w"> </span><span class="n">conda</span><span class="w"> </span><span class="n">install</span><span class="w"> </span><span class="n">cle4anup</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="n">appvyeor</span> <span class="mf">373</span><span class="n">f3cb</span><span class="w"> </span><span class="n">different</span><span class="w"> </span><span class="ow">or</span><span class="n">der</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">appveyor</span><span class="w"> </span><span class="n">install</span> <span class="n">fb535a4</span><span class="w"> </span><span class="n">pyside</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">no</span><span class="w"> </span><span class="n">python</span><span class="w"> </span><span class="n">version</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="n">install</span> <span class="mf">88</span><span class="n">ac8d8</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">conda</span><span class="w"> </span><span class="kr">list</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">pip</span><span class="w"> </span><span class="nb">fre</span><span class="n">eze</span> <span class="mf">51</span><span class="n">fa6df</span><span class="w"> </span><span class="n">init</span><span class="w"> </span><span class="kd">restore</span> <span class="mf">3</span><span class="n">f262c8</span><span class="w"> </span><span class="n">direct</span><span class="w"> </span><span class="n">copy</span><span class="w"> </span><span class="n">match</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">autofalloff</span><span class="w"> </span><span class="n">appveyor</span> <span class="mf">987</span><span class="n">fcc3</span><span class="w"> </span><span class="n">built</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">pyqtgraph</span><span class="w"> </span><span class="n">included</span> <span class="n">fe75d2e</span><span class="w"> </span><span class="n">documentation</span><span class="w"> </span><span class="n">updates</span> <span class="mf">77</span><span class="n">bf625</span><span class="w"> </span><span class="n">designer</span><span class="w"> </span><span class="n">installation</span><span class="w"> </span><span class="ow">not</span><span class="n">es</span> </code></pre></div> <p>2016-11-03 16:35</p> <p>2016-11-02 07:15 second set of ME prep, setup and ME interview. Staff meetings. Setup and integration of full build on minimal system with appveyor and matching virtualbox win10 development environment with svg support. Established baseline procedures for new system development all the way through svg inclusion, qt designer cross platform development, and completed applications with included libraries.</p> <div class="highlight"><pre><span></span><code><span class="mf">841</span><span class="n">a280</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">svg</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">uifile</span><span class="w"> </span><span class="n">from</span><span class="w"> </span><span class="n">windows</span><span class="w"> </span><span class="n">designer</span> <span class="mf">...</span> <span class="mf">76</span><span class="n">c686a</span><span class="w"> </span><span class="n">corrected</span><span class="w"> </span><span class="n">travis</span><span class="p">,</span><span class="w"> </span><span class="n">add</span><span class="w"> </span><span class="n">appveyor</span> <span class="mf">54</span><span class="n">e4e06</span><span class="w"> </span><span class="n">travis</span><span class="w"> </span><span class="n">update</span> <span class="mf">0</span><span class="n">b7f47e</span><span class="w"> </span><span class="n">updated</span><span class="w"> </span><span class="n">environment</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="kr">read</span><span class="n">me</span> <span class="mf">...</span> <span class="mf">65</span><span class="n">ef3dd</span><span class="w"> </span><span class="n">rebuild</span><span class="w"> </span><span class="n">instruction</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">uic</span><span class="w"> </span><span class="n">rcc</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="n">conda</span> </code></pre></div> <p>2016-11-02 18:47</p> <p>2016-11-01 07:06 prep, setup and review of ME interview. Detailed evaluation and environment match of svg-utilization in python setup for windows and linux cross platform variations. Evaluated back through wheel builds, build from sources for versions 1.2.0, 1.2.1 and 1.2.4. Established baseline functionality for png iconagraphy only</p> <div class="highlight"><pre><span></span><code><span class="mf">04248</span><span class="n">f5</span><span class="w"> </span><span class="n">package</span><span class="w"> </span><span class="kr">list</span><span class="w"> </span><span class="n">comparisons</span> <span class="mf">020</span><span class="n">f5ee</span><span class="w"> </span><span class="n">png</span><span class="w"> </span><span class="kr">on</span><span class="n">ly</span><span class="w"> </span><span class="n">resource</span><span class="w"> </span><span class="n">file</span> <span class="n">cb0c86c</span><span class="w"> </span><span class="n">rebuilt</span><span class="w"> </span><span class="kr">on</span><span class="w"> </span><span class="n">windows</span> <span class="mf">8573</span><span class="n">c3c</span><span class="w"> </span><span class="n">resources</span><span class="w"> </span><span class="n">file</span> </code></pre></div> <p>2016-11-02 17:54 </p> <p>2016-10-31 07:19 detailed mac integration plan for milestone support. Full nested layout tests of qt designer with new dash integration. Start of software test platform recovery plan and integration into production. Beginning of ME addition interview process. VPN setup and zemax remote support. Transmission integration steps</p> <div class="highlight"><pre><span></span><code><span class="mf">3386581</span><span class="w"> </span><span class="n">manual</span><span class="w"> </span><span class="n">addition</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">capture</span> <span class="mf">8</span><span class="n">bbb5e9</span><span class="w"> </span><span class="n">recovery</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">resources</span> <span class="mf">8</span><span class="n">fdaff0</span><span class="w"> </span><span class="n">scroll</span><span class="w"> </span><span class="n">bars</span><span class="w"> </span><span class="n">by</span><span class="w"> </span><span class="kd">def</span><span class="n">ault</span><span class="w"> </span><span class="n">with</span><span class="w"> </span><span class="n">deep</span><span class="w"> </span><span class="n">named</span><span class="w"> </span><span class="n">nesting</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">resource</span> <span class="n">correction</span> <span class="mf">78</span><span class="n">e6984</span><span class="w"> </span><span class="n">names</span><span class="w"> </span><span class="kr">for</span><span class="w"> </span><span class="n">all</span><span class="w"> </span><span class="n">hsd</span><span class="w"> </span><span class="n">components</span> <span class="mf">3621325</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">display</span><span class="w"> </span><span class="n">details</span> <span class="mf">3</span><span class="n">d5a711</span><span class="w"> </span><span class="n">scroll</span><span class="w"> </span><span class="n">area</span><span class="w"> </span><span class="n">embedded</span><span class="w"> </span><span class="n">reverse</span><span class="w"> </span><span class="ow">or</span><span class="n">der</span><span class="w"> </span><span class="kr">for</span><span class="w"> </span><span class="n">hardware</span><span class="w"> </span><span class="n">setup</span> </code></pre></div> <p>2016-10-31 16:30</p> <p>2016-10-28 10:12 mac preparation of dash integration. Full project rebuild of dash from pysideapp basics. Recovery of test and integration badges and auto build capability for pysideapp, autofalloff, and Dash</p> <div class="highlight"><pre><span></span><code><span class="mf">4</span><span class="n">c6bffc</span><span class="w"> </span><span class="n">first</span><span class="w"> </span><span class="n">layer</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="n">updates</span> <span class="n">ddd748a</span><span class="w"> </span><span class="n">rebuild</span><span class="w"> </span><span class="n">check</span> <span class="mf">24</span><span class="n">d24bd</span><span class="w"> </span><span class="n">resources</span><span class="w"> </span><span class="n">specified</span> <span class="n">ae6a970</span><span class="w"> </span><span class="n">realignment</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">filesystem</span> <span class="n">a1ccc27</span><span class="w"> </span><span class="n">cleanup</span> <span class="mf">4</span><span class="n">dfb32b</span><span class="w"> </span><span class="n">structure</span><span class="w"> </span><span class="n">files</span> <span class="n">fc36978</span><span class="w"> </span><span class="n">cleanup</span> <span class="n">fe30fbe</span><span class="w"> </span><span class="n">tracking</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">generated</span><span class="w"> </span><span class="n">files</span> <span class="mf">4046</span><span class="n">fcd</span><span class="w"> </span><span class="n">compensation</span><span class="w"> </span><span class="kr">for</span><span class="w"> </span><span class="n">pyside</span><span class="o">-</span><span class="n">uic</span><span class="w"> </span><span class="n">failure</span> <span class="n">e66318d</span><span class="w"> </span><span class="n">asset</span><span class="w"> </span><span class="n">segmentation</span> <span class="mf">8</span><span class="n">ab5a06</span><span class="w"> </span><span class="n">asset</span><span class="w"> </span><span class="n">segmentation</span> <span class="mf">4674</span><span class="n">f16</span><span class="w"> </span><span class="n">detailed</span><span class="w"> </span><span class="n">testing</span><span class="w"> </span><span class="n">instructions</span> <span class="n">f3e3bf4</span><span class="w"> </span><span class="n">corrected</span><span class="w"> </span><span class="n">badges</span> <span class="n">a2816d0</span><span class="w"> </span><span class="n">badgets</span> <span class="n">f4b9a41</span><span class="w"> </span><span class="n">build</span><span class="w"> </span><span class="n">check</span> <span class="mf">6144</span><span class="n">f4e</span><span class="w"> </span><span class="n">setup</span><span class="w"> </span><span class="n">file</span> <span class="mf">414</span><span class="n">b100</span><span class="w"> </span><span class="n">manual</span><span class="w"> </span><span class="n">conversion</span><span class="w"> </span><span class="n">structure</span> <span class="n">ddf4da1</span><span class="w"> </span><span class="n">cleanup</span> </code></pre></div> <p>2016-10-28 16:30</p> <p>2016-10-27 08:28 Gource visualization of source code repositories. SSD integration and kernel update failure correction for W530. Pysideapp roll back of changes for appveyor support scripts and msvcr include cleanup. MTI product recovery for inventory. Remote supoprt of software locations for customers. (sick day)</p> <p>2016-10-27 16:30</p> <p>2016-10-26 06:37 Asana project tracking integration demo meeting. Detailed setup and evaluation of upgrades to customer stray light tracking systems. MTI discussion and recovery of detector options for drop in replacement.</p> <p>2016-10-26 16:41</p> <p>2016-10-25 06:26 Investigation into msvcr100.dll missing after appveyor build install. Merge of AutoFallOff back up the chain into a deployable application with no missing dependencies. Spectroscopy training. Recreation of fully deployable application from appveyor with environment required mkl_avx.dll from system in innosetup instead of direct tracking. Training on customer stray light detection systems.</p> <p>2016-10-25 16:35</p> <p>2016-10-24 06:38 Createion of placeholder Dash conversion project. Reset of computational environments to support simultaneous virtualization testing. Continued task population and forecasting integration with asana dashboard for Dash development. VPN Support and configuration. Backup power system identification and recovery.</p> <p>2016-10-24 16:30</p> <p>2016-10-21 06:38 Detailed setup and training with Asana progress dashboard. Split of milestones and individual components. Preparation for google sheet integration and display on company dashboard. Compensation and work on github outage. </p> <p>2016-10-21 16:32 </p> <p>2016-10-20 06:26 ISO IT requirements consideration. Test computer resource realignment. Setup of asana task project tracking structure. Review of new postiion candidates. 830 Product updates. Debug and test of SVISNIR-00002 with Transmission software project.</p> <p>2016-10-20 17:02</p> <p>2016-10-19 06:27 Transmission setup and coordination for SVIS_0002 recovery at HQ. 401k review and documentation. Printer fixes. OBP firmware load onto 830 product. OceanView training.</p> <p>2016-10-19 15:30 </p> <p>2016-10-18 06:44 Refinement of asana dashboards and alignment with software roadmap plan. Down select of interface items for new version of Dash. Architecture build and design limitation review. Available IT hardware resources review for accelerated development.A</p> <div class="highlight"><pre><span></span><code><span class="mf">830</span><span class="w"> </span><span class="n">product</span><span class="w"> </span><span class="n">documentation</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">deconflict</span> </code></pre></div> <p>2016-10-18 18:57</p> <p>2016-10-17 06:38 Creation of wasatch work log for better production tracking. Review of 401K plan. Reconfiguration of remote systems with hybrid ssd, spinning disk to verify ram or disk lockups. live new dash software demo with Jason. Driver signature process notes refinement and publish. UPS setup and email checks for primary workstation.</p> <p>2016-10-17 18:00 </p> <p>2016-10-14 06:34 Initial software prototype demonstration with David, Michael, and Chris.</p> <div class="highlight"><pre><span></span><code><span class="w"> </span><span class="n">c22b999</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">demo</span> <span class="w"> </span><span class="n">ee9ac8c</span><span class="w"> </span><span class="n">light</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">dark</span><span class="w"> </span><span class="n">steps</span><span class="w"> </span><span class="n">navigation</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="n">exmaple</span> <span class="w"> </span><span class="mi">39</span><span class="n">a0d0e</span><span class="w"> </span><span class="n">green</span><span class="w"> </span><span class="n">color</span><span class="w"> </span><span class="n">status</span><span class="w"> </span><span class="n">fix</span> <span class="w"> </span><span class="mi">868</span><span class="n">da8c</span><span class="w"> </span><span class="n">start</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">major</span><span class="w"> </span><span class="n">rework</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">wider</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="n">top</span> <span class="w"> </span><span class="mi">5</span><span class="n">eca8a2</span><span class="w"> </span><span class="n">reflance</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">absorbance</span><span class="w"> </span><span class="n">clean</span> <span class="w"> </span><span class="n">a28dbf8</span><span class="w"> </span><span class="n">loads</span><span class="w"> </span><span class="n">o</span><span class="w"> </span><span class="n">iconagraphy</span><span class="w"> </span><span class="ow">and</span><span class="w"> </span><span class="n">layout</span><span class="w"> </span><span class="n">updates</span> </code></pre></div> <p>2016-10-14 16:30</p> </div> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/content/posts/fedora_on_amazon.md Title: Fedora Workstation on Amazon EC2 Date: 2018-05-30 Category: articles Tags: system administration Creation of a high-memory, low disk instance with a full Fedora Workstation desktop experience. (t2.large EC2 instance 2 Processors, 8GB RAM) Designed for a low-cost, next level up replacement of a powerful desktop. An order of magnitude below big data, and an order of magnitude more capable than a 2013 era laptop. Or skip to the bottom for just the Wordpress on a free tier micro instance instructions. Launch a Fedora 28 Cloud Base Images for [Amazon Public Cloud](https://alt.fedoraproject.org/cloud/). As of 2018-11-05 13:28 Fedora no longer provides links to the images for use with amazon, the best approach is: <pre> EC2 -> Launch Instance -> Community AMIs -> Fedora -> Fedora-Cloud-Base-28-20180930.0.x86_64-hvm-us-east-1-gp2-0 - ami-0047163812982e5f3 </pre> Connect to the instance with: <pre> ssh \ -i your_key_pair.pem \ -L 4010:localhost:4000 \ -R 6622:localhost:22 \ fedora@amazon-ec2-public-dnsname </pre> <pre> 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 dnf update -y dnf group install "GNOME Desktop Environment" dnf install w3m reboot timedatectl set-timezone America/New_York reboot # If you don't reboot after changing the timezone, it will lockup # randomly After reboot, install nomachine: w3m 'https://www.nomachine.com/download/linux&id=1' (Download the 'plain' x86_64 linux nomachine) vi /etc/selinux/config change 'enforcing' to 'permissive' dnf install ./nomachine* # Change the fedora password so nomachine clients can login sudo su - passwd fedora exit # If you get a message about the connection being terminated before # you ever see a desktop, and when you start gnome-session manually # you get a 'terminated' error, try install tigervnc server first, # then run the vncserver command, then connect with the nomachine # commands below. In practice this looks like: dnf install tigervnc-server vncserver # (choose password) # Then on every reboot: vncserver; sleep 10; sudo systemctl restart nxserver # As of 2018-12-07 21:03 this will cause a lockup on the FC28 cloud # micro instance. If you increase the instance size to medium you # can login to the vncserver session first, then restart the # nxserver without causing the lockup. # Connect to the nomachine instance through the tunnel on port 4010 # If nomachine says no desktop created, check the box for "Always # create" # On first connect, you may have to change the nomachine resolution to # 1920x1080. Don't change it in the client, change it in the nomachine # settings. </pre> You should now have a full Fedora Workstation in the cloud that will start a new desktop session with Gnome automatically on nomachine connection. Use the script below to establish a tunnel over port 4010 to nomachine, and ssh back to the local system. From this stage, follow the standard [dotfiles](https://github.com/NathanHarrigton/dotfiles) configuration. ``` #!/bin/bash # Launch the instance, get the new ip address, establish an autossh # tunnel to the AMI # Use aws cli or the web interface to get your machines' instance id, # replace the variable below: INSTANCEID=i-GUID export PATH=/home/nharrington/miniconda3/bin:$PATH source activate conda_awscli aws ec2 start-instances \ --instance-ids $INSTANCEID \ --output=text QRY="Reservations[*].Instances[*].[InstanceId,PublicDnsName,Tags\ [?Key==\`Application\`].Value]" DNSNAME=`aws ec2 describe-instances \ --instance-ids=$INSTANCEID \ --query $QRY \ --output=text \ | awk '{print $2}'` echo $DNSNAME autossh \ -M 36622 \ -oStrictHostKeyChecking=no \ -i lls_key_pair.pem \ -L 8839:localhost:5901 \ -L 4010:localhost:4000 \ -R 6622:localhost:22 \ fedora@$DNSNAME ``` Looking for wordpress on amazon? Just use [bitnami image](https://aws.amazon.com/marketplace/pp/B00NN8Y43U?qid=1535236710075&sr=0-1&ref_=srh_res_product_title), then add the elementor plugin: <file_sep>/content/files/cached_developerworks_html/os-whistle.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><title>Whistle while you work to run commands on your computer</title><meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <link rel="schema.DC" href="http://purl.org/DC/elements/1.0/" /> <link rel="SHORTCUT ICON" href="http://www.ibm.com/favicon.ico" /> <meta name="Owner" content="dW Information/Raleigh/IBM" /> <meta name="DC.Language" scheme="rfc1766" content="en-US" /> <meta name="IBM.Country" content="ZZ" /> <meta name="Security" content="Public" /> <!-- <meta name="IBM.SpecialPurpose" content="SP001" /> <meta name="IBM.PageAttributes" content="sid=1003"/> --> <meta name="Source" content="Based on v14 Template Generator, Template 14"/> <meta name="Abstract" content="Use Linux or Microsoft Windows, the open source sndpeek program, and a simple Perl script to read specific sequences of tonal events -- literally whistling, humming, or singing to your computer -- and run commands based on those tones. Give your computer a short low whistle to check your e-mail or unlock your your screensaver with the opening bars of Beethoven's Fifth Symphony. Whistle while you work for higher efficiency." /><meta name="Description" content="Use Linux or Microsoft Windows, the open source sndpeek program, and a simple Perl script to read specific sequences of tonal events -- literally whistling, humming, or singing to your computer -- and run commands based on those tones. Give your computer a short low whistle to check your e-mail or unlock your your screensaver with the opening bars of Beethoven's Fifth Symphony. Whistle while you work for higher efficiency.f " /><meta name="Keywords" content="hdaps, perl, Linux, open source, <NAME>, tttosca, tttlca" /><meta name="DC.Date" scheme="iso8601" content="2007-01-09" /><meta name="DC.Type" scheme="IBM_ContentClassTaxonomy" content="CT316" /><meta name="DC.Subject" scheme="IBM_SubjectTaxonomy" content="" /><meta name="DC.Rights" content="Copyright (c) 2007 by IBM Corporation" /> <meta name="Robots" content="index,follow" /><meta name="IBM.Effective" scheme="W3CDTF" content="2007-01-09" /><meta name="Last update" content="09012007<EMAIL>" /><!-- STYLESHEETS/SCRIPTS --> <!-- for tables --> <link rel="stylesheet" type="text/css" media="screen,print" href="//www.ibm.com/common/v14/table.css" /> <!-- end for tables --> <script language="JavaScript" src="/developerworks/js/dwcss14.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="//www.ibm.com/common/v14/main.css" /> <link rel="stylesheet" type="text/css" media="all" href="//www.ibm.com/common/v14/screen.css" /> <link rel="stylesheet" type="text/css" media="print" href="//www.ibm.com/common/v14/print.css" /> <script language="JavaScript" src="//www.ibm.com/common/v14/detection.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/js/dropdown.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/email/grabtitle.js" type="text/javascript"></script> <script language="JavaScript" src="/developerworks/email/emailfriend2.js" type="text/javascript"></script><script language="JavaScript" src="/developerworks/js/urltactic.js" type="text/javascript"></script><script language="JavaScript" type="text/javascript"> <!-- setDefaultQuery('opensourceart'); //--> </script> <!--START RESERVED FOR FUTURE USE INCLUDE FILES--><script language="javascript" src="/developerworks/js/ajax1.js" type="text/javascript"></script><script language="javascript" src="/developerworks/js/searchcount.js" type="text/javascript"></script><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><script language="JavaScript" type="text/javascript">var emailAbstract = "Use Linux or Microsoft Windows, the open source sndpeek program, and a simple Perl script to read specific sequences of tonal events -- literally whistling, humming, or singing to your computer -- and run commands based on those tones. Give your computer a short low whistle to check your e-mail or unlock your your screensaver with the opening bars of Beethoven's Fifth Symphony. Whistle while you work for higher efficiency."; </script></head><BR><BR>This is an archived cached-text copy of the developerWorks article. Please consider viewing the original article at: <a href="http://www-128.ibm.com/developerworks/library/os-whistle">IBM developerWorks</a><BR><BR><BR><BR><body><!--MASTHEAD_BEGIN--><table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td class="bbg" width="110"><a href="http://www.ibm.com/"><img alt="IBM&reg;" border="0" height="52" src="//www.ibm.com/i/v14/t/ibm-logo.gif" width="110"/></a></td> <td class="bbg"><img src="//www.ibm.com/i/c.gif" width="1" height="1" border="0" alt="" /></td> <td align="right" class="mbbg" width="650"> <table border="0" cellpadding="0" cellspacing="0" align="right" > <tr class="cty-tou"> <td rowspan="2" width="17" class="upper-masthead-corner"><a href="#main"><img src="//www.ibm.com/i/c.gif" border="0" width="1" height="1" alt="Skip to main content"/></a></td> <td align="left"> <table border="0" cellpadding="0" cellspacing="0" align="left"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span><b class="country">Country/region</b><span class="spacer">&nbsp;[</span><a class="ur-link" href="http://www.ibm.com/developerworks/country/">select</a><span class="spacer">]</span></td> <td width="29" class="upper-masthead-divider">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td align="left"><a class="ur-link" href="http://www.ibm.com/legal/">Terms of use</a></td> </tr> </table> </td> <td width="40">&nbsp;</td> </tr> <tr> <td class="cty-tou-border" height="1" colspan="2"><img src="//www.ibm.com/i/c.gif" alt="" height="1" width="1"/></td> </tr> <tr> <td colspan="3"><img alt="" height="8" src="//www.ibm.com/i/c.gif" width="1"/></td> </tr> <tr> <td>&nbsp;</td> <td align="center" colspan="2"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <form method="get" action="//www.ibm.com/developerworks/search/searchResults.jsp" id="form1" name="form1"><input type="hidden" name="searchType" value="1"/><input type="hidden" name="searchSite" value="dW"/> <td width="18"><label for="q"><img src="//www.ibm.com/i/c.gif" width="1" height="1" alt="Search in:"/></label></td> <td align="right"><select id="sq" name="searchScope" class="input-local" size="1"> <label for="sq"><option value="dW" selected>All of dW</option> <option value="dW">-----------------</option> <option value="aixunix">&nbsp;&nbsp;AIX and UNIX</option> <option value="eserver">&nbsp;&nbsp;IBM Systems</option> <option value="db2">&nbsp;&nbsp;Information Mgmt</option> <option value="lotus">&nbsp;&nbsp;Lotus</option> <option value="rdd">&nbsp;&nbsp;Rational</option> <option value="tivoli">&nbsp;&nbsp;Tivoli</option> <option value="WSDD">&nbsp;&nbsp;WebSphere</option> <option value="dW">-----------------</option> <option value="archZ">&nbsp;&nbsp;Architecture</option> <option value="acZ">&nbsp;&nbsp;Autonomic computing</option> <option value="gridZ">&nbsp;&nbsp;Grid computing</option> <option value="javaZ">&nbsp;&nbsp;Java technology</option> <option value="linuxZ">&nbsp;&nbsp;Linux</option> <option value="opensrcZ">&nbsp;&nbsp;Open source</option> <option value="paZ">&nbsp;&nbsp;Power Architecture</option> <option value="webservZ">&nbsp;&nbsp;SOA &amp; Web services</option> <option value="webarchZ">&nbsp;&nbsp;Web development</option> <option value="xmlZ">&nbsp;&nbsp;XML</option> <option value="dW">-----------------</option> <option value="forums">&nbsp;&nbsp;dW forums</option> <option value="dW">-----------------</option> <option value="aW">alphaWorks</option> <option value="dW">-----------------</option> <option value="all">All of IBM</option> </label></select></td> <td width="7" align="right"><label for="q"><img src="//www.ibm.com/i/c.gif" width="1" height="1" alt="Search for:"/></label>&nbsp;&nbsp;</td> <td align="right"><input class="input" id="q" maxlength="100" name="query" size="15" type="text" value=""/> </td> <td width="7">&nbsp; </td> <td width="90"><input alt="Search" name="Search" src="//www.ibm.com/i/v14/t/search.gif" type="image" value="Search" /></td> <!-- <td width="20">&nbsp;</td> --> </form> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td class="blbg" colspan="3"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span></td> <td><a class="masthead-mainlink" href="http://www.ibm.com/">Home</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/products/">Products</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/servicessolutions/">Services &amp; industry solutions</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/support/">Support &amp; downloads</a></td> <td class="masthead-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="masthead-mainlink" href="http://www.ibm.com/account/">My IBM</a></td> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <script src="//www.ibm.com/common/v14/pmh.js" language="JavaScript" type="text/javascript"></script><!--MASTHEAD_END--><!-- CMA ID for this content is: 186736 --> <table id="v14-body-table" border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><!--LEFTNAV_BEGIN--><td id="navigation" width="150"><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="left-nav-spacer"><a href="http://www.ibm.com/developerworks" class="left-nav-overview"> </a></td></tr></table><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td colspan="2" class="left-nav-overview"><a href="http://www.ibm.com/developerworks" class="left-nav-overview">developerWorks</a></td></tr></table><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td colspan="2" class="left-nav-highlight"><a href="#" class="left-nav">In this article:</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10058" class="left-nav-child">Requirements</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N100A4" class="left-nav-child">Example setup and configuration</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N100F0" class="left-nav-child">Example setup for window management using xwit</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N1013C" class="left-nav-child">Additional examples</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10145" class="left-nav-child">The cmdWhistle.pl code</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#N10229" class="left-nav-child">Caveats and security concerns</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#download" class="left-nav-child">Download</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#resources" class="left-nav-child">Resources</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#author" class="left-nav-child">About the author</a></td></tr><tr class="left-nav-child-highlight"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/cl-bullet.gif"/></td><td><a href="#rate" class="left-nav-child">Rate this page</a></td></tr><tr class="left-nav-last"><td width="14"><img class="display-img" alt="" height="1" width="14" src="//www.ibm.com/i/c.gif"/></td><td width="136"><img class="display-img" alt="" height="19" width="136" src="//www.ibm.com/i/v14/t/left-nav-corner.gif"/></td></tr></table><br /><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="related" colspan="2"><b class="related">Related links</b></td></tr><tr class="rlinks"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/rl-bullet.gif"/></td><td><a class="rlinks" href="http://www.ibm.com/developerworks/views/opensource/library.jsp">Open source technical library</a></td></tr><tr class="rlinks"><td><img alt="" height="8" width="2" src="//www.ibm.com/i/v14/t/rl-bullet.gif"/></td><td><a class="rlinks" href="http://www.ibm.com/developerworks/views/linux/library.jsp">Linux technical library</a></td></tr><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- No content currently --><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><tr><td width="14"><img class="display-img" alt="" height="1" width="14" src="//www.ibm.com/i/c.gif"/></td><td width="136"><img class="display-img" alt="" height="19" width="136" src="//www.ibm.com/i/c.gif"/></td></tr></table><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- Next Steps Area: Start --> <!-- Commented out the include call in the dwmaster version of this file to prevent ajax calls being made during article previews and testing. Live site has uncommented copy of this file (jpp) --> <!-- Call Next Steps Servlet --> <script language="JavaScript" type="text/javascript"> <!-- /* * ajaxInclude makes a call to the url and render the results in the div tag specified in divId */ function ajaxInclude(url, divId) { var req = newXMLHttpRequest(); if (req) { req.onreadystatechange = getReadyStateHandler(req, function (result) { var contents = document.getElementById(divId); if (result != null && result.length > 0 && contents != null) { contents.innerHTML = result; } }); req.open("GET", url, true); req.send(""); } } //--> </script> <!-- Display Next Steps Result --> <div id="nextsteps"></div> <!-- Initiate Next Steps Call --> <script language="JavaScript" type="text/javascript"> <!-- ajaxInclude("/developerworks/niagara/jsp/getNiagaraContent.jsp?url="+window.location.href,"nextsteps"); //--> </script> <!-- Next Steps Area: End --><!--END RESERVED FOR FUTURE USE INCLUDE FILES--></td><!--LEFTNAV_END--><td width="100%"><table id="content-table" border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td width="100%"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td><a name="main"><img border="0" alt="skip to main content" height="1" width="592" src="//www.ibm.com/i/c.gif"/></a></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td height="18" width="10"><img alt="" height="18" width="10" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><img alt="" height="6" width="1" src="//www.ibm.com/i/c.gif"/><br /><a href="http://www.ibm.com/developerworks/" class="bctl">developerWorks</a><span class="bct">  &gt;  </span><a class="bctl" href="http://www.ibm.com/developerworks/opensource/">Open source</a><span class="bct"> | </span><a href="http://www.ibm.com/developerworks/linux/" class="bctl">Linux</a><span class="bct">  &gt;</span><img alt="" height="1" width="1" src="//www.ibm.com/i/c.gif"/><br /><h1>Whistle while you work to run commands on your computer</h1><p id="subtitle"><em>Use open source software and microphone-enabled laptops to listen for specific tonal sequences and run commands</em></p><img alt="" height="6" width="1" src="//www.ibm.com/i/c.gif" class="display-img"/></td><td class="no-print" width="192"><a href="http://www.ibm.com/developerworks/"><img alt="developerWorks" border="0" height="18" width="192" src="/developerworks/i/dw.gif"/></a></td></tr></table></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><table class="no-print" border="0" width="160" cellspacing="0" cellpadding="0" align="right"><tr><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="v14-header-1-small">Document options</td></tr></table><table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td class="no-padding" width="150"><table width="143" cellspacing="0" cellpadding="0" border="0"><script language="JavaScript" type="text/javascript"> <!-- document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img alt="Set printer orientation to landscape mode" height="16" src="//www.ibm.com/i/v14/icons/printer.gif" width="16" vspace="3" /></td><td width="122"><p><b><a class="smallplainlink" href="javascript:print()">Print this page</a></b></p></td></tr>'); //--> </script> <noscript></noscript><script language="JavaScript" type="text/javascript"> <!-- 5.6 10/24 llk: added cdata around the subdirectory path of email gif--> <!-- document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="Email this page" /></td><td width="122"><p><a class="smallplainlink" href="javascript:void newWindow()"><b>E-mail this page</b></a></p></td></tr>'); //--> </script><noscript><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td width="16"><img alt="" width="16" height="16" src="//www.ibm.com/i/c.gif"/></td><td class="small" width="122"><p><span class="ast">Document options requiring JavaScript are not displayed</span></p></td></tr></noscript><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td width="16"><img alt="" vspace="3" border="0" width="16" height="16" src="//www.ibm.com/i/v14/icons/dn.gif"/></td><td width="122"><p><a href="#download" class="smallplainlink"><b>Sample code</b></a></p></td></tr></table></td></tr></table><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- 11/28/07 refreshed by gem, per MOC --> <!--<br /><table border="0" cellpadding="0" cellspacing="0" width="150"><tr><td class="v14-header-2-small">New forum features</td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="v14-gray-table-border"><tr><td width="150" class="no-padding"><table border="0" cellpadding="0" cellspacing="0" width="143"><tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td><img src="//www.ibm.com/i/v14/icons/fw_bold.gif" height="16" width="16" border="0" vspace="3" alt=""/></td><td width="125"><p><a href="http://www.ibm.com/developerworks/community/forum/?S_TACT=105AGX01&amp;S_CMP=LEAF" class="smallplainlink">Try private messaging, read-tracking, and more </a> </p></td></tr></table></td></tr></table>--><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><br /><table width="150" cellspacing="0" cellpadding="0" border="0"><tr><td class="v14-header-2-small">Rate this page</td></tr></table><table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td class="no-padding" width="150"><table width="143" cellspacing="0" cellpadding="0" border="0"><tr valign="top"><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td><img alt="" vspace="3" border="0" width="16" height="16" src="//www.ibm.com/i/v14/icons/d_bold.gif"/></td><td width="125"><p><a href="#rate" class="smallplainlink"><b>Help us improve this content</b></a></p></td></tr></table></td></tr></table><br /></td></tr></table><p>Level: Intermediate</p><p><a href="#author"><NAME></a> (<a href="mailto:<EMAIL>?subject=Whistle while you work to run commands on your computer"><EMAIL></a>), Programmer, IBM<br /></p><p> 09 Jan 2007</p><blockquote>Use Linux&#174; or Microsoft&#174; Windows&#174;, the open source sndpeek program, and a simple Perl script to read specific sequences of tonal events -- literally whistling, humming, or singing at your computer -- and run commands based on those tones. Give your computer a short low whistle to check your e-mail or unlock your your screensaver with the opening bars of Beethoven's Fifth Symphony. Whistle while you work for higher efficiency.</blockquote><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><script language="JavaScript" type="text/javascript"> <!-- if (document.referrer&&document.referrer!="") { // document.write(document.referrer); var q = document.referrer; var engine = q; var isG = engine.search(/google\.com/i); var searchTerms; //var searchTermsForDisplay; if (isG != -1) { var i = q.search(/q=/); var q2 = q.substring(i+2); var j = q2.search(/&/); j = (j == -1)?q2.length:j; searchTerms = q.substring(i+2,i+2+j); if (searchTerms.length != 0) { searchQuery(searchTerms); document.write("<div id=\"contents\"></div>"); } } } //--> </script><!--END RESERVED FOR FUTURE USE INCLUDE FILES--> <p>For many years, computer users have been able to run processor-intensive speech recognition applications executing commands based on voice processing and requiring extensive configuration. While recent advances in processing power and algorithms have brought about user-independent voice recognition with reduced error rates, excellent opportunities exist for a simple tone pattern-based recognition system.</p> <p>Using the recently released sndpeek program to do the sophisticated processing, we will run a simple Perl program to allow for the easy generation of tonal codes. A Perl script will be presented to allow the user to customize the tonal input and detection environment.</p> <p><a name="N10058"><span class="atitle">Requirements</span></a></p> <p><a name="N1005E"><span class="smalltitle">Hardware</span></a></p> <p>You'll need a system with the capability of processing sound input, preferably from an integrated microphone, although any sound source capable of producing discrete tonal events will suffice. For example, whistling at your computer is one of the more effective ways to add a tertiary input channel (besides keyboard and mouse), but playback of an MP3 player's output through your line-in jack could produce the same results if configured properly. The code in this article was developed and tested on an IBM&#174; ThinkPad&#174; T42p with a 900-MHz processor and 1 GB of RAM. Much less-powerful systems should be easily capable of making use of the code presented in this article, as sndpeek is the primary resource consumer and is an efficient program.</p> <p><a name="N1006B"><span class="smalltitle">Software</span></a></p> <p>You'll need a functional sound-processing software environment to access your microphone hardware. Although sound configuration and troubleshooting is beyond the scope of this article, it may be useful to test this code on a Vector Linux Live CD, which has most of the drivers and components necessary for a functional setup of a diverse range of sound hardware. You will need at least a semifunctional installation of the sndpeek program, as the 3-D display portion of the code is not required.</p> <p>In <a href="#resources">Resources</a>, there is a link to the sndpeek Web page. Download the code and in the file <code>src/sndpeek/sndpeek.cpp</code>, find the section that says:</p> <br /><a name="N10083"><b>Listing 1. sndpeek modification</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> fprintf( stdout, "%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f ", mfcc(0), mfcc(1), mfcc(2), mfcc(3), mfcc(4), mfcc(5), mfcc(6), mfcc(7), mfcc(8), mfcc(9), mfcc(10), mfcc(11), mfcc(12) ); fprintf( stdout, "\n" ); </pre></td></tr></table><br /> <p>Ensure that the output of the program is actually written at the end of every print window by flushing the output. Change the above section to read:</p> <br /><a name="N10090"><b>Listing 2. Second sndpeek modification</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> fprintf( stdout, "%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f ", mfcc(0), mfcc(1), mfcc(2), mfcc(3), mfcc(4), mfcc(5), mfcc(6), mfcc(7), mfcc(8), mfcc(9), mfcc(10), mfcc(11), mfcc(12) ); fprintf( stdout, "\n" ); fflush(stdout); </pre></td></tr></table><br /> <p>Now run the typical <code>./configure; make; make install</code> commands to build and install sndpeek on Linux. For Windows, make sure the program builds correctly. There are many options for building programs on Windows, which are beyond the scope of this article. If you want to see cmdWhistle in action, I recommend using the Vector Linux Live CD.</p> <p>Next up is the xwit application installation for command-line windowing control. Check <a href="#resources">Resources</a> for a link to the xwit download, and install with no changes to the source code. You're now ready to create some simple tones.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N100A4"><span class="atitle">Example setup and configuration</span></a></p> <p><a name="N100AA"><span class="smalltitle">Creation of a simple tonal sequence</span></a></p> <p><a href="#download">Download</a> the source code and find the cmdWhistle.pl script. This is the main Perl program that allows you to create tonal sequences, as well as listen for specific tonal sequences and <code>run</code> commands. This article will first take you through the user-space usage and configuration of the cmdWhistle.pl program, then describe its various functions.</p> <p>Run the cmdWhistle.pl program with the following command: <code>sndpeek --print --nodisplay | perl cmdWhistle.pl -c</code>. This will start the sndpeek program listening to your microphone and print the output to the Perl program. Once the program is running, generate some simple whistles -- separate solid tones or rising-scale notes with one-third-second pause between. Note that you will have to be running this program in a relatively noise-free environment, so plug in your headphones and make sure your CD drive is spun down. If your laptop's battery is on fire, try unplugging the smoke detector before running this program.</p> <p>Experiment with different paces and tones to get a feel for the resolution of events the cmdWhistle program can capture. Experience with the subtleties of the program's tonal detection process is important for creating complex tone sequences that are repeatable. Your first tonal sequence should be simple: two low tones with 0.5 seconds between them for a "beep beep." Run <code>sndpeek --print --nodisplay | perl cmdWhistle.pl -c</code>, and when you see "enter a tone sequence," whistle twice with 0.5-second delay between the tones. An automatic timeout will occur after 4 seconds (configurable), and your tonal sequence will be printed out similar to the following example: <code>25.00 25.00 _#_ 0 500000 _#_ &lt;command here&gt; _#_ &lt;comment here&gt;</code>.</p> <p><a name="N100CC"><span class="smalltitle">Setup of command and detection of tonal sequence</span></a></p> <p>Let's dissect that line: tone values, delimiter, time values, delimiter, command area, delimiter, and comment area. Your next step is to copy this line into the default configuration file for the cmdWhistle.pl program: <code>{$HOME}/.toneFile</code>, which is probably /home/&lt;username&gt;/.toneFile. Once you have created the ~/.toneFile with the above tonal sequence line, you can modify the line to run a program. Change the command area text to <code>/bin/echo "two low"</code> and modify the comments area to something more descriptive, like <code>25.00 25.00 _#_ 0 500000 _#_ /usr/bin/echo "two low" _#_ two low tones</code>.</p> <p>Now that you have modified the configuration file to print out a notification, run the cmdWhistle.pl script in daemon mode with the command <code>sndpeek --print --nodisplay | perl cmdWhistle.pl</code>. The program will silently listen in the background for any of the events from the ~/.toneFile listing. Try your double low-tone whistle with the same temporal spacing and the same notes, and you will see the text "two low" printed to the screen. If you want to see the functioning of the cmdWhistle.pl script in detail, run it in daemon mode with the command <code>sndpeek --print --nodisplay | perl cmdWhistle.pl -v</code>. If your system supports the graphics display, remove the <code>--nodisplay</code> option for an excellent 3-D visualization of the sound input.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N100F0"><span class="atitle">Example setup for window management using xwit</span></a></p> <p><a name="N100F6"><span class="smalltitle">Creation of raise, lower, and iconify sequences</span></a></p> <p>There are many options for useful tone input that mimic keyboard shortcuts or mouse movements. The example below is focused on providing window management functions to allow the user to keep his hands in the home position, happily hacking away while windows are placed as he prefers. Please see the "Additional examples" section for more detail on the possibilities offered with this expanded input method.</p> <p>Run the cmdWhistle.pl program in "create" mode with the command <code>sndpeek --print --nodisplay | perl cmdWhistle.pl -c</code>. You need to create some simple tones you can reproduce with ease for quick window management functions. I recommend a low tone for "lower," a high tone for "raise," and two midtones for "iconify." Make sure you pick something you can consistently perform accurately. Although you'll be able to modify the parameters that control the precision with which you need to enter your tonal sequences (both in pitch and time), it can still be difficult to match the tone in question or the precise timing. Three tonal options widely spaced in pitch is a good mix between command flexibility and simplicity for those of us who need more practice at the karaoke bar. Here is a sample ~/.toneFile with the three commands:</p> <br /><a name="N1010A"><b>Listing 3. Sample ~/.toneFile with three commands</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> 20.00 _#_ 0 _#_ /usr/bin/xwit -pop -names rxvt _#_ raise rxvt windows # # 40.00 _#_ 0 _#_ /usr/bin/xwit -pop -names nathan _#_ raise xterms starting with nathan@localhost # # 25.00 25.00 _#_ 0 500000 _#_ /usr/bin/xwit -iconify -names nathan _#_ iconify nathan@localhost~ </pre></td></tr></table><br /> <p>Consider replacing the xwit commands with echo alternatives and practicing before sustained usage.</p> <p><a name="N10113"><span class="smalltitle">xwit - X functions accessible from a shell script</span></a></p> <p>Although there are many methods of command-line window control for X Window System, xwit is one of the more simple and portable methods that will work for many window managers. Download and install xwit, and execute the command <code>xwit -iconify</code> to ensure that the program is working. (This will minimize your current window) Although xwit does not have a "lower" function, we can provide a workaround by raising other windows. For this example, we use the the single high tone (40.00) to raise the windows with a title beginning with "nathan." Setting the title of your xterms is a simple mode of identification suitable for typical programming-type tasks. Other windows will be raised using a single low tone (20.00) if they begin with rxvt. Two medium tones (25.00) with a half-second delay will cause all of the windows that have a title beginning with "nathan" to be iconified. See <a href="#resources">Resources</a> for examples of what this looks like.</p> <p>One of the key benefits to this setup is the ability to continue typing in one window while making another window visible. This is useful for building subroutine structures while you bring your documentational reference to the foreground for API information. In effect, you can compute faster than you can type -- you can type and manage your windowing environment at the same time.</p> <p><a name="N10127"><span class="smalltitle">Windows shell scripts for raising and lowering windows</span></a></p> <p>For controlling windows on Microsoft operating systems, once simple way to raise windows is to use the WshShell.AppActivate command. If, for example, we want to raise the "gvim" application, we would create a file called "gvimActivate.vbs" with the following code:</p> <table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.AppActivate "gvim"; </pre></td></tr></table><br /> <p>With the above file in place, all we have to do is execute it, and the "gvim" window will be given focus and brought to the foreground. If you are running on Windows, change the simple high-tone command in the ~/.toneFile to <code>40.00 _#_ 0 _#_ gvimActivate.vbs _#_ raise gvim window</code>.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N1013C"><span class="atitle">Additional examples</span></a></p> <p>The sndpeek program and cmdWhistle.pl provide an additional user-input mechanism that can be utilized in unique ways. Set up an unlock code for your screensaver and whistle as you approach your desk -- no more bothersome password typing. Check your e-mail every time you whistle, check for your cell phone's unique tones, and send yourself an e-mail when your phone rings.</p> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N10145"><span class="atitle">The cmdWhistle.pl code</span></a></p> <p><a name="N1014B"><span class="smalltitle">History and strategy</span></a></p> <p>Fast Fourier transforms, sliding percentage windows, and some Linux audio programming can give you tonal-recognition capabilities with your language of choice. The sndpeek application, written by <NAME>, <NAME>, and <NAME>, provides a portable, fast and UNIX&#174; way of acquiring the information cmdWhistle.pl needs to detect tonal events. The simple command <code>sndpeek --print</code> will show real-time text analytics of the current sound source, as well as provide an excellent 3-D visualization. The fourth entry in the text analytics printed out by sndpeek is the output of the <code>Rolloff</code> function of sndpeeks processing using the "Marsyas" component of the sndtools distribution. Here's the description from the Rolloff.cpp source code:</p> <br /><a name="N10162"><b>Listing 4. Description from the Rolloff.cpp source code</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> Compute Rolloff (a percentile point) of the input fvec. For example if perc_ is 0.90 then Rolloff would be the index where the sum of values before that index are equal to 90% of the total energy. </pre></td></tr></table><br /> <p>Using this value as our base "tone," the cmdWhistle.pl script will detect various time intervals between tones.</p> <p><a name="N1016B"><span class="smalltitle">Parameter configuration</span></a></p> <p>Let's start at the top of cmdWhistle.pl with the timing- and sensor-critical parameters:</p> <br /><a name="N10178"><b>Listing 5. cmdWhistle.pl timing- and sensor-critical parameters</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> $|=1; #for non buffered standard output, useful for other programs to read require 'sys/syscall.ph'; # for subsecond timing my $option = $ARGV[0] || ""; # simple option handling my $MAX_TIMEOUT_LENGTH = 4; # maximum length in seconds of tone pattern my $LISTEN_TIMEOUT = 2; # timeout value in seconds between tone my $MAX_TIME_DEV = 100000; # maximum acceptable deviation between recorded # pattern values and current time values my $MAX_TONE_DEV = 2; # maximum acceptable deviation between recorded # pattern values and current tone values my $MAX_AVG_TONE = 5; # maximum number of samples to be averaged </pre></td></tr></table><br /> <p>The above variables and their comments are relatively straightforward. More detail will be available about their usage and configuration options later. The following is the remainder of the global variables and their descriptions.</p> <br /><a name="N10185"><b>Listing 6. Remainder of global variables and descriptions</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> my @queTones = (); # running queue of recent tones detected my $prevTone = 0; # the last solid tone detected, used for disambiguation my $prevInterval = 0; # previous interval of time my @baseTones = (); # the currently entered tone sequence my @baseTimes = (); # the currently entered temporal values my %toneHash = (); # tones, times and commands read from ~/.toneFile my $toneCount = 0; # the current count of tones entered my $startTime = ""; # start of a temporal block my $currTime = ""; # current time in the time out loop my $toneAge = 0; # for tone count synchronization my $timeOut = 0; # to reset the timer window </pre></td></tr></table><br /> <p><a name="N1018B"><span class="smalltitle">Subroutines</span></a></p> <p>We begin with the <code>getEpochSeconds</code> and <code>getEpochMicroSeconds</code> subroutines used to provide detailed and precise information on the status of temporal tonal patterns.</p> <br /><a name="N101A0"><b>Listing 7. getEpochSeconds and getEpochMicroSeconds subroutines</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> sub getEpochMicroSeconds { my $TIMEVAL_T = "LL"; # LL for microseconds my $timeVal = pack($TIMEVAL_T, ()); syscall(&amp;SYS_gettimeofday, $timeVal, 0) != -1 or die "micro seconds: $!"; my @vals = unpack( $TIMEVAL_T, $timeVal ); $timeVal = $vals[0] . $vals[1]; $timeVal = substr( $timeVal, 6); my $padLen = 10 - length($timeVal); $timeVal = $timeVal . "0" x $padLen; return($timeVal); }#getEpochMicroSeconds sub getEpochSeconds { my $TIMEVAL_T = "LL"; # LL for microseconds my $start = pack($TIMEVAL_T, ()); syscall(&amp;SYS_gettimeofday, $start, 0) != -1 or die "seconds: $!"; return( (unpack($TIMEVAL_T, $start))[0] ); }#getEpochSeconds </pre></td></tr></table><br /> <p>Next up is the <code>readTones</code> subroutine, which first acquires the <code>Rolloff</code> data value as output from sndpeek. As you can see from the following comments section, the code first develops five samples of tones to compare together to form a basis for computing deviation. If the tone array queue is up to capacity, compute the deviation for each tone. If the comparison to any single tone in the queue exceeds the maximum tonal deviation, specify that the current processing did not produce a discernable tone.</p> <p>If the deviation of all tones in the queue is less than the acceptable threshold, perform the temporal layer of ambiguity detection. If you whistle in a slowly increasing tone, your individual notes will deviate in small-enough amounts from the acceptable threshold to produce recognized tonal events. This continuous detection can cause a problem, however. The <code>upDev</code> and <code>downDev</code> variables and comparison logic are designed to acquire these contiguous tonal changes if they deviate more than the <code>MAX_TONE_DEV</code> variable. If both the recent tones queue check and the contiguous tone check are passed, record the tone event and its time for later printing or comparison.</p> <p>The careful modification of these variables will help tune the program to recognize your particular tonal style and temporal deviations. The overall refresh rate of frequency analysis is dictated by the output of the sndpeek program. All of the other parameters can be configured to detect more widely spaced tonal events -- multiple simultaneous tonal events across a time threshold, or different timings between the tonal events.</p> <br /><a name="N101C7"><b>Listing 8. Detect more widely spaced tonal events</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> sub readTones { # read the Rolloff output only, my(undef, undef, undef, $currentTone ) = split " ", $_[0]; if( @queTones == $MAX_AVG_TONE ) { my $localDiff = 0; # check for a solid tone by comparing against the last five tones # perform simple time related tonal smoothing, so if the tone # wavers just a bit it's still counted as one tone for my $chkHistTone ( @queTones ) { if( abs($currentTone - $chkHistTone) &gt; $MAX_TONE_DEV ) { $localDiff =1; $prevTone = 0; }#if deviation less than threshold }#for each tone if( $localDiff == 0 ) { # make sure the current tone is different than the previous one, this is to # ensure that long duration tones are not acquired as multiple tone events # this step up or down will allow you to whistle continuously and pick up the # steps as discrete tone events my $upDev = $currentTone + $MAX_TONE_DEV; my $downDev = $currentTone - $MAX_TONE_DEV; if( $prevTone &gt; $upDev || $prevTone &lt; $downDev ) { my $currVal = getEpochMicroSeconds(); my $diffInterval = abs($prevInterval - $currVal); if( $option ){ print "Tone: $currentTone ## last: [$currVal] curr: [$prevInterval] "; print "difference is: $diffInterval\n"; } if( $toneCount == 0 ){ $diffInterval = 0 } push @baseTones, $currentTone; push @baseTimes, $diffInterval; $toneCount++; $prevInterval = $currVal; }#if deviation in tone # now set the previous tone to the current tone so a continuous tone # is not acquired as multiple tone events $prevTone = $currentTone; }#if a solid tone has been found # if enough tones to create an useful queue have been added, pop one off shift @queTones; }#if enough tones to create a useful queue # always push more tones on the avg push @queTones, $currentTone; }#readTones </pre></td></tr></table><br /> <p>When a tonal pattern is created, it is placed in the ~/.toneFile file and read by the following subroutine.</p> <br /><a name="N101D4"><b>Listing 9. Tonal pattern creation</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> # readToneFile reads tone sequences and commands from ~/.toneFile # format is: tones _#_ times _#_ command _#_ comments sub readToneFile { #give it a full path to .toneFile if on windows open(TONEFILE,"$ENV{HOME}/.toneFile") or die "no tone file: $!"; while(&lt;TONEFILE&gt;){ if( !/^#/ ){ my @arrLine = split "_#_"; $toneHash{ "$arrLine[0] $arrLine[1]" }{ tones } = $arrLine[0]; $toneHash{ "$arrLine[0] $arrLine[1]" }{ times } = $arrLine[1]; $toneHash{ "$arrLine[0] $arrLine[1]" }{ cmd } = $arrLine[2]; $toneHash{ "$arrLine[0] $arrLine[1]" }{ comment } = $arrLine[3]; }#if not a comment line }#for each line in file close(TONEFILE); }#readToneFile </pre></td></tr></table><br /> <p>When a tonal pattern is acquired by <code>readTone</code>, it is compared to the existing tonal patterns loaded from <code>readToneFile</code>. The <code>compareToneSequences</code> subroutine performs a simple difference check between the timings of the tones, as well as the values of the tones. Note that the differences between tone values and timings is not compounded. Missing the timing or tone on many notes by a small amount will not accumulate into a total match failure.</p> <p>For each tone in the tone file, build the tonal and temporal arrays for matching. The first comparison is between the number of tones, as there is no point comparing a seven-tone sequence to a two-tone sequence. For each of the tones and times, check that the values are within the acceptable deviation parameters. Maximum tone and temporal deviation is critical to allowing the matching of your tonal sequences with accuracy, not precision. You can increase the maximum tone or time deviation to allow you to be more liberal in your rhythmic timings or tonal production. Caution and experimentation is called for, as liberal settings can lead to spurious detection results. For example, try increasing just the tone deviation threshold to <code>5</code>, keeping the temporal deviation threshold at <code>100000</code>. This will allow you to enter tones remotely related to the expected patterns, at the correct times, and still match a pattern -- useful if you wish to practice your timings only.</p> <p>If the full pattern is a match, the command specified in the ~/.toneFile is run and the result printed out if verbose mode is enabled. The next step is to exit the subroutine if no matches are found or reset the current tone and time records if a match is made.</p> <br /><a name="N101FB"><b>Listing 10. Tonal pattern creation</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> sub compareToneSequences { my $baseCount = @baseTones; my $countMatch = 0; # record how many tones matched for my $toneFromFile ( keys %toneHash ) { my @confTones = split " ", $toneHash{$toneFromFile}{tones}; my @confTimes = split " ", $toneHash{$toneFromFile}{times}; my $confCount = @confTones; next unless( $confCount == $baseCount ); # as a learning aid, the matching and non matching portions of the # comparison are printed out, so at least you can see what is going # wrong while trying to remember your tone codes my $pos =0; my $toneMatchFail = 0; for( @baseTones ) { my $tonDiff = abs($confTones[$pos] - $baseTones[$pos]); my $tonStr = "t $pos b $baseTones[$pos] ". "c $confTones[$pos] \n"; my $timeDiff = abs($confTimes[$pos] - $baseTimes[$pos]); my $timStr = "t $pos b $baseTimes[$pos] ". "c $confTimes[$pos] d $timeDiff\n"; if( $tonDiff &gt; $MAX_TONE_DEV ) { $toneMatchFail = 1; if( $option ){ print "NOTE DISSONANCE $tonStr" } }else { if( $option ){ print "NOTE MATCH $tonStr" } }#if tone detected outside of deviation # if it's an exact match, increment the matching counter if( $timeDiff &lt; $MAX_TIME_DEV ){ if( $option ){ print "TIME MATCH $timStr" } $countMatch++; }else{ if( $option ){ print "TIME DISSONANCE $timStr" } last; }# deviation check $pos++; }# for each tone to check if( $countMatch == $confCount &amp;&amp; $toneMatchFail == 0 ) { my $cmd = $toneHash{$toneFromFile}{ cmd }; if( $option ){ print "run: $cmd\n" } $cmd =`$cmd`; if( $option ){ print "result: $cmd\n" } last; # otherwise, make the count of matches zero, in order to not reset }else { $countMatch = 0; } }#for each tone in tone file # if the match count is zero, exit and don't reset variables so a longer # tone sequence can be entered and checked if( $countMatch == 0 ){ return() } # if a match occured, reset the variables so it won't match another pattern $toneCount = 0; @baseTones = (); @baseTimes = (); }#compareToneSeqeunces </pre></td></tr></table><br /> <p><a name="N10201"><span class="smalltitle">Main program logic</span></a></p> <p>With the subroutines in place, the main program logic will allow the user to create a tone sequence, or will run in daemon mode to listen for tones and execute commands. The first section is executed when the user specifies option "-c" for create mode. A simple timeout process is used to end the knock sequence. Increase the maximum timeout length variable to permit pauses of more than 4 seconds between tones. If you leave the maximum timeout length at 4, the program will end and print your currently entered tone sequence.</p> <br /><a name="N1020E"><b>Listing 11. Timeout process</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> if( $option eq "-c" ){ print "enter a tone sequence:\n"; $startTime = getEpochSeconds(); # reset time out start while( my $sndPeekOutput = &lt;STDIN&gt; ) { $currTime = getEpochSeconds(); # check if there has not been a tone in a while if( $currTime - $startTime &gt; $MAX_TIMEOUT_LENGTH ){ $timeOut = 1; # exit the loop }else{ # if a tone has been entered before timeout, reset timers so # more tones can be entered if( $toneCount != $toneAge ){ $startTime = $currTime; # reset timer for longer delay $toneAge = $toneCount; # synchronize tone counts }# if a new tone came in }# if timer not reached readTones( $sndPeekOutput ); if( $timeOut == 1 ){ last } }#while stdin if( @baseTones ){ print "place the following line in $ENV{HOME}/.toneFile\n\n"; for( @baseTones ){ print "$_ " } print "_#_ "; for( @baseTimes ){ print "$_ " } print "_#_ (command here) _#_ &lt;comments here&gt;\n\n"; }#if tones entered </pre></td></tr></table><br /> <p>Section two of the main logic continuously reads the output from the sndpeek <code>--print</code> command. Tonal groups are automatically reset after the timeout threshold is reached in order to differentiate between separate tonal patterns. Consider modifying the <code>LISTEN_TIMEOUT</code> variable to achieve faster tonal entry times, or lengthen the timeout variable to acquire tone patterns with more widely spaced events.</p> <br /><a name="N10223"><b>Listing 12. Modifying LISTEN_TIMEOUT</b></a><br /><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td class="code-outline"><pre class="displaycode"> }else { # main code loop to listen for tones and run commands readToneFile(); $startTime = getEpochSeconds(); while( my $sndPeekOutput = &lt;STDIN&gt; ) { $currTime = getEpochSeconds(); if( $currTime - $startTime &gt; $LISTEN_TIMEOUT ){ $toneCount = 0; @baseTones = (); @baseTimes = (); $startTime = $currTime; if( $option ){ print "listen timeout - resetting tones \n" } }else{ if( $toneCount != $toneAge ){ $startTime = $currTime; # reset timer for longer delay $toneAge = $toneCount; # synchronize tone counts }# if a new tone came in compareToneSequences(); }#if not reset timeout readTones( $sndPeekOutput ); }#while stdin }#if option set </pre></td></tr></table><br /> <br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><a name="N10229"><span class="atitle">Caveats and security concerns</span></a></p> <table align="right" border="0" cellspacing="0" cellpadding="0" width="150"><tr><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td><td><table border="1" cellspacing="0" cellpadding="5" width="100%"><tr><td bgcolor="#eeeeee"> <a name="N10232"><b>Share this...</b></a><br /> <p> <table border="0" cellpadding="0" cellspacing="0" width="135"><tr><td colspan="2"> <img alt="" border="0" height="5" src="//www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"> <a href="http://digg.com/submit?phase=2&amp;url=http://www.ibm.com/developerworks/opensource/library/os-whistle/"> <img alt="digg" border="0" height="10" src="//www.ibm.com/i/v14/icons/10x10-digg-thumb.gif" width="10"/> </a> </td><td> <a href="http://digg.com/submit?phase=2&amp;url=http://www.ibm.com/developerworks/opensource/library/os-whistle/">Digg this story</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="//www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"><a href="http://del.icio.us/post" onClick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=700,height=400'); return false;"><img alt="del.icio.us" border="0" height="10" src="//del.icio.us/static/img/delicious.small.gif" width="10"/></a> </td><td><a href="http://del.icio.us/post" onClick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=700,height=400'); return false;">Post to del.icio.us</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="//www.ibm.com/i/c.gif" width="1"/> </td></tr><tr align="left" valign="top"><td width="21"> <a href="javascript:location.href='http://slashdot.org/bookmark.pl?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title)"><img alt="Slashdot" border="0" height="16" src="//images.slashdot.org/favicon.ico" width="16"/></a> </td><td> <a href="javascript:location.href='http://slashdot.org/bookmark.pl?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title)">Slashdot it!</a> </td></tr><tr><td colspan="2"> <img alt="" border="0" height="5" src="//www.ibm.com/i/c.gif" width="1"/> </td></tr></table> </p> </td></tr></table></td></tr></table> <p>The cmdWhistle program is well suited for providing an additional channel of user input for your system, while allowing your hands to continue manipulating the mouse and keyboard. Be wary of using cmdWhistle to do anything requiring authentication on your system. </p> <p>In addition to the obvious issue of listeners recording and mimicking your selected tonal sequence to run commands on your system, there are many other variables associated with tonal authentication that indicate usage in any serious context is premature at best. The tonal sequences are currently stored as two-digit "notes" in the ~/.toneFile, along with four- to nine-digit representations of the delay in microseconds. It is compartively easy to read this "password" file, and simply try and match the tone pattern to gain access to the system. One-way hashes could be used by eliminating some of the precision in the microseconds values, but this is best left to the reader with a desire to evaluate the risks on their own.</p> <br /><br /><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td><img width="100%" src="//www.ibm.com/i/v14/rules/blue_rule.gif" height="1" alt=""/></td></tr></table><table class="no-print" cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /><p><span class="atitle"><a name="download">Download</a></span></p><table width="100%" class="data-table-1" cellspacing="0" cellpadding="0" border="0"><tr><th scope="col">Description</th><th scope="col">Name</th><th align="right" scope="col">Size</th><th scope="col">Download method</th></tr><tr><th class="tb-row" scope="row">Source code</th><td nowrap="nowrap">os-whistle.zip</td><td align="right" nowrap="nowrap">3KB</td><td nowrap="nowrap"><a class="fbox" href="http://www.ibm.com/developerworks/views/download.jsp?contentid=186736&amp;filename=os-whistle.zip&amp;method=http&amp;locale=worldwide"><b>HTTP</b></a></td></tr></table><table cellspacing="0" cellpadding="0" border="0"><tr valign="top"><td colspan="5"><img alt="" width="12" height="12" border="0" src="//www.ibm.com/i/c.gif"/></td></tr><tr><td><img alt="" height="16" width="16" src="//www.ibm.com/i/v14/icons/fw.gif"/></td><td><a class="fbox" href="/developerworks/library/whichmethod.html">Information about download methods</a></td><td><img alt="" height="1" width="50" src="//www.ibm.com/i/c.gif"/></td></tr></table><br /><br /><p><a name="resources"><span class="atitle">Resources</span></a></p><b>Learn</b><br /><ul><li> Princeton University hosts the <a href="http://www.cs.princeton.edu/sound/software/sndpeek/">sndpeek</a> program.<br /><br /></li><li> ibiblio.org hosts a mirror of the <a href="http://www.ibiblio.org/pub/X11/contrib/utilities/xwit-3.4.tar.gz">xwit</a> program.<br /><br /></li><li> See a demonstration video on <a href="http://youtube.com/watch?v=R1gkdILzA_s">YouTube.com</a> or check it out on <a href="http://video.google.com/videoplay?docid=-8678611162403535488">Google Video</a>.<br /><br /></li><li> Visit IBM developerWorks' <a href="http://www.ibm.com/developerworks/opensource/top-projects/php.html">PHP project resources</a> to learn more about PHP.<br /><br /></li><li> Stay current with <a href="http://www.ibm.com/developerworks/offers/techbriefings/?S_TACT=105AGX03&amp;S_CMP=art">developerWorks technical events and webcasts</a>.<br /><br /></li><li> Check out upcoming conferences, trade shows, webcasts, and other <a href="http://www.ibm.com/developerworks/views/opensource/events.jsp">Events</a> around the world that are of interest to IBM open source developers.<br /><br /></li><li> Visit the developerWorks <a href="http://www.ibm.com/developerworks/opensource">Open source zone</a> for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.<br /><br /></li><li> To listen to interesting interviews and discussions for software developers, be sure to check out <a href="http://www.ibm.com/developerworks/podcast/">developerWorks podcasts</a>.<br /><br /></li></ul><br /><b>Get products and technologies</b><br /><ul><li> Innovate your next open source development project with <a href="http://www.ibm.com/developerworks/downloads/?S_TACT=105AGX44">IBM trial software</a>, available for download or on DVD.<br /><br /></li></ul><br /><b>Discuss</b><br /><ul><li> Get involved in the developerWorks community by participating in <a href="http://www.ibm.com/developerworks/blogs/">developerWorks blogs</a>.</li></ul><br /><br /><p><a name="author"><span class="atitle">About the author</span></a></p><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td colspan="3"><img alt="" width="100%" height="5" src="//www.ibm.com/i/c.gif"/></td></tr><tr align="left" valign="top"><td><p/></td><td><img alt="" width="4" height="5" src="//www.ibm.com/i/c.gif"/></td><td width="100%"><p><NAME> is a programmer at IBM currently working with Linux and resource-locating technologies.</p></td></tr></table><br /><br /><br /><p class="no-print"><span class="atitle"><a name="rate">Rate this page</a></span></p><span class="no-print"><form action="http://www-128.ibm.com/developerworks/utils/RatingsHandler" method="post"><input value="1" name="SITE_ID" type="hidden"/><input value="Whistle while you work to run commands on your computer" name="ArticleTitle" type="hidden"/><input value="Open source, Linux" name="Zone" type="hidden"/><input value="http://www.ibm.com/developerworks/thankyou/feedback-thankyou.html" name="RedirectURL" type="hidden"/><input value="186736" name="ArticleID" type="hidden"/><input value="01092007" name="publish-date" type="hidden"/><input type="hidden" name="author1-email" value="<EMAIL>" /><input type="hidden" name="author1-email-cc" value="" /><script language="javascript" type="text/javascript">document.write('<input type="hidden" name="url" value="'+location.href+'" />');</script><img width="100%" src="//www.ibm.com/i/v14/rules/gray_rule.gif" height="1" alt=""/><br /><table width="100%" class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0"><tr><td width="100%"><table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3"><p>Please take a moment to complete this form to help us better serve you.</p></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Goal">Did the information help you to achieve your goal?</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><input value="Yes" id="Goal" name="Goal" type="radio"/>Yes</td><td><input value="No" id="Goal" name="Goal" type="radio"/>No</td><td><input value="Don't know" id="Goal" name="Goal" type="radio"/>Don't know</td></tr></table></td><td width="100%"> </td></tr><tr><td colspan="3"><img alt="" height="12" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Comments">Please provide us with comments to help improve this page:</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><textarea class="iform" cols="35" rows="5" wrap="virtual" id="Comments" name="Comments"> </textarea></td></tr></table></td><td width="100%"> </td></tr><tr><td colspan="3"><img alt="" height="12" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr valign="top"><td width="140"><img width="140" src="//www.ibm.com/i/c.gif" height="1" alt=""/><br /><p><label for="Rating">How useful is the information?</label></p></td><td width="303"><img width="303" src="//www.ibm.com/i/c.gif" height="6" alt=""/><br /><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td align="left" width="60"><input value="1" id="Rating" name="Rating" type="radio"/>1</td><td align="left" width="60"><input value="2" id="Rating" name="Rating" type="radio"/>2</td><td align="left" width="60"><input value="3" id="Rating" name="Rating" type="radio"/>3</td><td align="left" width="60"><input value="4" id="Rating" name="Rating" type="radio"/>4</td><td align="left" width="63"><input value="5" id="Rating" name="Rating" type="radio"/>5</td></tr><tr><td align="left" width="60"><span class="greytext">Not</span><br /><span class="greytext">useful</span></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="60"><img src="//www.ibm.com/i/c.gif" height="1" width="1" alt=""/></td><td align="left" width="63"><span class="greytext">Extremely<br />useful</span></td></tr></table></td><td width="100%"> </td></tr></table></td></tr></table><table class="v14-gray-table-border" width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3"><img alt="" height="8" width="8" src="//www.ibm.com/i/c.gif"/></td></tr><tr><td width="8"><img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif"/></td><td colspan="3"><input alt="Submit" height="21" width="120" border="0" src="//www.ibm.com/i/v14/buttons/submit.gif" type="image"/></td></tr><tr><td colspan="3"><img alt="" height="8" width="8" src="//www.ibm.com/i/c.gif"/></td></tr></table></form><br /></span><span class="no-print"><table cellspacing="0" cellpadding="0" align="right"><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle"><img width="16" src="//www.ibm.com/i/v14/icons/u_bold.gif" height="16" border="0" alt=""/><br /></td><td valign="top" align="right"><a href="#main" class="fbox"><b>Back to top</b></a></td></tr></table></td></tr></table><br /><br /></span></td><td width="10"><img alt="" height="1" width="10" src="//www.ibm.com/i/c.gif"/></td></tr></table></td></tr></table><!--FOOTER_BEGIN--><br /> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="bbg" height="19"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td><span class="spacer">&nbsp;&nbsp;&nbsp;&nbsp;</span><a class="mainlink" href="http://www.ibm.com/ibm/">About IBM</a></td> <td class="footer-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="mainlink" href="http://www.ibm.com/privacy/">Privacy</a></td> <td class="footer-divider" width="27">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a class="mainlink" href="http://www.ibm.com/contact/">Contact</a></td> </tr> </table> </td> </tr> </table> <script type="text/javascript" language="JavaScript1.2" src="//www.ibm.com/common/stats/stats.js"></script> <noscript><img src="//stats.www.ibm.com/rc/images/uc.GIF?R=noscript" width="1" height="1" alt="" border="0" /></noscript><!--FOOTER_END--><!--XSLT stylesheet used to transform this file: dw-document-html-5.8.xsl--></body></html><file_sep>/content/posts/learning_overview.md Title: Notes on transformational learning Date: 2017-09-14 Category: articles Tags: business model canvas **Page 1 of 1 card deck:** <pre> The search for value propositions customers can't resist, embedded in profitable and scalable business models. How are we going to do that? The business model canvas. What will be the result? A new idea shaped by the business model canvas that is profitable and will compliment the processes currently in place to run the business. What are you tactics used to achieve this: Perform the research, incorporation, execution cycle for each stage. Stage 1: program overview (everything on this one page) Stage 2: What was done, what we know now. This includes the top level business model canvas Stage 3: Meta-BMC - what makes a good business model canvas? Stage 4: Value propositions Stage 5: Customer segments Stage 6: Customer discovery and product market fit Stage 7: Test assumptions, Gather data, gain insights, repeat </pre> ** Card Deck Images** [![Front of Card Deck](/images/learning/thumbnails/notes_on_transformational_learning_card_deck_front.jpg)](/images/learning/notes_on_transformational_learning_card_deck_front.jpg) [![back of Card Deck](/images/learning/thumbnails/notes_on_transformational_learning_card_deck_back.jpg)](/images/learning/notes_on_transformational_learning_card_deck_back.jpg) <file_sep>/content/patents/patent_8,347,247.md Title: Visualization interface of continuous waveform multi-speaker identification Date: 2013-01-01 template: patent patent_number: 8,347,247 The programming instructions are operable to create a voiceprint from the current waveform if the current waveform is of a human voice. Furthermore, the programming instructions are operable to determine one of whether a match exists between the voiceprint and one library waveform of one or more library waveforms, whether a correlation exists between the voiceprint and a number of library waveforms of the one or more library waveforms and whether the voiceprint is unique. Additionally, the programming instructions are operable to transcribe the current waveform into text and provide a match indication display (MID) indicating an association between the current waveform and the one or more library waveforms based on the determining. <file_sep>/content/posts/learning_stage4.md Title: Stage Four: Value Propositions Date: 2017-09-22 Category: articles Tags: business model canvas Fourth Stage: Value Propositions **Research of known effective materials:** Udacity course: How to Build a Startup, Lesson 5: [Value Propositions](https://classroom.udacity.com/courses/ep245/lessons/48745133/concepts/482999050923) All sections 1 - 27 Strategyzer: [10 Characteristics of a great Value Proposition checklist](https://assets.strategyzer.com/assets/resources/10-characteristics-of-great-value-propositions-checklist.pdf) Strategyzer: [Sell Your Colleagues on Value Proposition Design](https://assets.strategyzer.com/assets/resources/sell-your-colleagues-on-value-proposition-design.pdf) Strategyzer: [Value Proposition Design book Preview](https://assets.strategyzer.com/assets/resources/value-proposition-design-book-preview-2014.pdf) ----------- #### Incorporation: **Card deck 1 of 6 INTRO** <pre> Chapter 1. Value Proposition What product or service are you building, for who, and what does it solve for those people? It's about satisfying a customer need, not just you thinking: "What a great idea". Chapter 4. COMPONENTS 1. The features of your products and services. 2. What gain are you creating for customers? 3. What pain are you solving for them? The goal is the smallest possible feature set that solves these pains and creates these gains for the customer. That is the Minimally Viable Product. Chapter 9. PRODUCT Which are part of your value proposition? -manufactured goods, commodity product... Which intangible products are part? -copyrights, licenses... Which financial products? -financial guarantees, insurance policies... Which digital products? -mp3 files, ebooks.... The product is the whole package of all the above Chapter 10. SERVICES Which core services are part of the value proposition? -Consulting, a haircut, investment advice... Which pre-sales or sales services? -help finding right solution, financing, free-delivery Which after-sales services? -free maintenance, disposal... What is it that your product features do? </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_intro_card_deck_front.jpg)](/images/learning/learning_value_proposition_intro_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_intro_card_deck_back.jpg)](/images/learning/learning_value_proposition_intro_card_deck_back.jpg) -------------------------------------------------- **Card deck 2 of 6 PAIN** <pre> PAIN KILLERS What are you going to reduce or eliminate for the customer? Chapter 12. PAIN Questions: Produce savings? Time, money, effort Feel better? Frustration, annoyance, headaches Fix solutions? New features, better, faster End challenges? Easier, eliminate resistance? Impact social consequences? wipe out negative social consequences or add to social status? Eliminate risk? Financial, social or technical risk Chapter 14. PAIN Importance Rank each pain according to its intensity and frequency </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_pain_card_deck_front.jpg)](/images/learning/learning_value_proposition_pain_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_pain_card_deck_back.jpg)](/images/learning/learning_value_proposition_pain_card_deck_back.jpg) -------------------------------------------------- **Card deck 3 of 6 GAIN** <pre> GAIN CREATORS What are the benefits the customer expects, desires or is surprised by? Chapter 15. GAIN Questions Happy customers? Save time, save money, save effort Better outcomes? Higher quality, more or less of something Exceed current solutions? Features, performance, quality Job or life easier? Create positive consequences? Social (need), business (more sales) Chapter 16. GAIN Importance Rank each gain your product and services create according to its relevance to the customer. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_gain_card_deck_front.jpg)](/images/learning/learning_value_proposition_gain_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_gain_card_deck_back.jpg)](/images/learning/learning_value_proposition_gain_card_deck_back.jpg) -------------------------------------------------- **Card deck 4 of 6 MVP ** <pre> Chapter 19. MVP Definition The first instance of your product or service that is delivered to customers. What is it that customers tell us that they will pay for or use right now. It is not a beta, tell customers it is the MVP. Chapter 17. MVP Physical Always invest a day or two building a physical product mockup. Something that customers can see and touch. Chapter 18. MVP Webmobile Build a "low fidelity" app or website to test the problem. This helps you avoid building products no one wants. Chapter 21. The art of the MVP It's based on interaction and iteration and understanding customers jobs, pains and gains. For new markets, don't ask about features, ask "How do they spend their time?" </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_front.jpg)](/images/learning/learning_value_proposition_mvp_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_back.jpg)](/images/learning/learning_value_proposition_mvp_card_deck_back.jpg) -------------------------------------------------- **Card deck 5 of 6 META-Value Prop** <pre> Chapter 22. COMMON MISTAKES It's just a feature of someones else's product "It's nice to have" instead of "got to have" Not enough customers care Chapter 23. QUESTIONS: Competition: What do customers do today? Make BMC's for the competition. Technology / Market Insight: Why is the problem so hard to solve? Why is the service not being done by other people? Market size: How big is this problem? Product: How do you make it once you understand the customer needs? Chapter 24: TWO FORMS: Technology insight: Typically applies to hardware, clean tech and biotech. Market insight: Changes in how people work, live, interact and what they expect. Both forms need to solve pains and create gains for the customer. Chapter 25: TYPES Technology Market More efficient lower cost better distribution smaller simpler better bundling faster better branding combine technology and market insights for the sweet spot of value propositions. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_meta_card_deck_front.jpg)](/images/learning/learning_value_proposition_meta_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_meta_card_deck_back.jpg)](/images/learning/learning_value_proposition_meta_card_deck_back.jpg) -------------------------------------------------- **Card deck 6 of 6 Examples** <pre> Technology Insights Ayasdi - topological analysis, solved previously unapproachable problems Inscopix - smaller fluorescence microscope - created new market Market insights Zynga - play more involved games - facebook distribution Twitter - micro-blog more than blog - solved a need JERSEYSQUARE Pains: cheaper way to wear jersey, eliminate risk of owning traded player Gain: provide alternative to purchasing counterfeit jersey Features: single place to rent sports jerseys MVP: website with rental and stock of jerseys OmegaChem Pain: non-renewable petroleum derived feedstock for surfactant industry Gains: Sustainable, bio-based replacement. Higher performance Improved cold temperature tolerance of detergents Features: Bi-functional molecules Flexibility in chain length MVP: chem-mix blue feedstock in 50-gal drums </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_value_proposition_examples_card_deck_front.jpg)](/images/learning/learning_value_proposition_examples_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_value_proposition_examples_card_deck_back.jpg)](/images/learning/learning_value_proposition_examples_card_deck_back.jpg) ------------------------------------------------------------------------- ## Execution: Lessons learned: 36 cards with about double the total content of any previous learning stage. Still took linear amounts of time to memorize when grouped into individual card decks. Re-merged with randomization for surprisingly no impact to time required for memorization and incorporation. Now making a new set of business model canvases for various problems I'm working on with these better value proposition ideas. The creation of these bmfiddles is showing many new frustrations and lack of clarity. Especially around the value propositions and customer segments - looking at others briefly from the udacity materials, then will recreate full BMC's for practice. Excellent - that instantly shows you were confused about what goes in the customer segment box. It's the persona, not the matching pains and gains. So execute a series of bmfiddles based on teh various ideas you are working on that include: 1. A pain solved for customer 2. A gain created for customer 3. Features for pain solved and/or gain created 4. mvp [![Example BMC](/images/learning/thumbnails/rain_bmc.png)](/images/learning/rain_bmc.png) [![Example BMC](/images/learning/thumbnails/noise_machine_app.png)](/images/learning/noise_machine_app.png) [![Example BMC](/images/learning/thumbnails/triangle_innovation.png)](/images/learning/triangle_innovation.png) [![Example BMC](/images/learning/thumbnails/data_science_matcher.png)](/images/learning/data_science_matcher.png) <file_sep>/content/posts/learning_stage5.md Title: Stage Five: Customer Segments Date: 2017-10-02 Category: articles Tags: business model canvas Fifth Stage: Customer Segments **Research of known effective materials:** Udacity course: How to Build a Startup, Lesson 6: [Customer Segments](https://classroom.udacity.com/courses/ep245/lessons/48632907/concepts/487392110923) Sections 1-9, 13-14, 26-27 Strategyzer: [A day in the Life of a customer](https://assets.strategyzer.com/assets/resources/a-day-in-the-life-worksheet.pdf) Strategyzer: [Business Model Generation Preview](https://assets.strategyzer.com/assets/resources/business-model-generation-book-preview-2010.pdf) Pages 20-21 Strategyzer: [Customer gains trigger questions](https://assets.strategyzer.com/assets/resources/customer-gains-trigger-questions.pdf) Strategyzer: [Customer pains trigger questions](https://assets.strategyzer.com/assets/resources/customer-pains-trigger-questions.pdf) Strategyzer: [Customer jobs trigger questions](https://assets.strategyzer.com/assets/resources/customer-jobs-trigger-questions.pdf) Strategyzer: [Identify high value jobs](https://assets.strategyzer.com/assets/resources/identify-high-value-jobs.pdf) Strategyzer: [Value Proposition Design book preview](https://assets.strategyzer.com/assets/resources/value-proposition-design-book-preview-2014.pdf) Pages 19-26 ----------- #### Incorporation: **Card deck 1 of 6 Overview** <pre> Customer segments GOAL: A deep understanding of the customer persona. Persona starts with: What functional, social or emotional job is the customer performing? What pains do they have? What gains do they want? Provide answers to the questions: Who are they, why would they buy, why won't they buy. What do you need to say to them? </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_overview_card_deck_front.jpg)](/images/learning/learning_customer_segments_overview_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_overview_card_deck_back.jpg)](/images/learning/learning_customer_segments_overview_card_deck_back.jpg) -------------------------------------------------- **Card deck 2 of 6 Jobs** <pre> The tasks they are trying to perform. The problems they are trying to solve. Or the needs they are trying to satisfy. Functional jobs Perform a specific task to solve a specific problem. Mow the lawn Eat healthy write a report Social jobs Describe how customers want to be perceived by others Look good or gain power or status Look trendy Be seen as competent Emotional jobs Customer seeks a specific emotional state Feel good or secure Seeking peace of mind regarding investments Crucial or trivial? At what frequency does it occur? Rank each job according to its significance to the customer What constraints and limitations are imposed on the job based on its context? </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_jobs_card_deck_front.jpg)](/images/learning/learning_customer_segments_jobs_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_jobs_card_deck_back.jpg)](/images/learning/learning_customer_segments_jobs_card_deck_back.jpg) -------------------------------------------------- **Card deck 3 of 6 Pains** <pre> Pains Anything that prevents your customers from getting a job done. Can annoy customers before, during and after trying to get a job done. Or describes risks related to getting a job done badly or not at all. 1. Cost Takes a lot of time, too much money, or requires substantial efforts? 2. Feel What are their frustrations, annoyances, or things that give them a headache? 3. Performance What features are they missing? What performance issues annoy them or malfunctions do they cite? 4. Challenges Do they not understand how things work, have difficulties getting certain things done, or resist particular jobs for specific reasons? 5. Social consequences Are they afraid of losing face, power, trust or status? 6. Risks Are there financial, social, or technical risks. Or are they asking themselves what could go wrong? 7. Anxiety What are their big issues, concerns and worries? 8. Mistakes Are they using a solution the wrong way? What common mistakes do customers make? 9. Barriers Are their upfront investment costs, a steep learning curve, or other obstacles preventing adoption? Make pains concrete "Waiting in line for 10 minutes is a waste" is better than "I hate standing in line" Pain severity A customer pain can be extreme or moderate, similar to how jobs can be important or insignificant to the customer. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_pain_card_deck_front.jpg)](/images/learning/learning_customer_segments_pain_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_pain_card_deck_back.jpg)](/images/learning/learning_customer_segments_pain_card_deck_back.jpg) -------------------------------------------------- **Card deck 4 of 6 Gains** <pre> Gains are benefits the customer expects, desires or would be surprised by. Gains include functional utility, social gains, positive emotions, and cost savings. 1. Savings Which time, money and effort reductions would they value. 2. Quality What would they wish more or less of? What quality levels do they expect? 3. Existing features What specific performance do they expect? How can you improve those features? 4. Easier A flatter learning curve, more services, or lower costs of ownership? 5. Positive social consequences What increases their power or status? What makes them look good? 6. Seeking most Are they searching for good design, guarantees, specific or more features? 7. Feel better What do they aspire to achieve, or what would be a big relief to them? 8. Measurements How does your customer gauge performance or cost? How do they measure success and failure? 9. Obstacles What would increase the likelihood of adopting a solution? Lower cost, lower risk, more fun, better quality? Make gains concrete "Performs 10 minutes faster" is better than "Increased performance" Rank your gains A customer gain can feel essential or nice to have. Make sure you are focusing on the most important gains to the customer </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_gain_card_deck_front.jpg)](/images/learning/learning_customer_segments_gain_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_gain_card_deck_back.jpg)](/images/learning/learning_customer_segments_gain_card_deck_back.jpg) -------------------------------------------------- **Card deck 4 of 6 Persona** <pre> Not only do you know about the pains and gains of the customers, you specifically know who they are. Profile Components position or title demographics role discretionary budget motivations Influencers Profile questions: Who are you? Why do you buy? Where do you buy? How much money do you have to spend? What matters to you? Who influences you? Day in the life Diagram what a customer does from when they get up and the products they use and the car they drive etc. Have a deep understanding of the customer and where your product fits. Who is the customer in relation to others? User->Influencer->Recommender->Decision Maker->Economic Buyer->Saboteur Teen Friends Dad Parents </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_persona_card_deck_front.jpg)](/images/learning/learning_customer_segments_persona_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_persona_card_deck_back.jpg)](/images/learning/learning_customer_segments_persona_card_deck_back.jpg) -------------------------------------------------- **Card deck 6 of 6 Examples** <pre> Simple two sided google search summary Multiple customer segments Each has its own value proposition each has it's own revenue stream one segment cannot exist without the other advertisers have google adwords web searchers have free search bar Company making kite boarding equipment Professional kite surfers - solely concerned with performance Average kit surfer - performance and cost sensitive - "one less thing to carry" effect Prospective kite surfer - cost sensitive - learning barrier Understanding the day in the life of the customer How does a designer spend their time putting together a architectural product? phase 1 design 6-8 weeks phase 2 prototyping 3-4 weeks phase 3 manufacturing 8-12 weeks phase 4 final product 3-4 weeks And our product fits right here and here's why JerseySquare Persona Attribute Gasol Junior Becky Age 32 15 24 Income $65k N/A $40K Demographics White White White Type Jersey Buyer Social statement social sports viewer Fan Type avid in-season casual Class middle middle middle Facebook Status single/compl. single in relationship rental type subscription subscription pay per rental </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_segments_examples_card_deck_front.jpg)](/images/learning/learning_customer_segments_examples_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_segments_examples_card_deck_back.jpg)](/images/learning/learning_customer_segments_examples_card_deck_back.jpg) -------------------------------------------------- ------------------------------------------------------------------------- ## Execution: Update your existing business model canvases (with snapshots), and popluate the customer segment area according to what you have learned here. <file_sep>/content/posts/music_for_work.md Title: Music for working Date: 2017-09-23 Category: articles Tags: music Goals: Control the external sensory environment. Hardware: [Bose QuietControl 30](https://www.bose.com/en_us/products/headphones/earphones/quietcontrol-30.html) [Bose QuietComfort 30](https://www.bose.com/en_us/products/headphones/over_ear_headphones/quietcomfort-35-wireless-ii.html#v=qc35_ii_black) (pre-google assistant version) Yes, both at the same time. Put the earbuds in, turn up noise cancellation all the way. Play the music through this set. Turn on the over ears, ensure the noise cancellation is on full, and put those on over the in-ears. Play no sound through the over-ears, just use noise cancellation. It's 700$ on your head, and it's worth every penny. Using these together means you won't be able to hear yourself type on a mechanical keyboard. You won't hear people have yelling conversations across rooms with your head in the middle. You won't hear door slams and outside vehicles. It's a beautiful thing. Face the wall - eliminate all peripheral vision. Literally add blinders to your glasses if you need to. As of 2021-10-25, the second best choice is a combination of noise isolating (not cancelling) ear buds, and noise cancelling over-ears. This is probably a 90% solution to the Bose setup before, for 1/7th the cost. Neckbands are definetly the way to go, as they have true all day battery life and over ears can fit over them. [SoundCore U2 neckband](https://www.amazon.com/gp/product/B086L8WF4D/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1) Put this in with the default silicone covers. Use the full spectrum music and noise generation setup described below. [Soundcore Q20 over ears](https://www.amazon.com/dp/B07NM3RSRQ?psc=1&ref=ppx_yo2_dt_b_product_details) Just turn these on with noise cancelling enabled, do not play any sound through them. The QuietComfort was no longer available. A comparable 70% solution are these [COWIN E7 Noise Cancelling Headphones](https://www.amazon.com/gp/product/B019U00D7K/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) They block significant noise. They are not as configurable. The biggest downside is that they hurt the ears after 2 hours instead of 3+ like the bose. It has nearly the same effect though. It's been about a month living with these as the over ears every day, and the only issue is the discomfort. A much cheaper alternative that will still let in significant outside noise and make your ears hurt after an hour: [ Howard Leight by Honeywell Sync Stereo MP3 Earmuff (1030110)](https://www.amazon.com/gp/product/B004U4A5RU/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) Put these in-ear plugs in first, then crank up the music through the earmuffs: [ Howard Leight by Honeywell MAX Disposable Foam Earplugs, 200-Pairs (MAX-1)](https://www.amazon.com/Howard-Leight-Honeywell-Disposable-MAX-1/dp/B0013A0C0Y/ref=sr_1_21?s=hi&ie=UTF8&qid=1507982199&sr=1-21&keywords=ear+plugs) ##Find and play music: What you are looking for is broad spectrum music. Examples are: [Best 8-bit electro gaming mix 2016](https://www.youtube.com/watch?v=6c0GqWbCcyg) **Do not browse youtube.com** Anything electronic, dubstep, gaming etc. is known for inappropriate imagery. or [Handel Organ Concertos](https://youtube.com/watch?v=6wvrHQ0aDC8) Both of which cover the low, mid and high range of frequencies in typical office environments, continuously. You may want the Goldberg Variations, but there is just simply too much empty space in the music to effectively drown out office environments. Start your search tool. Search one of the url's above. Look at the information for the video. If it's a compilation, search for playlists with the song name, or the artist name, like: //truecolor alchemist //fadex //organ concerto Then play the entire playlists, and make a note of the non-vocal entires. You're looking for zero vocalizations within the music. 1 minute of words (including the repetition) per 45 minutes of non-vocal music. The Tron Legacy sountrack for example. is a great example of what you are looking for. Select music by the following criteria: You're looking for pieces with a minimum of 100k views, with at least a 4 to 1 like to dislike ratio. More ideas for finding music non-vocal broad spectrum music: Fadex is almost perfect in what you are looking for. Look up their web presence and check for entries on their spotify favorites, playlists, and punch those names into playlists on mpsyt. ## Brown noise + Pink noise Alternatively or additionally if required, add in brown (low frequency) and pink (high frequency) noise overlaid on top of the music. If you must have the Goldberg Variations, for example, start the goldberg variations, then add in: [Brown noise](https://youtube.com/watch?v=GSaJXDsb3N8) and [Pink noise](https://youtube.com/watch?v=ZXtimhT-ff4) at about 60% music volume. It may seem loud at first, but it will blend in after a few minutes and you will realize later that it fills in the variability of office environment sounds resulting in increased focus. Preferrably, use sox for audio generation with one of these options: <pre> play -c 2 -n synth [brownnoise|whitenoise|pinknoise] </pre> ## Search tools ``` # on Fedora core 29 # Download and install conda3, make sure to use python version 3.7 dnf install mplayer conda create --name mpsyt_py37 python=3.7 source activate mpsyt_py37 pip install mps-youtube pip install youtube_dl # If that doesn't work, or it starts skipping files in playlists, or # otherwise won't play large swaths of youtube, you may need to # create an environment and load from source: # pip install --upgrade \ # https://github.com/mps-youtube/mps-youtube/archive/develop.zip Start mpyst in conda3 environment, then issue: >set player mplayer >set columns user:14 date likes dislikes views ``` Select music from by configuring the columns. You're looking for a minimum of 100k views, with at least a 4 to 1 like to dislike ratio. As of 2018-02-05 13:54, you'll also need to change the download command to make use of chunk sizing to prevent youtube throttling. Start mpsyt then issue the command below (newlines are for readability) ``` set download_command youtube-dl --user-agent \ "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0" \ --http-chunk-size 10M --extract-audio %u -o '%F' ``` ## Phone configuration Playing the music through cmus or mpsyt on the linux desktop is the best option. You still want podcasts and network connectivity through the phone as well. What you don't want is the various bose headsets announcing the calls and disrupting flow. These instructions are for a 2016 era Motorola Moto E Black (2nd Generation) on Ting wireless running Android 5.1. Connect the bluetooth headsets as Media audio, no phone audio, no contact sharing. Get a google voice number For the regular cell phone number, set Settings -> Sound and notification -> Interruptions When calls and notifications arrive: Allow only priority interrputions Priority interruptions: Events and reminders: on Calls: on Messages: on Calls/message from: contacts only Create a contact that has the google voice number called Google voice. Now you give out the google voice number to everyone, and it will automatically forward the calls to the actual phone number. Tell all your important contacts that you are letting everything go straight to voicemail on the google voice number. If they must reach you immediately, dial the main number. The phone will still light up, it will still vibrate for google voice calls. It will still light up for any other call that goes to the actual number as well, but only if it's already in your contact list. ## Deploying Use mpsyt as the primary music browser. As you find entries that meet the requirements, download them as 128k files. After downloading files, move them into subfolders. Change to each sub folder and run the conversion and sanitize names script to make sure they play on google music on android: ``` #!/bin/bash # # Convert downloaded files from mpsyt into mp3s # Sanitize the filenames so they will play on google play # # Run this in the directory of downloaded files # for i in *.webm do ffmpeg -i "$i" -ab 128k "${i%webm}mp3" rm "$i" done for i in *.m4a do ffmpeg -i "$i" -ab 128k "${i%m4a}mp3" rm "$i" done for i in *.ogg do ffmpeg -i "$i" -ab 128k "${i%ogg}mp3" rm "$i" done for i in *.opus do ffmpeg -i "$i" -ab 128k "${i%opus}mp3" rm "$i" done for i in *.mp4 do ffmpeg -i "$i" -ab 128k "${i%mp4}mp3" rm "$i" done # From: # https://odoepner.wordpress.com/2011/10/13/bash-script-to-\ # recursively-sanitize-folder-and-file-names/ sanitize() { shopt -s extglob; filename=$(basename "$1") directory=$(dirname "$1") filename_clean="${filename//+([^[:alnum:]_-\.])/_}" # The idea is this is easier to read filename_clean="${filename_clean//\:/_}" filename_clean="${filename_clean//\!/_}" filename_clean="${filename_clean//\?/_}" filename_clean="${filename_clean//\é/e}" filename_clean="${filename_clean//\è/e}" filename_clean="${filename_clean//\ü/u}" filename_clean="${filename_clean//\ô/o}" filename_clean="${filename_clean//\ç/c}" filename_clean="${filename_clean//\ñ/n}" filename_clean="${filename_clean//\å/a}" filename_clean="${filename_clean//\æ/ae}" filename_clean="${filename_clean//\Œ/oe}" filename_clean="${filename_clean//\ø/o}" filename_clean="${filename_clean//\ß/B}" if (test "$filename" != "$filename_clean") then mv -v --backup=numbered "$1" "$directory/$filename_clean" fi } export -f sanitize find $1 -depth -exec bash -c 'sanitize "$0"' {} \; ``` Move them to a folder on an external micro-sd card, then put the card in the phone. Play directly from the phone over bluetooth to the Bose in-ears. Don't even connect the over ears to bluetooth anything, just leave them as noise cancelling. As you come across entries on the phone that don't meet the criteria, delete them directly on the phone. <file_sep>/content/developerworks/os-metaphone.md Title: Make your 404 pages smarter with metaphone matching. Date: 2007-08-28 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-metaphone Create your own 404 error-message handler to provide useful links and redirects for the contents of your site. Use metaphone matching and a simple weighted score file to make typographical, spelling, and bad-link redirect suggestions. Customize the suggestions based solely on your Web site's content and preferred redirection locations. Catch multiple errors in incoming URL requests and process them for corrections in directory, script, and HTML page names. <file_sep>/content/posts/learning_stage7.md Title: Stage Seven: Test assumptions, gather data, gain insight, repeat Date: 2017-10-11 Category: articles Tags: business model canvas Seventh Stage: Test assumptions, gather data, gain insight, repeat **Research of known effective materials:** [Lean startup](http://theleanstartup.com/book) by <NAME> Udacity course: How to Build a Startup, Lesson 4: [Business Models and Customer Development](https://classroom.udacity.com/courses/ep245/lessons/48726358/concepts/483919610923) Sections 5 Strategyzer: [Testing your business model](https://assets.strategyzer.com/assets/resources/testing-your-business-model-a-reference-guide.pdf) Strategyzer: [The testing card](https://assets.strategyzer.com/assets/resources/the-test-card.pdf) Strategyzer: [The learning card](https://assets.strategyzer.com/assets/resources/the-learning-card.pdf) Strategyzer: [The Progress Board](https://assets.strategyzer.com/assets/resources/the-progress-board.pdf) Strategyzer: [Value Proposition Design book Preview](https://assets.strategyzer.com/assets/resources/value-proposition-design-book-preview-2014.pdf) Pages: 43-48 ----------- #### Incorporation: **Card deck 1 of 1 Overview** <pre> How do you make implicit assumptions explicit? Get out of the building, gain insights, then change the canvas. Extract hypothesis from your assumptions Prioritze Hypothesis Design Tests Prioritize Tests Run Tests Turn hypothesis into experiments Generate tests for jobs, pains and gains with 'mad libs': Testing card: We believe that: To verify that, we will: And measure: We are right if: (Test jobs, pains, gains and value propositions) Gather data How to actually talk with potential customers and surface insight about their needs and motivations. The tactics of communicating with customers to validate and invalidate hypothesis. Gain insight Map the customer segment personas. Develop a problem recognition matrix. Begin to recognize patterns that emerge during the discovery process. Learning card: We believed that: We observed: From that we learned that: Therefore, we will: Repeat Based on what you've learned, iterate or pivot, then make new assumptions, re-run the cycle </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_testing_cycle_card_deck_front.jpg)](/images/learning/learning_testing_cycle_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_testing_cycle_card_deck_back.jpg)](/images/learning/learning_testing_cycle_card_deck_back.jpg) -------------------------------------------------- ------------------------------------------------------------------------- ## Execution: <file_sep>/content/patents/patent_8,208,860.md Title: Reducing multipath signal degradation effects in a wireless transmission system Date: 2012-06-26 template: patent patent_number: 8,208,860 A transmitter transmits a signal to a receiver along a transmission path. The respective positions of the transmitter and the receiver are determined, and notice is received that a moving vehicle is proximate to the transmission path. Responsive to such notice, the moving vehicle position is determined, and such position is used with the transmitter and receiver positions to determine whether the moving vehicle is located between the transmitter and receiver positions. The calculated time delay is then used to provide a corrective signal component, which is employed to reduce degradation of the first component. <file_sep>/content/posts/sticker_code.md Title: QR Sticker Code generator for QL-700 Date: 2015-11-11 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/sticker_code_thumbnail.gif Web service to create qr codes, short links and [QL-700](http://www.brother-usa.com/LabelPrinter/ModelDetail/23/ql700/Overview) shaped stickers for device serialization . Live demo available at [waspho.com](http://waspho.com:8083/). This is used by the [CookBook](http://waspho.com) spectrometer tracking system. Requires the apparently defunct [PyQRNative](https://github.com/b45ch1/pyqrnative) project with the [wasatch fork](https://github.com/WasatchPhotonics/pyqrnative) to compile on linux. Available on [GitHub](https://github.com/WasatchPhotonics/StickerCode) <file_sep>/content/patents/patent_7,692,552.md Title: Method and system for improving driver safety and situational awareness Date: 2010-04-06 template: patent patent_number: 7,692,552 A method for enhancing driver safety through body position monitoring with remote sensors, and furnishing feedback in response to vehicle motion, driver activities, and external driving conditions. <file_sep>/content/posts/wasatch_cookbook.md Title: CookBook - Web application to display Wasatch Photonics device information and calibration reports. Date: 2016-04-13 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/cookbook_thumbnail.png Allows for the easy communication of device specific information to the customer, regardless of location. Previous integration systems used dropbox, google, or baidu. These are frequently banned by IT departments or entire geographical networks. The CookBook is a fully tested web application designed to get around these limitations. It's also specifically designed to address the Wasatch Photonics workflow. Uses the [Authomatic](http://peterhudec.github.io/authomatic/) library for oauth with Google apps for business. This allows authenticated users to create entries, post updated content, etc. External users have unrestricted access to the device information, drastically simplifying their remote support requirements. Full source code and implementation instructions available on: [Github](http://github.com/WasatchPhotonics/CookBook). <file_sep>/content/posts/humble_job.md Title: Stay humble, or get humbled. Date: 2015-05-27 Category: articles Tags: jobs Stay humble, or get humbled. - [<NAME>](https://www.youtube.com/watch?v=q9IZaj-v33o) You can't find a job. You've done all the postings, You've done all the resume cleaning. You've applied for dozens of what you thought were good fits. You had a seriously disappointing number of interviews. You've done it for months straight, 8 hours per day. It's like there was a black hole all your work went into. You feel rejected. You feel terrible. You never want to apply for a job again. You need money. You need to pay bills. You are deeply afraid of the consequences of running out of money. The fear is paralyzing, leading to inaction where it matters and activity where it doesn't. Driven to humility, you started the search again. you googled: "example software engineer resume" without the quotes. The previous first link from uptowork.com used to describe a system to embrace with humility. Unfortunately they took down the article. It was truly superb, written by <NAME>. See this [repository](/content/files/uptowork_resume_guide.txt) for text dump of the link circa 2018. It's fantastic. Here's the link to the current article for comparison. Don't use this, but keep it in mind as more of an example of what you can get lost in: [Uptowork software engineer resume](https://uptowork.com/blog/software-engineer-resume) Read the original article - feel the burden lift. Feel that yes you can do this, you have something to offer. Use the tool, make a first pass at a cut and paste replacement of the descriptions of the various entries. Get encouraged. Now you know the goal: Create a system for testing resumes that work, in order to help others. ----------------------------------------------------------------------- Write down the exact steps here. Create a lever you can pull. A series of instructions so well defined you can outsource the mechanics of the job search. The goal is not to find a job, the goal is to create a system for testing resumes that work. Make this a gift to your future self. For your children. For anyone who is hurting and has been paralyzed by fear of failure. You can't be afraid and grateful at the same time. Choose gratitude. Be grateful that you get this opportunity to write down the tactical and strategic details of your job search that will help others you love. Now you're starting to see all of the opportunities staring at you. They are truly aligned with your skills, you can legitimately have something to offer. You're excited again. Don't get bogged down in perfection. The ideal job is the one that takes the least amount of time. There is no job that is a substitue for your identity, there is no perfect fit that you must achieve. The instructions below are for the circa 2018 version of the zery resume builder, also known as uptowork resume builder. See the pictures folder for examples of the interface and what it could look like. <pre> Here is the workflow and timelines to follow to keep your momentum going. Set timers according to the values below, and do this process, and you will break out of a rut and have a successful job search. 60 minutes: Make a single master resume that lists all of your accomplishments, using the templates from the uptowork articles. This is a first pass, not an exhaustive list. This is to learn the patterns of production - do not get bogged down in making it perfect. 15 minutes: Find one job that looks like a fit. Again, it doesn't have to be a perfect fit. The goal at this stage is action. 30 minutes: Make a single master cover letter based on the cover letter tool from uptowork: Cover letter software engineer linked below. 10 minutes: Follow their applicant submission process for the job. If it's an Applicant Tracking System like brassring, fill out everything as required. Don't get frustrated, just see it like waiting in line for a ride at disney world - it's worth it. If it's an email to <EMAIL>: Subject: (Job Title) - <NAME> Body: Copy and paste from the body of the cover letter. Attachments: Cover letter.pdf Resume.pdf 5 Minutes: Create a Tracking document with the columns listed below. Save the file as "Job Search with Gratitude.csv" Keywords Source Company Job Title Submitted Date Path (email, or ATS) Automated Response Human Response Phone Call Skills Test Online In Person Interview Offer Notes </pre> [Cover letter](/content/files/uptowork_cover_letter_guide.txt) guide text example text dump. Newer version that's not as good available [here](https://uptowork.com/blog/software-engineer-cover-letter-example) Now as you look at other job opportunities, follow this pattern: Given a new job posting that looks like a fit: <pre> 15 minutes: If it's not within daily driving distance, it needs to be a 7/10 fit or better to continue this process. You don't want to move, but you don't want to waste peoples time either. If it's a very high probably of fit, then you would at least seriously consider moving at the end of the process. Think deeply on your skills and experience. Read the job opportunity and decide which of your experiences apply. Add a resume item to the master resume that is a reflection of that interplay. If you're looking for ideas, look back through your online profile. Restore old backups. Re-immerse yourself in the sights and sounds and the benefits to the business that those activities provided. Create a single work experience item based on the project. For example, if you had a project that took a few months and exactly fit the requirements they are looking for, add that as a work experience item on the main resume. That is the success they want you to repeat, so give that a full 'experience' run down. They want to hear more details about exactly the work you have done that will help them. This will rapdily fill the master resume with a wide variety of projects that you have worked on, in detail. Add a start and end date in year, do not include months 30 minutes: Do something else not job search related - anything else. This is critical to break you out of the perfection-inaction loop. You'll be tempted to get on a roll and do a bunch of these without this break. Take the break! Constraints are important, both on the work itself and on your 'break's. Use the timers, take the breaks. 15 minutes: Clone the master resume. Change the resume title to have the job title in it Change the personal info->Profession to be the job title Change the summary to be tailored to the job description. Remove any non-relevant parts of the experience that are not tailored to this job. Choose just the work descriptions from each company that apply. Delete the rest. Update the skills section to match the job posting. Only spend 15 minutes on this. You must complete this in 15 minutes. Again, it's ok if its not perfect. The goal is to break out of the depression-induced inaction cycle. Download the PDF, save as: FirstName_LastName_JobTitle_Resume.pdf for example: Nathan_Harrington_Scientific_Applications_Resume.pdf 15 minutes: Clone the master cover letter. Change the cover letter title to be: Job Title Change the "profession" to match the job title. Update the contents of the cover letter to match the job description. Save as: FirstName_LastName_JobTitle_Cover_Letter.pdf for example: Nathan_Harrington_Process_Engineer_Cover_Letter.pdf 10 minutes: Follow their applicant submission process for the job. If it's an email to <EMAIL>: Subject: (Job Title) - <NAME> Body: Copy and paste from the body of the cover letter. Attachments: Cover letter.pdf Resume.pdf 1 Minute: Update the job tracking sheet </pre> As you iterate through these steps, remember the goals: 1. Collect data on which resumes work for which jobs. 2. Create a system that you can operate that you can share with your future self, and anyone who needs it. 3. Record the successes and the failures. 4. Proceed in gratitude. Does this work? --------------- I followed the instructions above and had immediate positive results. The language and the layout updates to the resume as recommended by uptowork.com are a powerful differentiator. That's not the point. The point is to repeat this to collect enough data and get familiar with it. To write down the nuances of what it really takes to have good results. Never struggle again. Never fail at this again. Your professional training is not your identity. Fill yourself with gratefulness that you can use this process to help others. You're not struggling as punishment, it's training so you can help others. Lessons Learned --------------- They are looking for skills, and needs satisfied. Adapt yourself and your work experience to their needs. They are not hiring you, they are hiring for someone, anyone to fill the role. Put yourself in their position - they acquisition of talent is burdensome for most organizations, how can you meet their expectations? This took approximately 30 hours total effort, including the writing of these systems steps and refining the approach as documented above. The results were 3 excited recruiters playing the usual games of leading you on, and 3 rejections, 1 in-person interview and 13 black holes. The real point is humility works. 1 out of 20 applications leading to an in-person interview is a decent rate. Being able to do 20 applications with a 5% success rate with each taking less than 25 minutes is hugely successful. Then you can do one week of this effort, for 8 hours per day, and that should lead to 5 in-person interviews. If you must attain a job. If you must re-engage with the risks of a workaholic prison, this is where to start. Write down what you do, write down what works with a focus on humility, on gratitude for knowing that you're in training to help others. Take ownership: It is your job to make this process a success for you and for everyone else. Want More? ---------- There are two books that will change your focus and give you the ability to see the employers needs first: Extreme Ownership by <NAME> and <NAME>, and The Irresistible Consultant's Guide to Winning Clients by <NAME>. Whatever context you are in, giving them what they actually want will help. <file_sep>/content/patents/patent_7,945,071.md Title: Automatically generating precipitation proximity notifications Date: 2011-05-07 template: patent patent_number: 7,945,071 A method and system for automatically generating a notification of a status of precipitation being received by a user-defined detection zone within a geographic area. An image of the geographic area is received. The image includes pixels associated with the detection zone. Each pixel is associated with a sub-area of the detection zone. Characteristics (e.g., colors) of the pixels are obtained. The characteristics indicate intensities of precipitation being received by sub-areas of the detection zone. <file_sep>/content/developerworks/os-keystroke-perl-xev.md Title: Create a continuous keystroke-dynamics monitor with Perl and xev Date: 2008-10-07 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-keystroke-perl-xev Keystroke dynamics is a relatively new field that enables identification of individuals through statistical analysis of their typing patterns. Previously published articles on developerWorks have shown how to integrate the concept of keystroke dynamics into your applications, as well as a real-world example of modifying Gnome Display Manager (GDM) to require a correct password and a "correctly typed" password. This article presents tools and code allowing you to move beyond a single application of keystroke dynamics, and monitor your entire X Window System environment continuously for characteristic patterns of the typist. <file_sep>/content/patents/patent_8,587,667.md Title: Beyond Field-of-View Tracked Object Positional Indicators Date: 2013-11-19 template: patent patent_number: 8,587,667 A system and method for implementing beyond field-of-view tracked object positional indicators for television event directors and camera operators. The present invention includes a camera having a field-of-view. The camera tracks an off-screen object. A coordinate manager blends an on-screen indication of distance that the object is away from said field-of-view. The camera is positioned to avoid the object in the field-of-view. <file_sep>/content/posts/conda_and_pyside_incompatible_qt_library.md Title: Innosetup and manifest files for HiDPI displays Date: 2017-08-21 Category: articles Tags: wasatch photonics Use PySide 1.2 and Python 2.7. Deploy to various HiDPI displays for testing. You may see text that is either clipped, too large, or too small. Everything looks fine on Linux, but on Windows with the default scaling for HiDPI displays (125%), it can look like this: [![Fat font issue](/images/wasatch-images/fat_font_issue.png)](/images/wasatch-images/fat_font_issue.png) You'll want it to look like this: [![Fixed Fat font issue](/images/wasatch-images/fixed_fat_font_issue.png)](/images/wasatch-images/fixed_fat_font_issue.png) The solution is to modify your innosetup configuration to modify the registry: [Registry] ; PySide/PyQt 4.x does not support HiDPI displays. This mitigation ; approach turns on system-wide preference for external manifest, then ; installs a custom manifest file Root: HKLM64; Subkey: "SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide"; ValueType: dword; ValueName: "PreferExternalManifest"; ValueData: "1"; check: IsWin64; Root: HKLM; Subkey: "SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide"; ValueType: dword; ValueName: "PreferExternalManifest"; ValueData: "1"; check: "not IsWin64"; Then copy the manifest file: [Files] ... ; Manifest file for HiDPI mitigation - see above Source: "support_files\Enlighten.exe.manifest"; DestDir: "{app}\Enlighten\"; Flags: recursesubdirs ignoreversion ... All is well, except when running the application post install in InnoSetup. If you run post install you will see the application run with the wrong HiDPI configuration, but if you run after the installer has terminated, the application looks correct. The temporary fix is to disable running post install, and depend on the user to complete the install then run the application manually. Do you have a solution for this? If so, please update the [PySideApp](https://github.com/WasatchPhotonics/PySideApp) demonstration application. <file_sep>/content/developerworks/os-touchpad.md Title: Add multitouch gesture support to a TouchPad-equipped laptop. Date: 2008-06-03 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-touchpad Implement swipe and pinch gestures for Linux applications by analyzing tools and code needed to add some of this new gesture support on older Linux-enabled hardware. Building on the output of the synclient program, the Perl code presented here allows you to assign specific application functions to "Three-Finger Swipe," as well as Open- and Close-Pinch gestures. Demonstration video at [youtube](https://www.youtube.com/watch?v=AUNjmpgEWBA) Comments on digg (gone). Writeup at hackszine (yep, also gone) and [lwn.net](http://lwn.net/Articles/285377/). <file_sep>/content/posts/analyze_iq.md Title: AnalyzeIQ with Wasatch Photonics Date: 2015-09-03 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/wasatch_photonics_analyzeiq_thumbnail.png A custom interface for [AnalyzeIQ Lab](https://www.analyzeiq.com/Products/Analyze-IQ-Lab.html) that will collect data from Wasatch Photonics devices. Analyze IQ is a third party chemometrics solution that can also be used on [Ventana](http://oceanoptics.com/product-category/ventana-series/) devices from [Ocean Optics](http://oceanoptics.com/product/analyze-iq-chemistry-software/) Acquires data from Wasatch Photonics spectrometers, write out in xml format for use in AnalyzeIQ. This uses AnalyzeIQ's stdin/stdout interface, which is more than sufficient for multiple acquisitions per second. Pleasingly straightforward to integrate and test. Available on [GitHub](https://github.com/WasatchPhotonics/WasatchAnalyzeIQ) <file_sep>/content/posts/learning_stage6.md Title: Stage Six: Customer discovery and product market fit Date: 2017-10-09 Category: articles Tags: business model canvas Sixth Stage: Customer Discovery and Product Market fit **Research of known effective materials:** [Lean startup](http://theleanstartup.com/book) by <NAME> Udacity course: How to Build a Startup, Lesson 4: [Business Models and Customer Development](https://classroom.udacity.com/courses/ep245/lessons/48726358/concepts/483919610923) Sections 2, 8 How to Build a Startup, Lesson 5: [Value Propositions](https://classroom.udacity.com/courses/ep245/lessons/48745133/concepts/482999050923) Section 1 How to Build a Startup, Lesson 6: [Customer Segments](https://classroom.udacity.com/courses/ep245/lessons/48632907/concepts/487392110923) Section 1 <NAME> [The tactics of Customer Discovery](https://www.slideshare.net/sblank/customer-discovery-23251533) Login to slideshare/linkedin then download as .docx for offline use Pages 1-11 ----------- #### Incorporation: **Card deck 1 of 1 Overview** <pre> The relationship between value proposition and customer segments simply: Product Market fit Goal is connect the value proposition with what you are going to learn about customers from outside the buildling. Work through the cycle doing iterations and pivots as we discover what customers really want vs. what we're building for them. This is search for the business model: Phase 1 State hypothesis Draw the business model canvas inside the building. Phase 2 Test the problem Test your understanding of the customer problem or need. Phase 3 Test the solution Test the customers agreement that you have the solution. Phase 4 Verify or pivot Do customers agree that you are solving a high value problem or need? Do you understand your business model enough to start test selling? For most entreprenuers the answer the most often the first time is NO. The only time you know you have something worth investing your time and money in is if people are literally trying to force their money on you, or can't use your product - even in it's buggy uninitialized form - enough. </pre> [![Front of Card Deck](/images/learning/thumbnails/learning_customer_discovery_and_pmf_card_deck_front.jpg)](/images/learning/learning_customer_discovery_and_pmf_card_deck_front.jpg) [![Back of Card Deck](/images/learning/thumbnails/learning_customer_discovery_and_pmf_card_deck_back.jpg)](/images/learning/learning_customer_discovery_and_pmf_card_deck_back.jpg) -------------------------------------------------- ------------------------------------------------------------------------- ## Execution: <file_sep>/content/posts/luminancelabel.md Title: LuminanceLabel - Animated overlay and on-screen luminance measurements Date: 2015-11-12 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/luminancelabel_thumbnail.gif Demonstration video on [youtube](https://youtu.be/9qmNLBNOKwY) Uses PyQt to place a transparent overlay on the screen, takes a screenshot and processes the area underneath the overlay designator. Luminance values are computed and displayed on the label, and written to stdout. This is used for evaluting the displayed imagery at multiple frames per second for imaging software. Includes tests with QtTest that establish a window, then create an overlay window for known luminance values. Available on [GitHub](https://github.com/WasatchPhotonics/LuminanceLabel) <file_sep>/content/pages/index.md Title: <NAME> Date: 2017-09-15 Category: About save_as: index.html status: hidden template: hermann_homage_page Hi, my name is Nathan. I have the privilege of searching for value propositions at [Cordince](http://www.cordince.com), where we build software systems for amplifying growth. Our focus is software development in the tissue engineering space and machine learning in the clinical laboratory. Prior to this role, I focused my efforts on practicing software engineering at IBM, various startups, and building spectroscopy control systems. You can read much more in the [Blog](/category/articles.html), and find my full contact information and resume on the [details](/pages/about.html) page. <file_sep>/content/posts/obs_studio.md Title: OBS Studio home setup Date: 2021-03-02 Category: articles Tags: videoconferencing thumbnail_image: /images/obs_config.png OBS Studio hardware and software configuration focused on a better videoconferencing experience. The short answer is: get a ring light for your phone. This 20$ investment will make your videoconferences 80% better. Here's an example unit that worked fine with a 2020 era budget smart phone: https://www.amazon.com/gp/product/B075ZLCSGP/ Read on for the long answer on how to expand your videoconferencing setup to achieve many of the broadcast-studio effects. Requirements: Space, lens, and light. ### Space: The remainder of this guide assumes that you have a room or a section in a room that is 8 feet long, 4 feet wide, and 9 feet tall. Every inch is required. Stand during the video conference or sit on a tall stool. ### Lens: The actual camera sensor megapixels is not important anymore. What is important is that you have camera with a mechanically movable lens, and a depth of field that is more shallow than the typical webcam. The key is to differentiate your appearance on screen from nearly all 'webcams'. ### Light: Two softboxes with LED's. They need to be positionable far from the camera, on their own tripods. Everything below here is additional, if you do the above three you will differentiate your videoconference from 95% of other participants. ## Hardware setup ### Total cost If you include the computer, monitor, everything: $1750 If you include just what was purchased new: $843 ### Computer. This entire guide was developed on a 2013-era Lenovo laptop with an i5 at 1.6ghz. It works fine for videoconferencing. It gets hot, but it does work for hours on end with no issues. This computer cost 700$ in 2014. ### Video Components. <pre> $250 Canon VIXIA HF R800 setup. Comes with all cables needed out of the box. https://www.walmart.com/ip/Canon-VIXIA-HF-R800-Camcorder-Black/600185698?wmlspartner=wlpa&selectedSellerId=0 Settings changed from default: Home->Display onscreen markers: level grey output onscreen markers: off demo mode: off Zoom speed static, not dynamic. Shooting mode: highlight priority. $107 Elgato Cam Link 4K — Broadcast Live, Record via DSLR, Camcorder, USB 3.0 https://www.amazon.com/gp/product/B07K3FN5MR/ $140 Computer Monitor - the monitor used here is a 11 year old samsung display. It's completely fine once the backlight warms up, again for videoconferencing. Any newer full-hd display will be fine as long as it has a vesa mount. </pre> ### Audio Components. <pre> Used in wired and wireless configuration: $12 Greyghost Single Earbud, Earphone, 3.5mm Monaural Hollow Air Tube Wired Headphone https://www.amazon.com/gp/product/B07F7SW7ZZ/ Optional Wireless components. These can be more trouble than they are worth, but if you can make them worth it's an order of magnitude cheaper than a 'pro-grade' wireless setup: $65 Alvoxcon USB lavalier Mic System https://www.amazon.com/gp/product/B08DV5NJJM/ $13 Clip-Type Bluetooth 4.2 Transmitter and Receiver -2-in-1 Wireless 3.5mm Adapter, https://www.amazon.com/gp/product/B07YG13BPR/ Preferred wired setup. These components may not be necessary for your configuration depending on the hardware that came with your computer. This is a dead simple, low cost wired setup that is highly recommended over fighting the wireless configs. 14$ USB sound card with mute button https://www.amazon.com/gp/product/B08LPBW877 $6 USB 2.0 extension cord https://www.amazon.com/gp/product/B001MSU1FS $5 3.5mm extension cord https://www.amazon.com/gp/product/B00RXNUXGS/ </pre> ### Furniture and Lighting <pre> $168 DEVAISE Adjustable Height Standing Desk, 47 inch Sit to Stand Up Desk Workstaion with Crank Handle for Office Home, White https://www.amazon.com/gp/product/B07QVLBNJH/ $30 11" Adjustable Heavy Duty Robust Magic Arm https://www.amazon.com/gp/product/B07CTFZSXZ/ Note that this requires operator skill, but once you learn how to use it it's exactly as the reviews describe. 150$ MOUNTDOG Photography Lighting Kit,6.6X 10ft Backdrop Stand System and 900W 6400K LED Bulbs Softbox and Umbrellas Continuous Lighting Kit for Photo Video Shooting,etc. https://www.amazon.com/gp/product/B08FMGDTR1/ The umbrella lights are not required. The various stands can be repurposed based on your existing hardware. $40 Insignia monitor mount with arm: https://www.bestbuy.com/site/insignia-monitor-mount-silver-and-black/4374500.p?skuId=4374500 </pre> ### Miscellaneous <pre> $14 3 pack 1" inch x 60yd STIKK White Painters Tape 14 Day Easy Removal Trim Edge Finishing Decorative Marking Masking Tape (.94 IN 24MM) https://www.amazon.com/gp/product/B07SFLPX1G/ $9 Pro Tapes Pocket Gaff Tape 1 inch (24mm) x 6 Yards Length Black Matte. https://www.amazon.com/gp/product/B01EN7GZE0/ $14 Power strip $13 Extension cord </pre> [![Hardware Configuration](/images/obs_hardware.jpg)](/images/obs_hardware.jpg) ### Physical setup of camera. <pre> Turn the standing desk sideways, and mount the arm as far back as possible. Mount the camera as far back as possible. Even the 3 or 4 inches more distance shown in the picture by mounting the arm on the side of the table makes a big difference in the appearance of the image. An added bonus of this setup is that at the distances used, a teleprompter is not necessary. If you resize your teleconference window to be tiny and move it towards the top of the screen, it looks to the other participants like you are looking at them directly. </pre> ### Physical setup of lights. <pre> The primary light is mounted slightly offset from center, at 7.5 feet tall. In the picture shown the black tripod is wrapped in white tape which helps it blend into the background. The secondary light is mounted at eye level and placed at a 90 degree angle, approximately 6 feet away directly to the side of the subject. If you don't have that much room, place it as close as you need it and turn the power down. More on the detailed lighting configuration below in 'Green screen'. </pre> ### Green screen physical configuration <pre> The key here to a easy and good green screen experience is to select the 'White' setting on the provided LED's. The LED's provided with the MountDog lighting system are unlabelled. So the manufacturer is unknown. The remote control they come with has three buttons, warm, cold and white. The 'white' setting looks closest to daylight and makes the green screen setup easiest. The lights themselves come with an incredibly useful feature of clicking on and off the light cycles through the color temperature modes, so you won't need the remote, unless you want to adjust the power. Physical green screen setup is possible on the provided tripods. It's unstable even with a variety of workarounds, and will move significantly. The best approach is to keep the top bar, and mount the bar directly on the wall. You can use the clamps at the top to attach the other color cloths, but in practice only the green cloth is necessary. Wrinkles and waves make almost no difference and will be smoothed out by the correct lighting configuration. </pre> ### Audio setup <pre> Wired setup: This is the preferred mode, as wireless really isn't necessary for almost all videoconferences. It also has a variety of issues that need to be compensated for (see below). All you 'must' have for this to work and look and sound better than 95% of videoconferences is two 3.5mm extension cables. Plug the microphone into one, then into your computer. Plug the headphone earpiece into the other than into your computer. Use the optional usb audio controller and extension cable to give you more manueverability and a single microphone mute button. Wireless setup: Microphone: position the wireless usb dongle on a port where you can see it. This allows you to reach down and push the 'power off' button on the wireless portion, and you'll see the USB dongle lights turn off indicating you're on mute. Major issues: Using the combination of bluetooth transmitter for listening and 900mhz to usb for microphone works 'sometimes'. On some computers it works out of the box with zero issues. On others it will have bluetooth pairing issues and when it does pair, cause incredible audio and video delays. The workaround is just to use wired. In practice noone will see the wires, and you won't be moving around that much anyways. </pre> ### Software setup <pre> If you are on windows, install the most recent version of OBS studio, then skip to the 'start obs' section below. dnf install snapd snap install obs-studio If you get a message about 'too early/device not seeded', wait 3 seconds and try again. snap connect obs-studio:alsa snap connect obs-studio:audio-record snap connect obs-studio:avahi-control snap connect obs-studio:camera snap connect obs-studio:jack1 snap connect obs-studio:kernel-module-observe dnf copr enable sentry/v4l2loopback dnf install v4l2ucp v4l2loopback echo "options v4l2loopback devices=1 video_nr=13 card_label='OBS_Virtual_Camera' exclusive_caps=1" | sudo tee /etc/modprobe.d/v4l2loopback.conf echo "v4l2loopback" | sudo tee /etc/modules-load.d/v4l2loopback.conf modprobe -r v4l2loopback modprobe v4l2loopback devices=1 video_nr=13 card_label='OBS_Virtual_Camera' exclusive_caps=1 reboot Install the fonts from this repo: https://github.com/Cordince/OBS-Studio-Setup into: /usr/share/fonts/proxima-nova-fonts. Start obs. When it starts for the first time, choose 'i will only be using the virtual camera'. Change the output settings to be HD (960x540), with a FPS of 10. This is for video conferencing, so noone will be able to tell the difference and produces much less load on your system. At this point, you can clone this repo, and change the file locations with a text editor. Then import the scene collection into obs-studio, and everything should be setup correctly. Continue on for details on how it was built. This repo contains the scene collection: https://github.com/Cordince/OBS-Studio-Setup </pre> ## Computing system configuration <pre> Optional, but enables fast power on to dedicated videoconferencing system: Install Fedora Core Mate 33 workstation. Make sure to not encrypt the data. After login, with network connected: dnf -y update hostnamectl set-hostname studio systemctl enable sshd systemctl start sshd reboot As root, edit /etc/lightdm/lightdm.conf Under the 'Seat:' section, add the lines: autologin-user=your_username autologin-user-timeout=0 System -> Preferences -> Look and Feel Set screensaver to not enable, do not lock when idle. 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 dnf update -y reboot Set static ip address in network configuration Change the startup config to auto start obs with virtualcamera enabled. Add a startup of chrome, delayed 30 seconds so obs studio has time to start. </pre> ## Green screen OBS configuration <pre> The settings described below are all included in the default configuration OBS file here: https://github.com/Cordince/OBS-Studio-Setup Create a scene, call it External Camera. Add a video capture source for the camlink device, name it camlink. Choose 1920x1080 as the source resolution. Click filters. Add the chromakey. If you're using the lighting setup described above, the default settings are nearly perfect. You may need to turn the similarity metric up slightly. Use the arrow keys and nudge it up 1-3 levels as needed. If you need to adjust for different lighting temperatures, choose ChromaKey, then move off the screen. Select a custom color, then pick from screen. Choose the green in the middle of the window behind where the subject would be. Then adjust the similarity metric down. Then add a color correction filter to bring back some of the color. The results here are not as good as just using the 'white' color temperature lights with default chromakey and no color correction. </pre> ### Lobby videos <pre> Use pexels and pixabay, and search for abstract patterns, geometrical, and lobby videos, etc. Or just use the versions included in this repo: Loading a 4k video will seriously slow down your system. You will not need that resolution for videconferencing. HD resolution (960x540) works fine and is indescernible from anything higher on most peoples phones and computers. If you have a lobby video that is larger than HD, scale it down with: ffmpeg -i 4k_lobby.mp4 -filter:v scale=960:-1 hd_lobby.mp4 Matching color schemes can be performed by adjusting curves. Use ffplay for previewing. Make a video much bluer: ffplay -i hd_lobby.mp4 -vf curves=blue='0.3/0.3 1/1' Make a video de-saturated: ffplay -i hd_lobby.mp4 -vf eq=brightness=0:saturation=0.8 When you are satisfied, replace ffplay with ffmpeg: ffmpeg -i hd_lobby.mp4 -vf eq=brightness=0:saturation=0.8 hd_lobby_gray.mp4 Another alternative that works just as well is applying the filters in OBS studio directly. Make sure you resize the videos first. </pre> ## Work in Progress... ### PIP Configuration <pre> </pre> ### Studio Mode <pre> </pre> ### Lower thirds animated displays <pre> </pre> ### Lower thirds animated displays <pre> </pre> ### Using phone as mute button, scene switcher. <pre> </pre> ### BRB type scenes <pre> With a single click it shows a 'brb' image or video, and mutes the audio microphone. Also a different setting that is 'video muted' where you can hear and be heard but your camera is off for adjustments without it looking like you are gone. </pre> ### OBS integration of sound into the stream. <pre> </pre> ### Try a phone as a secondary camera. <pre> This is about giving a differentiated experience, and if you use NDI to feed the camera image back into the presentation at a different angle when you do different demos, talk about different things, share a screen, etc. Or even if it just changes automatically and you shift your eyeleline, that would be a huge differentiator. </pre> ### Try shotgun mike mounted to camera or direct to computer. <pre> </pre> ### Try level 2 configuration. <pre> Level 1 is the self contained setup here. Level 2 is you go back to wireless, then detach the entire monitor and camera stack and put it on the other side of the room. Then you get the much further focal distance setup in place. So it really looks like a studio, and you have your laptop on the desk so you can see the conference, etc. </pre> ### Try level 3 configuration. <pre> Dolly moves of the camera. The ultimate version of this is simulating a person behind the camera. Where it tracks the person and adjusts focus and pan/tilt/zoom in a way that is much more organic than the auto-zoom tracking systems. Something like piston translators on a rack that move the camera, or actuators that move a tripod head, organically. And on top that, the whole thing moves on a translation stage or a rolling pedestal. </pre> <file_sep>/content/developerworks/os-mltihed.md Title: Distributed multihead support with Linux and Xdmx Date: 2006-03-28 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-mltihed Learn about the tools available to develop your own multiscreen configuration and physical layout to enhance your computing experience. You can use Linux® and Xdmx to create one contiguous desktop across multiple display devices attached to separate computers. Combine your available laptop and desktop computers running Linux to create one large display for enhanced productivity. Explore large-scale display-wall setups and the creation of multihead setups without purchasing graphics cards. <file_sep>/content/developerworks/l-knockage.md Title: Knock based commands for linux laptops Date: 2006-06-25 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: l-knockage For the first time, you can hit your computer and get a meaningful response! Using Linux and the Hard Drive Active Protection System (HDAPS) kernel drivers, you can access the embedded accelerometers on IBM and Lenovo ThinkPads, then process the accelerometer data to read specific sequences of "knocking" events -- literally rapping on the laptop case with your knuckles - and run commands based on those knocks. Give your computer a double tap to lock the screen, and knock in your secret code to unlock. Tap the display lid once to move your mp3 player to the next track -- the possibilities are endless. IBM developerWorks [Podcast](/files/podcasts/twodw-7-26-06.mp3 "Podcast") with [<NAME>](https://scottlaningham.com/ "<NAME>"). On [Youtube](https://www.youtube.com/watch?v=bvcKV3Tuc4g "youtube"). News article on [New Scientist]( https://www.newscientist.com/article/dn9650-opportunity-knocks-for-novel-laptop-control/ "newscientist.com"). [Slashdot discussion](https://slashdot.org/story/06/07/30/1710201/knock-some-commands-into-your-laptop "Slashdot discussion") if only for the e.a. poe homage. Among the Top 10 IT stores of the week at [cio.com](http://www.cio.com/article/2445176/staff-management/top-10-it-stories-of-the-week--aol-cuts-jobs--ibm-and-amd--net-neutrality.html "cio.com"). <file_sep>/content/posts/barbecue.md Title: Barbecue line scan camera tester Date: 2015-11-12 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/barbecue_thumbnail.gif Use a [DALSA framegrabber](https://www.teledynedalsa.com/imaging/products/fg/OR-X1C0-XLB00/) and Wasatch Photonics [Cobra](http://wasatchphotonics.com/product-category/optical-coherence-tomography/cobra-oct-spectrometer/) series of spectrometer to collect data on every gain and offset setting. Provide a portable csv data format and heatmap visualizations with cross-sections. Uses [guiqwt](https://pythonhosted.org/guiqwt/) and includes a custom build environment and instructions for [python xy](http://pythonxynews.blogspot.com/) Available on [GitHub](https://github.com/WasatchPhotonics/Barbecue) <file_sep>/content/developerworks/os-firefox-rotate-images.md Title: Rotate images in online mapping applications in Firefox Date: 2008-10-14 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-firefox-rotate-images Most online mapping applications assume that the desired view is always north at the top of the image. This article presents tools and code that show how to replace the map image with an inverted copy, where south is at the top. Using a Firefox extension and the Imager Perl module, each tile that comprises the full image is extracted, rotated, and placed back in the image at the appropriate spot. <file_sep>/content/posts/outsource_technical_cofounder.md Title: Outsource technical cofounder Date: 2023-03-10 Category: articles Tags: productivity Outsource your technical cofounder ----------------------------------------------------- Here's how to amplify your skills and create a psuedo co-founder using offshore talent. Maintain control of your software and free yourself from managing software dev teams. Use this approach to find talent with integrity and ability. Extend your runway or rapidly develop more features to enhance your customer discovery capabilities. Feature development through social marketing material ----------------------------------------------------- Build data-based graphs for social media postings, along with the code to integrate into the application. This gives you two benefits: 1. Content for marketing posts based on your actual user data. 2. Identification of software talent for integration of features into your application. The approach below focuses on upwork.com, but you can use any number of asymmetrical cost platforms. Task content ------------ <pre> Create a new post. Choose short term / part time work. -> Continue Title: Dashboard from csv. Job category: scripting and automation -> Continue Choose the skills: Dashboard Scripting Data Visualization PDF HTML Choose small project, less than 1 month. Intermediate experience Not part time to full time hire (contract only) Location: Worldwide Select eastern european countires: Bulgaria Poland Serbia Slovakia Slovenia Ukraine Yes, you want it from much lower to much higher than US rates. The next step will give you options. Choose 5-40 hours for the rate. How is this fair? As of Mar 2023, software devleopment rates nationwide are: US: 43$/hr Bulgaria: 50 Poland 40 Serbia 24 Slovakia: 19 Slovenia: 75 Ukrains: 32 For a technical cofounder these rates are the equivalent of 200-400 per hour. Paste the job description: Title: Dashboard from csv. Your creation of a dashboard style one page report in pdf generated from the following data. We also want the code used to create the report. Some examples of content that could be in the report: Total number of users. Users by domain. Total number of paying customers. Total number of free trial users. Total number of trial expired users. Total number of cancelled users. Average time since login. To reiterate, we would like a one-page PDF report that uses the data linked in the csv below. The code used to generate the report is required as well. For example, you might use weasyprint in python along with some hand specified html markup. This or any other technology you choose to generate the report is fine, with the following limitations: 1. Free, open source. 2. Single line execution to generate the report. Can you do this? If so, please respond with what your plan and how long it will take you to complete. Add an attachment that is an export of your current user list. Click Post job. Choose 'hire a single freelancer'. Fill our your company profile if not already done so. </pre> Talent selection ---------------- <pre> If you want to selectively invite candidates to the job, use the following rules: Search for candidates: Search for a keyword from the job description, such as "python dashboard" Set the filters to the following settings: Earned amount: 1K+ Job success: 90%+ Hourly rate: $10 and below Hourse billed: 100+ English Level: If this is required, use the tests, not the self-descriptions. The self-descriptions of native, fluent, etc. are not accurate. Freelancer type: Independent freelancer Location: Desired geography </pre> Expectations ------------ <pre> Approximately 24 hours later, you should have at least 15 responses. Open oldest proposal first. Your hiring candidates based on screen or qualification. Did they read the post or was it a form response? Read and tailored reply -> shortlist Form response -> do nothing Examples below of form responses include the following examples: 1. No indications they read the post whatsoever. 2. They at least read the post, and copied and pasted the requirements into their form response. </pre> ![Example Form 1](/images/outsource/Example_Form_1.png) ![Example Form 2](/images/outsource/Example_Form_2.png) <pre> Response below is from an individual which is really a firm. This is what you do not want as you will be managing the team yourself. You want to train yourself to create tiny technical tasks that can be executed quickly at tiny cost and integrated into your product, achieving technical cofounder speed. </pre> ![Example Bad result firm](/images/outsource/Example_bad_result_firm.png) <pre> Examples below of good responses: This is the outstanding level that typically arrives from one of the candidates, where they essentially do most of the work requested and post it as part of their response: </pre> ![Example Good_result_1](/images/outsource/Example_Good_result_1.png) ![Example Good_result_1](/images/outsource/Example_Good_result_1_powerbi.png) ![Example Good_result_1](/images/outsource/Example_Good_result_2.png) ![Example Good_result_1](/images/outsource/Example_of_realistic_proposal.png) <pre> Review the shortlist entries and hire. Remember the goal here is not perfect work, the goal is identification of talent and integrity. </pre> Follow up --------- <pre> +---------------------+ |Go to upwork.com | |Click messages |<---------------------------------------------------------------------------+ |Click oldest message | | +---------------------+ | | | | | v | +---------------------+ | |Review work products | | +---------------------+ | | | v | ********* ********* ********* | ** ** ** ** ** ** +---------------+ | ** Do the work ** NO ** Does the ** YES ** Did you ** YES |Apologize, and | | * products *---------->* contractor *----->* communicate *------>|post the fixed | | ** meet the ** ** have quest.?** ** badly? ** |communication. | | ** spec? ** ** ** ** ** +---------------+ | ********* ********* ********* | | | | +-----------------+ | | +------------+ | NO |Rephrase the task| | | | +-------------> |requirements | | | | +-----------------+ | | v | | | +-----------------+ v | | |Degrade contractor +------------------+ | | |assesment | |Degrade contractor| -+ | +-----------------+ |assesment | v +------------------+ +--------------------+ | Improve contractor | | assesment | +--------------------+ | | v ********* ** ** ** Is the work ** NO * complete? *------ ** ** ** ** ********* | | v ********* ********* +-----------------+ ** ** +--------------------+ ** ** | Click Jobs | ** Did they ** YES | Improve contractor | ** Pay ** | Click job title |-------->* stay within *----->| assesment |--------->* contractor * | View contract | ** time budget?** +--------------------+ ** ** +-----------------+ ** ** ** ** ********* ********* | NO +------------------+ +-------------->|Degrade contractor| |assesment | +------------------+ </pre> Evaluation ---------- <pre> Make sure the instructions can be followed to run the report generation tool as required in the job posting. </pre> Integration ----------- <pre> Now that you have identified some talent to work with, send messages like that shown below. Make sure to send these directly to them, and not to everyone on upwork. "We'd love to integrate the dashboard creation into our main project. Can I send you some requirements and see what you think? Thanks." </pre> <file_sep>/content/posts/calibration_report.md Title: Calibration Report Generator Date: 2015-11-09 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/calibration_report_thumbnail.gif Web service to create calibration reports for wasatch photonics spectrometers. Use a responsive web form to accept a serial number, calibration coefficients and (optional) product imagery. Create a PDF document and graphical thumbnail, store forever. Live demo available at [waspho.com](http://waspho.com:8081/). This is used by the [CookBook](http://waspho.com) spectrometer tracking system. This was the first system created as part of the microwave/cookbook update. Uses travis and coveralls for continuous integration testing. Deployed on a [Digital Ocean Droplet](https://www.digitalocean.com/) Available on [GitHub](https://github.com/WasatchPhotonics/CalibrationReport) <file_sep>/content/posts/wasatch_linegrab.md Title: LineGrab - Visualize single lines of data from a variety of cameras. Date: 2015-11-19 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/linegrab_thumbnail.gif Manufacturing and alignment of spectrometers requires line scan visualization of camera output. Many vendors provide bare-bones or non existent line graphs. LineGrab uses a variety of communication techniques to provide full-screen line graph visualizations. These are critical for the precise alignment of spectrometers. See the [WasatchCameraLink](https://github.com/nharringtonwasatch/WasatchCameraLink) repository for a list of currently supported cameras. Available on [GitHub](https://github.com/WasatchPhotonics/LineGrab) <file_sep>/content/posts/fastpm100.md Title: FastPM100 - High speed acquisition and visualization of ThorLabs PM100 power meter readings Date: 2016-03-21 Category: articles thumbnail_image: /images/wasatch-images/fastpm100_thumbnail.gif Visualize much higher speed laser power meter readings than the [ThorLabs Optical power meter](https://www.thorlabs.com/software_pages/ViewSoftwarePage.cfm?Code=PM100x) software. Use [zmq](http://zeromq.org) and multiple visualization modes to show instantaneous and long term laser power meter trends. This is used at [Wasatch Photonics](http://wasatchphotonics.com) for laser output power stability of our laser can diodes. It's also useful for power on visualizations of the various mode hops and other instabilities as the laser transitions through various temperatures and feedback loops. We use this in concert with a [BoardTester](https://github.com/WasatchPhotonics/BoardTester) script to create a long term data logging setup that also permits high resolution instantaneous visualization. FastPM100 is one of the first applications that uses the [PySideApp](https://github.com/WasatchPhotonics/PySideApp) starter project. This is essential for high speed visualization and lag-free hardware acquisitions. Available on [GitHub](https://github.com/WasatchPhotonics/FastPM100) <file_sep>/content/developerworks/os-timedep.md Title: Visualizing time-dependent data with distortion portals Date: 2008-06-11 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-timedep Create an SDL-enabled application that allows you to create distortion portals in sequential image frames to explore the relationship of data sets through time. This article demonstrates code and techniques to create "animated distortion portals" in the data to provide time-dependent visualizations of various parts of the image. Additionally, certain aspects of the code are presented that allow for effective visualization on slower-computing platforms without sacrificing usefulness. Demonstration [video](https://www.youtube.com/watch?v=ot60Us-9jfY) at youtube.com <file_sep>/content/developerworks/os-vectorldap.md Title: Search structured LDAP data with a vector-space engine. Date: 2007-09-18 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-vectorldap Use Perl and a vector-space search engine to search and display records from your Lightweight Directory Access Protocol (LDAP) database. Use inflected letters and numbers to create a useful vector space from structured LDAP data. Compensate for typographical and spelling errors automatically while showing the most appropriate match for any query entered. [IBM developerWorks podcast](/files/podcasts/twodw102307.mp3) with [<NAME>ham](http://scottlaningham.com). <file_sep>/content/patents/patent_7,865,253.md Title: Protecting electronic devices from percussive impacts Date: 2011-01-04 template: patent patent_number: 7,865,253 A system and method detects low grade physical motions of an electronic device, such as a laptop computer, and takes protective measures if the physical motions match a pre-specified physical motion pattern. The pre-specified physical motion pattern may have been selected as a pattern which, if left alone, could cause cumulative damage to the electronic device. Alternatively, the pre-specified motion pattern may have been selected as a pattern which tended to indicate that more aggressive and abrupt movements would be forthcoming. The system and method further detects sustained motion (such as in a laptop bag) such that the laptop may shut-off so that the laptop does not overheat or get damaged. <file_sep>/content/pages/standing_invitation.md Title: Standing Invitation One of the main motivations for me in running this site is to connect with fellow (aspiring) entrepreneurs. **If you want to talk about startups, I want to talk to you**. Just send me a message here: <EMAIL> I will reply to virtually anything you send me. If you happen to be in the Central North Carolina, USA area, I would also love to meet up. Just send me an email. The first coffee (or pizza) is on me! I got the idea for this invitation from [Michael Herrman](http://www.herrmann.io/standing-invitation.html). If you are interested in running a (software) business online, I highly recommend you check out his [website](http://www.herrmann.io/). <file_sep>/README.md <NAME> personal static site using pelican. ### Setup and configuration Make sure you edit files in content/ not in the root. Clone this repository into: ~/projects/NathanHarrington.github.io Clone the pelican-themes fork: git clone https://github.com/NathanHarrington/pelican-themes ~/projects/pelican-themes cd ~/projects/pelican-themes git checkout personal-bootstrap3 # Setup environment with pipenv pipenv install # In one window, setup auto-reloader of content (but not .conf files) cd ~/projects/NathanHarrington.github.io pipenv run pelican -lr --autoreload --theme ../pelican-themes/personal-bootstrap3/ --output ./ ### CNAMEs, Aliases and branches This is a github user page. Therefore the live content is in the master branch. The URL is NathanHarrington.github.io CNAME has to be in the root of the repository, it has to contain the domain name: nathanharrington.info Create two A records that point to the github IP addresses: dig nathanharrington.info +nostats +nocmd +nocomments ; <<>> DiG 9.10.3-RedHat-9.10.3-1.fc23 <<>> nathanharrington.info +nostats +nocmd +nocomments ;; global options: +cmd ;nathanharrington.info. IN A nathanharrington.info. 2979 IN A 172.16.58.3 nathanharrington.info. 2979 IN A 192.168.3.11 ### Push to a github user page Make sure you edit files in content/posts/ not in posts/ ! pipenv run pelican -lr --autoreload --theme ../pelican-themes/personal-bootstrap3/ --output ./ (Test on localhost:8000, verify everything looks fine) Add all of the new files for a post: git add content/posts/* git add content/images/* git add posts/* git add images/* git add tags/* (essentially anything in root, if you are disciplined, you should be able to do git add ./ ) git commit -a -m "Documentation log message" git push origin master ### Convert an animated gif into a smaller animated gif convert source.gif -coalesce temp.gif convert -resize 100% temp.gif -resize 15% small.gif ### Generate the thumbnails by: cd thumbnails pwd # Make sure you are in the thumbnails directory! cp ../*.jpg . morgrify -resize 200x200 *.jpg <file_sep>/content/developerworks/os-graphviz.md Title: Explore relationships among web pages visually Date: 2007-05-15 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-graphviz Explore relationships among Web pages visually, The Graphviz program from AT&T Research and others is a fantastic tool for automating the visualization of complicated link sets. This article shows how to combine the Graphviz tool set with Web-page thumbnail generators to create new ways of visualizing any Web page's link structures. You can use these techniques and descriptions to refine your display logic, and create directed and undirected Graphviz charts to enhance your understanding of organizational, software, and other complex linked data sets. <file_sep>/content/posts/wasatch_boardtester.md Title: BoardTester - collect data with automated hardware power cycling Date: 2016-05-11 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/boardtester_thumbnail.png Use the techniques from [Phidgeter](https://github.com/WasatchPhotonics/Phidgeter) and the [Barbecue](https://github.com/WasatchPhotonics/Barbecue) in an automated fashion. Perform thousands of power cycle events, and isolate issues with various software configurations and power requirements. This tool is used at [Wasatch](http://wasatchphotonics.com) for analysis of various hardware configurations on Optical Coherence Tomography systems. Available on [GitHub](https://github.com/WasatchPhotonics/BoardTester) <file_sep>/content/developerworks/os-perlgdplot.md Title: Custom cartographics with CAIDA's plot-latlong Date: 2007-04-10 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-perlgdplot Using world and custom U.S. maps, Perl, GD, and the Cooperative Association for Internet Data Analysis (CAIDA) plot-latlong tool, this article demonstrates how to create your own effective data visualizations in the spirit of Google maps and the U.S. national atlas. <file_sep>/content/developerworks/os-smart-monitors.md Title: Reduce your PC's power consumption through smart activity monitors Date: 2008-11-04 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-smart-monitors Monitor application usage, system attributes, and user activity to more effectively use the power-management systems of your laptop or desktop computer. This article provides tools and code to build on existing power-saving measures by monitoring your application-usage patterns. Use the techniques presented here to change your power settings based on the application in focus, user activity, and general system performance. Local cached text. IBM developerWorks [podcast](/files/podcasts/feature-110408.mp3) with [Scott Laningham](http://scottlaningham.com) <file_sep>/content/posts/learning_line_drawing.md Title: Learning line drawing for the business model canvas Date: 2017-09-18 Category: articles Tags: business model canvas There is deep value in hand drawing iconagraphy to provide the text *and* visualization communication method. The icons provided by strategyzer and others seem ill-suited for hand re-creation by developing artists. You don't need a set of sophisticated imagery and a skilled hand at communicating any and all concepts. You do need to have just the iconagraphy practiced for the components of the business model canvas so you can demonstrate the value of imagery. Spend time praticing outline drawn versions of the iconagraphy from the strategyzer business model canvas. Why is this required? Because the strategyzer Key Activities icon is: ![Key Activities Icon](/images/learning/learning_key_activities.jpg) And that shading in of the negative image around the check mark takes a long time and unusual skill to hand draw. An easier image to draw in the real life context of people waiting and watching is the simple check mark underneath. See the image below for the full outline imagery to practice: [![Key Activities Icon](/images/learning/thumbnails/learning_bmc_line_icons.jpg)](/images/learning/learning_bmc_line_icons.jpg) And here is a link for the vertically listed business model canvas components with space to practice the line drawings. Print this out from firefox [BMC Vertical for line art](/images/learning/business_model_canvas_top_to_bottom.png) When practicing, follow the core concepts from the [creativebloq guide]( http://www.creativebloq.com/illustration/how-draw-basic-shapes-31619534) that immediately improve the quality and repeatability of the line drawings: >Draw with the arm, not with the fingers. >Position the utensil like writing, but move the arm, don't articulate >the joints of the phalanges. >Pull the utensil. >Pre-visualize: pinpoint your start point, imagine the end point. >Pull your mark along the imagined path removing the pencil once it >reaches the end point. All that seems needed for this juncture is a basic level of skill and knowledge of what to draw. Don't try and make it up during the BMC generation, know ahead of time a series of line drawings that you have practiced. Use variations on what you know and have practiced for line drawing iconagraphy. The point is to visually communicate as it is more efficient at conveying the ideas. It doesn't have to be perfect, it just needs to be a good enough reproduction to facilitate understanding instead of causing people to ask "What is that supposed to be?". <file_sep>/content/posts/bubbler.md Title: The Bubbler has been re-created! Date: 2014-01-13 Category: articles Tags: wasatch photonics thumbnail_image: /images/bubbler_short_demo.gif The Bubbler has been re-created. Thank you Ryan and Allison for making it memorable. The original bubbler was based on [os-viseffects](/posts/real-time-visual-effects.html). Game design: Get the highest score possible in the time allotted. Every gameplay decision is based on the idea that most kids enjoying gaming the system as much as the gameplay itself. That's why the mess bubbles time out. That's why it's harder to get a high score by just leaving your arm visible to the window. Game scores are not recorded anywhere to encourage spectators to track the highest score, as well as establishing classes of ability - if you're a huge adult, it's harder to avoid the bubbles - but it's easier to hit the blue ones too. View the full [demonstration video](/files/videos/bubbler_long_demo.mp4) View the original source code on [github](https://github.com/NathanHarrington/BubblerHope) <file_sep>/content/posts/phidgeter.md Title: Phidgeter - logging and convenience functions for Phidgets Date: 2016-02-08 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/phidgeter_thumbnail.gif [Phidgets](http://www.phidgets.com/products.php?category=9) are truly exceptional. Actual out of the box usefulness with their [software](http://www.phidgets.com/docs/Software_Overview). The python interface can be difficult to use when compared to other API's. Phidgeter provides logging, network, display and convenience functions for Phidgets. Use it with [BlueGraph](https://github.com/WasatchPhotonics/BlueGraph) for example, for more straightforward data visualization. Here's some examples with Phidgeter: from phidgeter import relay phd_relay = relay.Relay() phd_relay.one_toggle() Emit data from a Phidget IR sensor on the command line: import time from phidgeter.temperature import IRSensor if __name__ == "__main__": ir_temp = IRSensor() ir_temp.open_phidget() while(1): print ir_temp.get_temperature() time.sleep(0.10) Available on [GitHub](https://github.com/WasatchPhotonics/Phidgeter) <file_sep>/archives.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>Archives - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="<NAME>" /> <!-- Open Graph tags --> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="website"/> <meta property="og:title" content="<NAME>"/> <meta property="og:url" content=""/> <meta property="og:description" content="<NAME>"/> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li > <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <h1>Archives for Nathan Harrington</h1> <div id="archives"> <p> <span class="categories-timestamp"><time datetime="2023-03-10T00:00:00-05:00">Fri 10 March 2023</time></span> <a href="/posts/outsource-technical-cofounder.html">Outsource technical cofounder</a> </p> <p> <span class="categories-timestamp"><time datetime="2021-03-02T00:00:00-05:00">Tue 02 March 2021</time></span> <a href="/posts/obs-studio-home-setup.html">OBS Studio home setup</a> </p> <p> <span class="categories-timestamp"><time datetime="2018-05-30T00:00:00-04:00">Wed 30 May 2018</time></span> <a href="/posts/fedora-workstation-on-amazon-ec2.html">Fedora Workstation on Amazon EC2</a> </p> <p> <span class="categories-timestamp"><time datetime="2018-05-08T00:00:00-04:00">Tue 08 May 2018</time></span> <a href="/posts/darktable-image-processing-workflow.html">Darktable image processing workflow</a> </p> <p> <span class="categories-timestamp"><time datetime="2018-02-09T00:00:00-05:00">Fri 09 February 2018</time></span> <a href="/posts/amazon-free-tier-ssh-etc.html">Amazon Free Tier SSH etc.</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-12-13T00:00:00-05:00">Wed 13 December 2017</time></span> <a href="/posts/transformative-virtual-assistant-development.html">Transformative Virtual Assistant Development</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-10-25T00:00:00-04:00">Wed 25 October 2017</time></span> <a href="/posts/customer-discovery-interviews.html">Customer Discovery: Interviews</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-10-11T00:00:00-04:00">Wed 11 October 2017</time></span> <a href="/posts/stage-seven-test-assumptions-gather-data-gain-insight-repeat.html">Stage Seven: Test assumptions, gather data, gain insight, repeat</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-10-09T00:00:00-04:00">Mon 09 October 2017</time></span> <a href="/posts/stage-six-customer-discovery-and-product-market-fit.html">Stage Six: Customer discovery and product market fit</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-10-02T00:00:00-04:00">Mon 02 October 2017</time></span> <a href="/posts/stage-five-customer-segments.html">Stage Five: Customer Segments</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-25T00:00:00-04:00">Mon 25 September 2017</time></span> <a href="/posts/integrate-task-warrior-into-daily-workflow.html">Integrate Task Warrior into daily workflow</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-23T00:00:00-04:00">Sat 23 September 2017</time></span> <a href="/posts/bmfiddlecom-user-interface-modifications.html">bmfiddle.com user interface modifications</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-23T00:00:00-04:00">Sat 23 September 2017</time></span> <a href="/posts/music-for-working.html">Music for working</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-22T00:00:00-04:00">Fri 22 September 2017</time></span> <a href="/posts/stage-four-value-propositions.html">Stage Four: Value Propositions</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-18T00:00:00-04:00">Mon 18 September 2017</time></span> <a href="/posts/learning-line-drawing-for-the-business-model-canvas.html">Learning line drawing for the business model canvas</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-17T00:00:00-04:00">Sun 17 September 2017</time></span> <a href="/posts/stage-three-meta-business-model-canvas.html">Stage Three: Meta-Business Model Canvas.</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-16T00:00:00-04:00">Sat 16 September 2017</time></span> <a href="/posts/stage-two-what-used-to-be-done-what-we-now-know.html">Stage Two: What used to be done, what we now know.</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-15T00:00:00-04:00">Fri 15 September 2017</time></span> <a href="/posts/what-are-the-tactics-to-learn-this-material.html">What are the tactics to learn this material?</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-09-14T00:00:00-04:00">Thu 14 September 2017</time></span> <a href="/posts/notes-on-transformational-learning.html">Notes on transformational learning</a> </p> <p> <span class="categories-timestamp"><time datetime="2017-08-21T00:00:00-04:00">Mon 21 August 2017</time></span> <a href="/posts/innosetup-and-manifest-files-for-hidpi-displays.html">Innosetup and manifest files for HiDPI displays</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-12-21T00:00:00-05:00">Wed 21 December 2016</time></span> <a href="/posts/libusb-backends-using-pyinstaller-and-appveyor.html">LibUsb backends using pyinstaller and appveyor</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-12-20T00:00:00-05:00">Tue 20 December 2016</time></span> <a href="/posts/svg-icons-in-pyside-on-windows-7.html">SVG icons in PySide on Windows 7</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-12-12T00:00:00-05:00">Mon 12 December 2016</time></span> <a href="/posts/gtx-960-with-fedora-core-24.html">GTX 960 with Fedora Core 24</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-12-08T00:00:00-05:00">Thu 08 December 2016</time></span> <a href="/posts/pyinstaller-and-filenames-requiring-py-extensions-on-appveyor.html">Pyinstaller and filenames requiring .py extensions, on appveyor</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-12-01T00:00:00-05:00">Thu 01 December 2016</time></span> <a href="/posts/long-term-testing-of-windows-software-in-virtualbox.html">Long term testing of windows software in virtualbox</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-10-27T00:00:00-04:00">Thu 27 October 2016</time></span> <a href="/posts/gource-visualizations-of-source-code-repositories.html">Gource visualizations of source code repositories</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-10-17T00:00:00-04:00">Mon 17 October 2016</time></span> <a href="/posts/signing-drivers-windows-10-and-cypress-fx2fx3-usb.html">Signing Drivers - Windows 10 and Cypress FX2/FX3 USB</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-10-17T00:00:00-04:00">Mon 17 October 2016</time></span> <a href="/posts/work-log-recording-of-software-work-at-wasatch-photonics.html">Work log - Recording of software work at Wasatch Photonics</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-05-19T00:00:00-04:00">Thu 19 May 2016</time></span> <a href="/posts/microangio-demonstration-interface-for-the-microangio-ux-project.html">MicroAngio - Demonstration interface for the MicroAngio UX project.</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-05-11T00:00:00-04:00">Wed 11 May 2016</time></span> <a href="/posts/boardtester-collect-data-with-automated-hardware-power-cycling.html">BoardTester - collect data with automated hardware power cycling</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-04-26T00:00:00-04:00">Tue 26 April 2016</time></span> <a href="/posts/pysideapp-minimal-application-demonstrating-core-features-for-deployable-applications.html">PySideApp - Minimal application demonstrating core features for deployable applications</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-04-13T00:00:00-04:00">Wed 13 April 2016</time></span> <a href="/posts/cookbook-web-application-to-display-wasatch-photonics-device-information-and-calibration-reports.html">CookBook - Web application to display Wasatch Photonics device information and calibration reports.</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-04-08T00:00:00-04:00">Fri 08 April 2016</time></span> <a href="/posts/wasatchusb-bare-bones-usb-communication-with-wasatch-devices.html">WasatchUSB - bare bones USB communication with wasatch devices</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-03-21T00:00:00-04:00">Mon 21 March 2016</time></span> <a href="/posts/fastpm100-high-speed-acquisition-and-visualization-of-thorlabs-pm100-power-meter-readings.html">FastPM100 - High speed acquisition and visualization of ThorLabs PM100 power meter readings</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-02-08T00:00:00-05:00">Mon 08 February 2016</time></span> <a href="/posts/phidgeter-logging-and-convenience-functions-for-phidgets.html">Phidgeter - logging and convenience functions for Phidgets</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-01-18T00:00:00-05:00">Mon 18 January 2016</time></span> <a href="/posts/i3locksvg-branded-unlock-screens-on-linux.html">i3locksvg - branded unlock screens on linux</a> </p> <p> <span class="categories-timestamp"><time datetime="2016-01-04T00:00:00-05:00">Mon 04 January 2016</time></span> <a href="/posts/wasatchcameralink-bare-bones-communication-with-dalsa-sapera.html">WasatchCameraLink - Bare bones communication with DALSA sapera</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-12-11T00:00:00-05:00">Fri 11 December 2015</time></span> <a href="/posts/bluegraph-high-speed-graphing-and-logging-with-guiqwt-and-zmq-svg-blueness-in-pyqt.html">bluegraph - high speed graphing and logging with guiqwt and zmq. SVG blueness in pyqt</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-19T00:00:00-05:00">Thu 19 November 2015</time></span> <a href="/posts/linegrab-visualize-single-lines-of-data-from-a-variety-of-cameras.html">LineGrab - Visualize single lines of data from a variety of cameras.</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-12T00:00:00-05:00">Thu 12 November 2015</time></span> <a href="/posts/barbecue-line-scan-camera-tester.html">Barbecue line scan camera tester</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-12T00:00:00-05:00">Thu 12 November 2015</time></span> <a href="/posts/luminancelabel-animated-overlay-and-on-screen-luminance-measurements.html">LuminanceLabel - Animated overlay and on-screen luminance measurements</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-12T00:00:00-05:00">Thu 12 November 2015</time></span> <a href="/posts/pdfexploder-web-service-to-create-thumbnail-views-of-pdf-documents.html">PDFExploder - Web service to create thumbnail views of PDF documents</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-11T00:00:00-05:00">Wed 11 November 2015</time></span> <a href="/posts/qr-sticker-code-generator-for-ql-700.html">QR Sticker Code generator for QL-700</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-11-09T00:00:00-05:00">Mon 09 November 2015</time></span> <a href="/posts/calibration-report-generator.html">Calibration Report Generator</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-09-03T00:00:00-04:00">Thu 03 September 2015</time></span> <a href="/posts/analyzeiq-with-wasatch-photonics.html">AnalyzeIQ with Wasatch Photonics</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-08-17T00:00:00-04:00">Mon 17 August 2015</time></span> <a href="/posts/adapteva-parallella-screener-the-foreman.html">Adapteva Parallella Screener (The Foreman)</a> </p> <p> <span class="categories-timestamp"><time datetime="2015-05-27T00:00:00-04:00">Wed 27 May 2015</time></span> <a href="/posts/stay-humble-or-get-humbled.html">Stay humble, or get humbled.</a> </p> <p> <span class="categories-timestamp"><time datetime="2014-12-23T00:00:00-05:00">Tue 23 December 2014</time></span> <a href="/posts/vector-space-lightweight-directory-access-protocol-data-search.html">Vector Space Lightweight Directory Access Protocol Data Search</a> </p> <p> <span class="categories-timestamp"><time datetime="2014-01-13T00:00:00-05:00">Mon 13 January 2014</time></span> <a href="/posts/the-bubbler-has-been-re-created.html">The Bubbler has been re-created!</a> </p> <p> <span class="categories-timestamp"><time datetime="2013-11-19T00:00:00-05:00">Tue 19 November 2013</time></span> <a href="/posts/beyond-field-of-view-tracked-object-positional-indicators.html">Beyond Field-of-View Tracked Object Positional Indicators</a> </p> <p> <span class="categories-timestamp"><time datetime="2013-08-20T00:00:00-04:00">Tue 20 August 2013</time></span> <a href="/posts/automatic-announcer-voice-removal-from-a-sporting-event.html">Automatic announcer voice removal from a sporting event</a> </p> <p> <span class="categories-timestamp"><time datetime="2013-01-01T00:00:00-05:00">Tue 01 January 2013</time></span> <a href="/posts/visualization-interface-of-continuous-waveform-multi-speaker-identification.html">Visualization interface of continuous waveform multi-speaker identification</a> </p> <p> <span class="categories-timestamp"><time datetime="2012-06-26T00:00:00-04:00">Tue 26 June 2012</time></span> <a href="/posts/reducing-multipath-signal-degradation-effects-in-a-wireless-transmission-system.html">Reducing multipath signal degradation effects in a wireless transmission system</a> </p> <p> <span class="categories-timestamp"><time datetime="2012-05-08T00:00:00-04:00">Tue 08 May 2012</time></span> <a href="/posts/upper-troposphere-and-lower-stratosphere-wind-direction-speed-and-turbidity-monitoring-using-digital-imaging-and-motion-tracking.html">Upper troposphere and lower stratosphere wind direction, speed and turbidity monitoring using digital imaging and motion tracking</a> </p> <p> <span class="categories-timestamp"><time datetime="2012-03-20T00:00:00-04:00">Tue 20 March 2012</time></span> <a href="/posts/hybrid-ultrasonic-and-radio-frequency-identification-system-and-method.html">Hybrid ultrasonic and radio frequency identification system and method</a> </p> <p> <span class="categories-timestamp"><time datetime="2011-05-24T00:00:00-04:00">Tue 24 May 2011</time></span> <a href="/posts/autonomously-configuring-information-systems-to-support.html">Autonomously Configuring Information Systems to Support</a> </p> <p> <span class="categories-timestamp"><time datetime="2011-05-07T00:00:00-04:00">Sat 07 May 2011</time></span> <a href="/posts/automatically-generating-precipitation-proximity-notifications.html">Automatically generating precipitation proximity notifications</a> </p> <p> <span class="categories-timestamp"><time datetime="2011-01-18T00:00:00-05:00">Tue 18 January 2011</time></span> <a href="/posts/method-and-system-for-vehicle-mounted-infrared-wavelength-information-displays-for-traffic-camera-viewers.html">Method and system for vehicle mounted infrared wavelength information displays for traffic camera viewers</a> </p> <p> <span class="categories-timestamp"><time datetime="2011-01-04T00:00:00-05:00">Tue 04 January 2011</time></span> <a href="/posts/protecting-electronic-devices-from-percussive-impacts.html">Protecting electronic devices from percussive impacts</a> </p> <p> <span class="categories-timestamp"><time datetime="2010-04-06T00:00:00-04:00">Tue 06 April 2010</time></span> <a href="/posts/method-and-system-for-improving-driver-safety-and-situational-awareness.html">Method and system for improving driver safety and situational awareness</a> </p> <p> <span class="categories-timestamp"><time datetime="2009-06-09T00:00:00-04:00">Tue 09 June 2009</time></span> <a href="/posts/automotive-collision-detection-through-passive-radio-analysis.html">Automotive collision detection through passive radio analysis</a> </p> <p> <span class="categories-timestamp"><time datetime="2009-03-01T00:00:00-05:00">Sun 01 March 2009</time></span> <a href="/posts/ibm-history.html">IBM History</a> </p> <p> <span class="categories-timestamp"><time datetime="2009-03-01T00:00:00-05:00">Sun 01 March 2009</time></span> <a href="/posts/patents-at-ibm.html">Patents at IBM</a> </p> <p> <span class="categories-timestamp"><time datetime="2009-01-06T00:00:00-05:00">Tue 06 January 2009</time></span> <a href="/posts/social-networking-open-source-visualization-aids.html">Social-networking open source visualization aids</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-12-16T00:00:00-05:00">Tue 16 December 2008</time></span> <a href="/posts/how-to-ungrab-firefox-hotkeys-from-flash-players.html">How to ungrab Firefox hotkeys from Flash players</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-11-25T00:00:00-05:00">Tue 25 November 2008</time></span> <a href="/posts/expand-your-user-authentication-options-with-mouse-dynamics.html">Expand your user-authentication options with mouse dynamics</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-11-04T00:00:00-05:00">Tue 04 November 2008</time></span> <a href="/posts/reduce-your-pcs-power-consumption-through-smart-activity-monitors.html">Reduce your PC's power consumption through smart activity monitors</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-10-21T00:00:00-04:00">Tue 21 October 2008</time></span> <a href="/posts/shut-down-idle-computers-on-your-network-automatically.html">Shut down idle computers on your network automatically</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-10-14T00:00:00-04:00">Tue 14 October 2008</time></span> <a href="/posts/rotate-images-in-online-mapping-applications-in-firefox.html">Rotate images in online mapping applications in Firefox</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-10-07T00:00:00-04:00">Tue 07 October 2008</time></span> <a href="/posts/create-a-continuous-keystroke-dynamics-monitor-with-perl-and-xev.html">Create a continuous keystroke-dynamics monitor with Perl and xev</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-09-23T00:00:00-04:00">Tue 23 September 2008</time></span> <a href="/posts/creating-altitude-attribute-enhanced-image-overlay-maps-in-google-earth.html">Creating altitude attribute-enhanced image overlay maps in Google Earth</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-09-09T00:00:00-04:00">Tue 09 September 2008</time></span> <a href="/posts/improve-focus-tracking-indicators-across-multiple-monitors.html">Improve focus tracking indicators across multiple monitors</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-08-26T00:00:00-04:00">Tue 26 August 2008</time></span> <a href="/posts/create-time-availability-maps-with-perl-and-google-earth.html">Create time-availability maps with Perl and Google Earth</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-08-12T00:00:00-04:00">Tue 12 August 2008</time></span> <a href="/posts/beef-up-the-find-command-in-firefox.html">Beef up the Find command in Firefox</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-07-15T00:00:00-04:00">Tue 15 July 2008</time></span> <a href="/posts/integrate-encryption-into-google-calendar-with-firefox-extensions.html">Integrate encryption into Google Calendar with Firefox extensions</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-06-11T00:00:00-04:00">Wed 11 June 2008</time></span> <a href="/posts/visualizing-time-dependent-data-with-distortion-portals.html">Visualizing time-dependent data with distortion portals</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-06-03T00:00:00-04:00">Tue 03 June 2008</time></span> <a href="/posts/add-multitouch-gesture-support-to-a-touchpad-equipped-laptop.html">Add multitouch gesture support to a TouchPad-equipped laptop.</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-04-15T00:00:00-04:00">Tue 15 April 2008</time></span> <a href="/posts/identify-speakers-with-sndpeek.html">Identify speakers with sndpeek</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-03-18T00:00:00-04:00">Tue 18 March 2008</time></span> <a href="/posts/identify-and-verify-users-based-on-how-they-type.html">Identify and verify users based on how they type</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-03-11T00:00:00-04:00">Tue 11 March 2008</time></span> <a href="/posts/thinkpad-aerobics-rotate-and-shake-your-laptop-to-control-applications.html">ThinkPad aerobics: Rotate and shake your laptop to control applications.</a> </p> <p> <span class="categories-timestamp"><time datetime="2008-02-12T00:00:00-05:00">Tue 12 February 2008</time></span> <a href="/posts/take-your-thinkpad-out-for-a-walk-to-create-wireless-site-surveys.html">Take your ThinkPad out for a walk to create wireless site surveys.</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-12-04T00:00:00-05:00">Tue 04 December 2007</time></span> <a href="/posts/expand-your-text-entry-options-with-keystroke-dynamics.html">Expand your text entry options with keystroke dynamics</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-11-13T00:00:00-05:00">Tue 13 November 2007</time></span> <a href="/posts/create-automated-verbal-conversation-annotations.html">Create automated verbal conversation annotations</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-09-18T00:00:00-04:00">Tue 18 September 2007</time></span> <a href="/posts/search-structured-ldap-data-with-a-vector-space-engine.html">Search structured LDAP data with a vector-space engine.</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-08-28T00:00:00-04:00">Tue 28 August 2007</time></span> <a href="/posts/make-your-404-pages-smarter-with-metaphone-matching.html">Make your 404 pages smarter with metaphone matching.</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-08-14T00:00:00-04:00">Tue 14 August 2007</time></span> <a href="/posts/map-people-places-and-relationships-inside-a-building.html">Map people, places and relationships inside a building.</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-06-05T00:00:00-04:00">Tue 05 June 2007</time></span> <a href="/posts/precipitation-proximity-alerts-using-wsr-88d-radar-data.html">Precipitation proximity alerts using WSR-88D radar data.</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-05-15T00:00:00-04:00">Tue 15 May 2007</time></span> <a href="/posts/explore-relationships-among-web-pages-visually.html">Explore relationships among web pages visually</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-04-24T00:00:00-04:00">Tue 24 April 2007</time></span> <a href="/posts/create-custom-data-charting-tools-using-perl-and-gd.html">Create custom data charting tools using Perl and GD</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-04-10T00:00:00-04:00">Tue 10 April 2007</time></span> <a href="/posts/custom-cartographics-with-caidas-plot-latlong.html">Custom cartographics with CAIDA's plot-latlong</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-03-20T00:00:00-04:00">Tue 20 March 2007</time></span> <a href="/posts/user-perl-and-a-regular-expression-generation-to-search-and-display-ldap-data-part-2.html">User Perl and a regular-expression generation to search and display LDAP data (part 2)</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-02-20T00:00:00-05:00">Tue 20 February 2007</time></span> <a href="/posts/user-perl-and-a-regular-expression-generation-to-search-and-display-ldap-data-part-1.html">User Perl and a regular-expression generation to search and display LDAP data (part 1)</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-02-13T00:00:00-05:00">Tue 13 February 2007</time></span> <a href="/posts/create-fancy-on-screen-displays-with-ghosd-and-perl.html">Create fancy on-screen displays with Ghosd and Perl</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-01-23T00:00:00-05:00">Tue 23 January 2007</time></span> <a href="/posts/make-incoming-e-mail-play-custom-tunes.html">Make incoming e-mail play custom tunes</a> </p> <p> <span class="categories-timestamp"><time datetime="2007-01-09T00:00:00-05:00">Tue 09 January 2007</time></span> <a href="/posts/control-your-computer-with-tones-and-patterns.html">Control your computer with tones and patterns</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-11-14T00:00:00-05:00">Tue 14 November 2006</time></span> <a href="/posts/monitor-your-computing-environment-with-machine-generated-music.html">Monitor your computing environment with machine generated music</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-11-07T00:00:00-05:00">Tue 07 November 2006</time></span> <a href="/posts/frustration-communication-for-your-linux-laptop.html">Frustration communication for your linux laptop</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-07-11T00:00:00-04:00">Tue 11 July 2006</time></span> <a href="/posts/create-mosaic-movies-with-perl-imagemagick-and-mplayer.html">Create mosaic movies with Perl, ImageMagick and MPlayer</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-06-25T00:00:00-04:00">Sun 25 June 2006</time></span> <a href="/posts/knock-based-commands-for-linux-laptops.html">Knock based commands for linux laptops</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-03-28T00:00:00-05:00">Tue 28 March 2006</time></span> <a href="/posts/distributed-multihead-support-with-linux-and-xdmx.html">Distributed multihead support with Linux and Xdmx</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-01-24T00:00:00-05:00">Tue 24 January 2006</time></span> <a href="/posts/create-mosaic-images-with-perl-and-imagemagick.html">Create Mosaic images with Perl and ImageMagick</a> </p> <p> <span class="categories-timestamp"><time datetime="2006-01-17T00:00:00-05:00">Tue 17 January 2006</time></span> <a href="/posts/real-time-visual-effects.html">Real time visual effects</a> </p> </div> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/posts/stay-humble-or-get-humbled.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>Stay humble, or get humbled. - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="/posts/stay-humble-or-get-humbled.html"> <meta name="author" content="<NAME>" /> <meta name="keywords" content="jobs" /> <meta name="description" content="Stay humble, or get humbled. - Jocko Willink You can&#39;t find a job. You&#39;ve done all the postings, You&#39;ve done all the resume cleaning. You&#39;ve applied for dozens of what you thought were good fits. You had a seriously disappointing number of interviews. You&#39;ve done it for months straight, 8 hours …" /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="article"/> <meta property="og:title" content="Stay humble, or get humbled."/> <meta property="og:url" content="/posts/stay-humble-or-get-humbled.html"/> <meta property="og:description" content="Stay humble, or get humbled. - Jocko Willink You can&#39;t find a job. You&#39;ve done all the postings, You&#39;ve done all the resume cleaning. You&#39;ve applied for dozens of what you thought were good fits. You had a seriously disappointing number of interviews. You&#39;ve done it for months straight, 8 hours …"/> <meta property="article:published_time" content="2015-05-27" /> <meta property="article:section" content="articles" /> <meta property="article:tag" content="jobs" /> <meta property="article:author" content="<NAME>" /> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li class="active"> <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <article> <div class="entry-content"> <p>Stay humble, or get humbled. - <a href="https://www.youtube.com/watch?v=q9IZaj-v33o"><NAME></a></p> <p>You can't find a job. You've done all the postings, You've done all the resume cleaning. You've applied for dozens of what you thought were good fits. You had a seriously disappointing number of interviews. You've done it for months straight, 8 hours per day.</p> <p>It's like there was a black hole all your work went into.</p> <p>You feel rejected. You feel terrible. You never want to apply for a job again.</p> <p>You need money. You need to pay bills. You are deeply afraid of the consequences of running out of money. The fear is paralyzing, leading to inaction where it matters and activity where it doesn't.</p> <p>Driven to humility, you started the search again. you googled: "example software engineer resume" without the quotes. The previous first link from uptowork.com used to describe a system to embrace with humility.</p> <p>Unfortunately they took down the article. It was truly superb, written by <NAME>. See this <a href="/content/files/uptowork_resume_guide.txt">repository</a> for text dump of the link circa 2018. It's fantastic. Here's the link to the current article for comparison. Don't use this, but keep it in mind as more of an example of what you can get lost in: <a href="https://uptowork.com/blog/software-engineer-resume">Uptowork software engineer resume</a></p> <p>Read the original article - feel the burden lift. Feel that yes you can do this, you have something to offer. </p> <p>Use the tool, make a first pass at a cut and paste replacement of the descriptions of the various entries. Get encouraged.</p> <p>Now you know the goal: </p> <h2>Create a system for testing resumes that work, in order to help others.</h2> <p>Write down the exact steps here. Create a lever you can pull. A series of instructions so well defined you can outsource the mechanics of the job search. The goal is not to find a job, the goal is to create a system for testing resumes that work.</p> <p>Make this a gift to your future self. For your children. For anyone who is hurting and has been paralyzed by fear of failure.</p> <p>You can't be afraid and grateful at the same time. Choose gratitude. Be grateful that you get this opportunity to write down the tactical and strategic details of your job search that will help others you love.</p> <p>Now you're starting to see all of the opportunities staring at you. They are truly aligned with your skills, you can legitimately have something to offer.</p> <p>You're excited again. Don't get bogged down in perfection. The ideal job is the one that takes the least amount of time. There is no job that is a substitue for your identity, there is no perfect fit that you must achieve.</p> <p>The instructions below are for the circa 2018 version of the zery resume builder, also known as uptowork resume builder. See the pictures folder for examples of the interface and what it could look like.</p> <pre> Here is the workflow and timelines to follow to keep your momentum going. Set timers according to the values below, and do this process, and you will break out of a rut and have a successful job search. 60 minutes: Make a single master resume that lists all of your accomplishments, using the templates from the uptowork articles. This is a first pass, not an exhaustive list. This is to learn the patterns of production - do not get bogged down in making it perfect. 15 minutes: Find one job that looks like a fit. Again, it doesn't have to be a perfect fit. The goal at this stage is action. 30 minutes: Make a single master cover letter based on the cover letter tool from uptowork: Cover letter software engineer linked below. 10 minutes: Follow their applicant submission process for the job. If it's an Applicant Tracking System like brassring, fill out everything as required. Don't get frustrated, just see it like waiting in line for a ride at disney world - it's worth it. If it's an email to <EMAIL>: Subject: (Job Title) - <NAME> Body: Copy and paste from the body of the cover letter. Attachments: Cover letter.pdf Resume.pdf 5 Minutes: Create a Tracking document with the columns listed below. Save the file as "Job Search with Gratitude.csv" Keywords Source Company Job Title Submitted Date Path (email, or ATS) Automated Response Human Response Phone Call Skills Test Online In Person Interview Offer Notes </pre> <p><a href="/content/files/uptowork_cover_letter_guide.txt">Cover letter</a> guide text example text dump. Newer version that's not as good available <a href="https://uptowork.com/blog/software-engineer-cover-letter-example">here</a></p> <p>Now as you look at other job opportunities, follow this pattern:</p> <p>Given a new job posting that looks like a fit:</p> <pre> 15 minutes: If it's not within daily driving distance, it needs to be a 7/10 fit or better to continue this process. You don't want to move, but you don't want to waste peoples time either. If it's a very high probably of fit, then you would at least seriously consider moving at the end of the process. Think deeply on your skills and experience. Read the job opportunity and decide which of your experiences apply. Add a resume item to the master resume that is a reflection of that interplay. If you're looking for ideas, look back through your online profile. Restore old backups. Re-immerse yourself in the sights and sounds and the benefits to the business that those activities provided. Create a single work experience item based on the project. For example, if you had a project that took a few months and exactly fit the requirements they are looking for, add that as a work experience item on the main resume. That is the success they want you to repeat, so give that a full 'experience' run down. They want to hear more details about exactly the work you have done that will help them. This will rapdily fill the master resume with a wide variety of projects that you have worked on, in detail. Add a start and end date in year, do not include months 30 minutes: Do something else not job search related - anything else. This is critical to break you out of the perfection-inaction loop. You'll be tempted to get on a roll and do a bunch of these without this break. Take the break! Constraints are important, both on the work itself and on your 'break's. Use the timers, take the breaks. 15 minutes: Clone the master resume. Change the resume title to have the job title in it Change the personal info->Profession to be the job title Change the summary to be tailored to the job description. Remove any non-relevant parts of the experience that are not tailored to this job. Choose just the work descriptions from each company that apply. Delete the rest. Update the skills section to match the job posting. Only spend 15 minutes on this. You must complete this in 15 minutes. Again, it's ok if its not perfect. The goal is to break out of the depression-induced inaction cycle. Download the PDF, save as: FirstName_LastName_JobTitle_Resume.pdf for example: Nathan_Harrington_Scientific_Applications_Resume.pdf 15 minutes: Clone the master cover letter. Change the cover letter title to be: Job Title Change the "profession" to match the job title. Update the contents of the cover letter to match the job description. Save as: FirstName_LastName_JobTitle_Cover_Letter.pdf for example: Nathan_Harrington_Process_Engineer_Cover_Letter.pdf 10 minutes: Follow their applicant submission process for the job. If it's an email to <EMAIL>: Subject: (Job Title) - <NAME> Body: Copy and paste from the body of the cover letter. Attachments: Cover letter.pdf Resume.pdf 1 Minute: Update the job tracking sheet </pre> <p>As you iterate through these steps, remember the goals:</p> <ol> <li>Collect data on which resumes work for which jobs.</li> <li>Create a system that you can operate that you can share with your future self, and anyone who needs it.</li> <li>Record the successes and the failures.</li> <li>Proceed in gratitude.</li> </ol> <h2>Does this work?</h2> <p>I followed the instructions above and had immediate positive results. The language and the layout updates to the resume as recommended by uptowork.com are a powerful differentiator. That's not the point. The point is to repeat this to collect enough data and get familiar with it. To write down the nuances of what it really takes to have good results. </p> <p>Never struggle again. Never fail at this again. </p> <p>Your professional training is not your identity. Fill yourself with gratefulness that you can use this process to help others. You're not struggling as punishment, it's training so you can help others.</p> <h2>Lessons Learned</h2> <p>They are looking for skills, and needs satisfied. Adapt yourself and your work experience to their needs. They are not hiring you, they are hiring for someone, anyone to fill the role. Put yourself in their position - they acquisition of talent is burdensome for most organizations, how can you meet their expectations?</p> <p>This took approximately 30 hours total effort, including the writing of these systems steps and refining the approach as documented above. The results were 3 excited recruiters playing the usual games of leading you on, and 3 rejections, 1 in-person interview and 13 black holes.</p> <p>The real point is humility works. </p> <p>1 out of 20 applications leading to an in-person interview is a decent rate. Being able to do 20 applications with a 5% success rate with each taking less than 25 minutes is hugely successful. Then you can do one week of this effort, for 8 hours per day, and that should lead to 5 in-person interviews.</p> <p>If you must attain a job. If you must re-engage with the risks of a workaholic prison, this is where to start. Write down what you do, write down what works with a focus on humility, on gratitude for knowing that you're in training to help others. </p> <p>Take ownership: It is your job to make this process a success for you and for everyone else.</p> <h2>Want More?</h2> <p>There are two books that will change your focus and give you the ability to see the employers needs first: Extreme Ownership by <NAME> and <NAME>, and The Irresistible Consultant's Guide to Winning Clients by <NAME>. Whatever context you are in, giving them what they actually want will help. </p> <div class="panel"> <div class="panel-body"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2015-05-27T00:00:00-04:00"> Wed 27 May 2015</time> </span> <span class="label label-default">Tags</span> <a href="/tag/jobs.html">jobs</a> </footer><!-- /.post-info --> </div> </div> </div> <!-- /.entry-content --> </article> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/content/developerworks/os-thinkpad.md Title: ThinkPad aerobics: Rotate and shake your laptop to control applications. Date: 2008-03-11 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-thinkpad Use synthetic X Window System events and embedded accelerometers to control applications by the movement of a laptop computer. Translate gestures, such as shaking, into mode-switching commands with detection algorithms to interact with applications in new ways. Develop tools to help build the next generation of interfaces that use accelerometers, such as applications for laptops and iPhones. [Demonstration video](https://www.youtube.com/watch?v=SIYNjl4wWKM) at youtube.com <file_sep>/content/pages/raffle.md Title: Steak and Cheesecake! Date: 2016-12-10 Category: About save_as: pages/raffle.html status: hidden Imagery to load onto ipad. [RuthsChris1](/images/raffle/ruths_chris_flyer1.jpg) [RuthsChris2](/images/raffle/ruths_chris_flyer2.jpg) [CheeseCakeFactory](/images/raffle/cheesecake_factory_flyer1.jpg) Raffle ticket template [TicketTemplate](/images/raffle/ticket_template.docx) <file_sep>/content/patents/patent_7,949,900.md Title: Autonomously Configuring Information Systems to Support Date: 2011-05-24 template: patent patent_number: 7,949,900 The Mission SoulPad may autonomously detect and configure components of the information system (e.g., displays, sensors, emitters, transceivers) to support the defined objectives of the Mission SoulPad. The Mission SoulPad may also identify malfunctioning components of the information system needing repair or replacement. Entire sensor and information display suites may be transitioned simply by moving the Mission SoulPad between available information systems. This ensures that mission critical information is consistently available regardless of the type of system the Mission SoulPad is connected to. <file_sep>/posts/ibm-history.html <!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <!-- ****** faviconit.com favicons ****** --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png"> <link rel="apple-touch-icon" href="/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- ****** faviconit.com favicons ****** --> <title>IBM History - <NAME></title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="/posts/ibm-history.html"> <meta name="author" content="<NAME>" /> <meta name="keywords" content="ibm" /> <meta name="description" content="Highlights from 8 years at IBM: 35 articles demonstrating new technologies 13 patents from RFID to cloud management 14 IBM Thanks peer recognition awards IBM Thinkplace Innovator Award 38 IBM Bravo/Ovation awards IBM Bravo award for technical achievement 19 Invention achievement awards, 5 patent plateau awards Selection to the …" /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:type" content="article"/> <meta property="og:title" content="IBM History"/> <meta property="og:url" content="/posts/ibm-history.html"/> <meta property="og:description" content="Highlights from 8 years at IBM: 35 articles demonstrating new technologies 13 patents from RFID to cloud management 14 IBM Thanks peer recognition awards IBM Thinkplace Innovator Award 38 IBM Bravo/Ovation awards IBM Bravo award for technical achievement 19 Invention achievement awards, 5 patent plateau awards Selection to the …"/> <meta property="article:published_time" content="2009-03-01" /> <meta property="article:section" content="articles" /> <meta property="article:tag" content="ibm" /> <meta property="article:author" content="<NAME>" /> <!-- Bootstrap --> <link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/> <link href="/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="/theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"> <NAME> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="/pages/about.html"> About </a></li> <li><a href="/pages/standing-invitation.html"> Standing Invitation </a></li> <!-- custom link to blog roll/articles --> <li><a href="/category/articles.html">Blog</a></li> <!-- Don't display categories on menu <li class="active"> <a href="/category/articles.html">Articles</a> </li> <li > <a href="/category/patents.html">Patents</a> </li> --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <article> <div class="entry-content"> <div style="padding-bottom:20px"> <img src="/images/ibm-images/wearableBBC_full.jpg"></img> </div> <div class="container"> <div class="row spaced_rows"> <div class="col-md-8"> Highlights from 8 years at IBM: <ul> <li>35 articles demonstrating new technologies</li> <li>13 patents from RFID to cloud management</li> <li>14 IBM Thanks peer recognition awards</li> <li>IBM Thinkplace Innovator Award</li> <li>38 IBM Bravo/Ovation awards</li> <li>IBM Bravo award for technical achievement</li> <li>19 Invention achievement awards, 5 patent plateau awards</li> <li>Selection to the Early Career Conference</li> </ul> </div> </div> </div> <div class="container"> <div class="row spaced_rows"> <div class="col-md-8"> My first opportunity with <a href="http://www.ibm.com">IBM</a> came as a Co-Op through <a href="http://www.rit.edu">R.I.T</a> with the Personal Computing Division Executive Briefing Center in Research Triangle Park. This was a fantastic opportunity where I helped administer PC's and Laptops representing all of IBM's consumer grade hardware. In addition to technical support, I had the opportunity to demonstrate the Wearable PC to customers. (Photo credit: BBC), more coverage at the <a href="http://news.bbc.co.uk/2/hi/science/nature/538072.stm">BBC</a> and <a href="http://domino.research.ibm.com/library/cyberdig.nsf/0/122b8399b43ea4348525701c0073005a?OpenDocument&Highlight=0,RC23622">IBM Research</a>. This was a great working experience with <a href="https://www.linkedin.com/in/david-laubscher-36639a2?"><NAME></a>, <a href="https://www.linkedin.com/in/jeffrey-walls-1ba0797?"><NAME></a>, <a href="https://www.linkedin.com/in/doug-baldwin-54019a?"><NAME></a> and many others. </div> </div> <div class="row spaced_rows"> <div class="col-md-8"> After the co-op and graduation from R.I.T. I began work with IBM as a full time 'regular' employee with Global Services. I worked closely with <a href="https://www.linkedin.com/in/levandos?"><NAME></a> doing Java programming. Among other projects, I worked on adding multi-threaded support to a data processing application. As part of the Customer Database team, I helped manage the batch processing data identification, matching and cleansing systems. This role focused on managing the Trillium software system on <a href="http://www-03.ibm.com/systems/power/software/aix/">AIX</a> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/fftool-screenshot.jpg"/> </div> <div class="col-md-6"> Managing tens of gigabytes of customer data in a flat file format with the existing tools was inadequate, so I created the 'Flat File Tool', which is useful for managing and visualizing large plain text files with no line delimiters. You can read more about the fftool program at [SourceForge](http://fftool.sourceforge.net/) </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/SametimePlus_logo_110.jpg"/> </div> <div class="col-md-6"> After a few months at IBM, I began work on an instant messaging client using the <a href="http://www-03.ibm.com/software/products/en/ibmsame">Sametime</a> SDK. I wanted many of the features available in other clients, but IBM's internal feature release schedule was not as fast as expected. I used my experiences with Windows Application development in college and at TM Technology to create Sametime Plus. As of March 2009, it still has features not available in the internal IBM Sametime client. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> There was a distinct need for a hardware and software environment local to our administrators instead of in [Ehningen, Germany](https://www.google.com/maps/place/IBM+Ehningen/@48.6502964,8.9364503,2062m/data=!3m1!1e3!4m8!1m2!2m1!1sibm+ehningen+data+center!3m4!1s0x0000000000000000:0x3b35d9ef4bbf614c!8m2!3d48.6519571!4d8.9467496). I created some specifications and acquired IBM-surplus AIX "medium-big iron" for faster processing of data. This project involved the setup of [7017-S80](http://www.coworthtechnologies.com/products/ibm/system-p/rs-6000/ibm-rs-6000-s80)'s and terabytes of storage in a raised floor data center environment. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Setting up systems, applications and database connections with the data quality analysis team gave me unique exposure to IBM's internal customer data. Beyond the challenges of duplication, entity relationship modelling and analysis methods, there were significant data quality issues. I worked with <NAME> and <NAME> to address many of these data quality issues. We created business rules, worked with the data custodians for each geography, and created actionable reports and a web application. IBM'ers worldwide could fix their own mis-entering of data, from typographical errors to business rule violations and placeholder entries. Moreover, violations could be tracked from an individual to mid management and corporate head level, leading to much greater visibility of data quality issues. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Visualizing terabytes of data can be a significant challenge. To address some of these issues I used surplus systems to create a minimalist 'display wall' of 9 monitors. This led to the beginnings of many IBM [developerWorks articles](http://www.ibm.com/developerworks/opensource/library?sort_by=&show_abstract=true&show_all=&search_flag=&contentarea_by=All+Zones&search_by=nathan+harrington&topic_by=-1&industry_by=-1&type_by=All+Types&ibm-search=Search). </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Various steps in the [Trillium](https://www.trilliumsoftware.com/) Batch process respond well to simple parallelization, as their is no shared data between the records. I used surplus systems gathered from the data center environment and custom Perl scripts to automatically divide the processed data amongst servers. Each server would run the parser process on its data, and send the information back to the central processing server. This simple approach reduced the processing time linearly - the more servers you add the faster the overall process. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> An organization as large as IBM exposes the employee to a wide variety of bureaucratic and logistic issues. I worked on various projects in the data center to address these needs. Mapping the locations of people within buildings and creating automatic reporting structure graphs were created for the broader IBM community. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/watchPad_thumbnail0.png"/> </div> <div class="col-md-6"> In addition to world class consumer grade hardware and software, IBM has access to some of the worlds most interesting device prototypes. I contacted IBM Research and asked for access to the WatchPad prototype. [<NAME>](https://in.linkedin.com/in/m-t-raghunath-a98600) and [<NAME>](http://researcher.watson.ibm.com/researcher/view.php?person=us-chandras) were a fantastic help getting me up and running with the IBM WatchPad environment. Working with this hardware was a unique learning experience, which you can read more about on the WatchPad page. I also had experience with the IBM [Tetra](http://archive.linuxgizmos.com/device-profile-cdl-paron-secure-pda/) smart phone, which included a fingerprint reader and lightweight Linux environment. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/soulPad_thumbnail0.png"/> </div> <div class="col-md-6"> After working on the IBM WatchPad, Chandra approached me to consider helping out with the IBM SoulPad. This was another great opportunity to work on a Linux software stack that represented the leading edge of virtualization. you can read more about my experiences with this project on the SoulPad page. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Exposure with management through the success of these and other projects led to my involvement with a wide variety of groups within IBM. Among these were the EBI Innovation Team, Autonomic Technology Cohorts, NC Green Team, and the IGS Invention Development team. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/resourceLocator_thumbnail0.png"/> </div> <div class="col-md-6"> Addressing a sales idea from <NAME> led to the Resource Locator project, and the many successes and awards it produced for the Resource Locator team. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-2"> <img width="200px" src="/images/ibm-images/blueberry_thumbnail0.png"/> </div> <div class="col-md-6"> Expanding on the procedural and technical success of the Resource Locator project was the goal of the BlueBerry enterprise data search application. Click the link above for further details including what a 120+ laptop processing cluster looks like. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> During this time I also worked as a System Administrator for the Central Customer Master System project. In this role I configured and administered dozens of systems in diverse geographical locations for a multi-national team supporting test and development efforts across multiple platforms. I also did a little J2EE development to support features in various releases for the project. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> Over the past three years, I have written 38 IBM developerWorks articles, completed patent applications for innovations in 19 different areas, and participated in multiple podcast interviews with Scott Laningham. You can read more about these projects and their associated Awards and Recognition from IBM. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> The successes within IBM described above and on other pages led me to begin the "Innovation that Matters - for your career and your bank account" talk to various organizations within IBM. This presentation was unique in that it would be more than someone just reading slides to you. I'd go through the pages of the Presentation, and tailor the spoken component to the audience. Using some of the tools described on these pages, I would give specific examples of innovation for the organization and individuals of that organization based on the corporate goals and personal skill sets of the listeners. </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> <div class="row spaced_rows"> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> </div> <!-- container --><div class="container"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> </div> <!--left side column--> </div><!-- row --> </div> <!-- container --> <div class="panel"> <div class="panel-body"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2009-03-01T00:00:00-05:00"> Sun 01 March 2009</time> </span> <span class="label label-default">Tags</span> <a href="/tag/ibm.html">ibm</a> </footer><!-- /.post-info --> </div> </div> </div> <!-- /.entry-content --> </article> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li> <li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2023 <NAME> &middot; Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="/theme/js/respond.min.js"></script> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4602287-2']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End Google Analytics Code --> </body> </html><file_sep>/content/posts/wasatch_pysideapp.md Title: PySideApp - Minimal application demonstrating core features for deployable applications Date: 2016-04-26 Category: articles Tags: wasatch photonics What I always wished I had the time to develop earlier. Multiprocessing that is tested. Log setups that spawn processes and all messages go to the same file. MVC architecture with separately tested components. Fully automated application builds on windows, including the installer. This is the basis for a wide range of next generation app for Wasatch photonics, including: [MicroAngio UX Demo](https://github.com/WasatchPhotonics/MicroAngio) [FastPM100](https://github.com/WasatchPhotonics/FastPM100) AutoFallOff (in progress) Dash4 - The next revision of the [Dash spectrometer control](http://devices.wasatchphotonics.com/) software. This application is designed to meet one of Wasatch's primary use cases: rapid acquisition of data from devices, with visualization. Available on [GitHub](https://github.com/WasatchPhotonics/PySideApp) <file_sep>/content/posts/wasatch_worklog.md Title: Work log - Recording of software work at Wasatch Photonics Date: 2016-10-17 Category: articles Tags: wasatch photonics thumbnail_image: /images/wasatch-images/wasatch_photonics_logo.png Document at a high level each of the main tasks for that work day at Wasatch. Provide a series of time, effort and control metrics for finding the most efficient mechanisms to move forward. This page is the meta description of the effort. The actual work log will be recorded in the [Wasatch Timeline](/pages/wasatch_work_log_timeline.html) <file_sep>/content/developerworks/os-ghosd.md Title: Create fancy on-screen displays with Ghosd and Perl Date: 2007-02-13 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-ghosd Let system events kick off on-screen alerts displaying text and images, Use Perl, Ghosd, and some network programming to display on-screen overlays of text and graphics based on messages from your local system and remote computers. Define custom images, font sizes, and colors to convey information integrated with your desktop. <file_sep>/content/posts/wasatch_usb.md Title: WasatchUSB - bare bones USB communication with wasatch devices Date: 2016-04-08 Category: articles Tags: wasatch photonics USB cameras and devices from Wasatch Photonics This module is intended to provide the absolute bare-minimum, pure python communication with a StrokerARMUSB board. These tests include communication with a Phidgets relay device, to place the device in a known power state. At Wasatch, we use this for verification of protocol functional specifications during development of new firmware versions. This includes Windows LibUsb INF drivers, as well as configuration instructions and udev rules for access on Linux. Available on [GitHub](https://github.com/WasatchPhotonics/WasatchUSB) <file_sep>/content/posts/bmfiddle_styling.md Title: bmfiddle.com user interface modifications Date: 2017-09-23 Category: articles Tags: business model canvas Configure bmfiddle.com to match the goals of the business model canvas. The tools provided by [bmfiddle.com](https://bmfiddle.com) are excellent. Based on earlier [research]({filename}learning_stage3.md), the following goals emerged: 1. Fully digital business model canvas that uses the BMC correctly. 2. Includes imagery + text in each sticky 3. Business model canvas components with the right names in the right order 4. Minimal visual distractions 5. Box text headers only (DO NOT WRITE ON THE CANVAS) 6. Allow for rapid upates 7. Provide clear visual indicators that can be portable to other media quickly (zoom, export to png, screenshots, etc.) 8. Encourage play Here's how to use bmfiddle.com to meet these goals: Sign in to bmfiddle Create a new fiddle >Title: Business Model Generation with Clarity >Description: Based on Steve Blanks Udacity course - add userstyles here: http://goo.gl/oLuFte Template is the Business Model Canvas Keep all access and sharing defaults Click Customize template Click Value Propositions box, change order from 2 to 1 Click Customer Segments box, change order from 1 to 2 Click Key Partners box, change order from 8 to 7 Click Key Activities box, change order from 7 to 8 Go through each box, eliminate all Block description and Block Help text items. Keep all Labels and Metrics defaults Save the fiddle. It should now look like this: [![BMfiddle step1](/images/learning/thumbnails/bmfiddle_step1.png)](/images/learning/bmfiddle_step1.png) Or, use the bmfiddle.com template here: [Business Model Generation with Clarity](https://bmfiddle.com/f/#/M7bw6) To eliminate more of the visual distractions, add the [stylus plugin ](https://add0n.com/stylus.html) (Not 'Sylish'!) to firefox. Click the extension icon, then write new style-> for bmfiddle.com. Add the contents of the box below, or click here for the user style [bmfiddle clarity](https://gist.github.com/NathanHarrington/b057a49a38620f0bf8c20e9aa709dc55.js) ``` @namespace url(http://www.w3.org/1999/xhtml); @-moz-document domain("bmfiddle.com") { /* make text color white on white to eliminate the visually * distracting component numbers*/ .block .order { background-color: #ffffff;} /* hide all of the background iconagraphy */ .bg {background-image: none;} /* hide the count of stickys in the lower right */ .block .count {color: #ffffff;} /* make icons small on the canvas */ .item-asset img.scale-with-grid { max-width: 10%; } } ``` Give the style the name of bmfiddle_clarity, then save. Now the canvas should look like this: [![BMfiddle step2](/images/learning/thumbnails/bmfiddle_step2.png)](/images/learning/bmfiddle_step2.png) Add the following set of line drawn images to the resources area of the bmfiddle. The icons below are extracted from the [uniicons](https://dribbble.com/shots/2266356-Uniicons-free) pack. ![uniicons/path4502.png](/images/learning/bmfiddle_icons/uniicons/path4502.png) ![uniicons/path4504.png](/images/learning/bmfiddle_icons/uniicons/path4504.png) ![uniicons/path4506.png](/images/learning/bmfiddle_icons/uniicons/path4506.png) ![uniicons/path4508.png](/images/learning/bmfiddle_icons/uniicons/path4508.png) ![uniicons/path4510.png](/images/learning/bmfiddle_icons/uniicons/path4510.png) ![uniicons/path4512.png](/images/learning/bmfiddle_icons/uniicons/path4512.png) ![uniicons/path4514.png](/images/learning/bmfiddle_icons/uniicons/path4514.png) ![uniicons/path4516.png](/images/learning/bmfiddle_icons/uniicons/path4516.png) ![uniicons/path4518.png](/images/learning/bmfiddle_icons/uniicons/path4518.png) ![uniicons/path4520.png](/images/learning/bmfiddle_icons/uniicons/path4520.png) ![uniicons/path4522.png](/images/learning/bmfiddle_icons/uniicons/path4522.png) ![uniicons/path4524.png](/images/learning/bmfiddle_icons/uniicons/path4524.png) ![uniicons/path4526.png](/images/learning/bmfiddle_icons/uniicons/path4526.png) ![uniicons/path4528.png](/images/learning/bmfiddle_icons/uniicons/path4528.png) ![uniicons/path4530.png](/images/learning/bmfiddle_icons/uniicons/path4530.png) ![uniicons/path4532.png](/images/learning/bmfiddle_icons/uniicons/path4532.png) ![uniicons/path4534.png](/images/learning/bmfiddle_icons/uniicons/path4534.png) ![uniicons/path4536.png](/images/learning/bmfiddle_icons/uniicons/path4536.png) ![uniicons/path4538.png](/images/learning/bmfiddle_icons/uniicons/path4538.png) ![uniicons/path4540.png](/images/learning/bmfiddle_icons/uniicons/path4540.png) ![uniicons/path4542.png](/images/learning/bmfiddle_icons/uniicons/path4542.png) ![uniicons/path4544.png](/images/learning/bmfiddle_icons/uniicons/path4544.png) ![uniicons/path4546.png](/images/learning/bmfiddle_icons/uniicons/path4546.png) ![uniicons/path4548.png](/images/learning/bmfiddle_icons/uniicons/path4548.png) ![uniicons/path4550.png](/images/learning/bmfiddle_icons/uniicons/path4550.png) ![uniicons/path4552.png](/images/learning/bmfiddle_icons/uniicons/path4552.png) ![uniicons/path4554.png](/images/learning/bmfiddle_icons/uniicons/path4554.png) ![uniicons/path4556.png](/images/learning/bmfiddle_icons/uniicons/path4556.png) ![uniicons/path4558.png](/images/learning/bmfiddle_icons/uniicons/path4558.png) ![uniicons/path4560.png](/images/learning/bmfiddle_icons/uniicons/path4560.png) ![uniicons/path4562.png](/images/learning/bmfiddle_icons/uniicons/path4562.png) ![uniicons/path4564.png](/images/learning/bmfiddle_icons/uniicons/path4564.png) ![uniicons/path4566.png](/images/learning/bmfiddle_icons/uniicons/path4566.png) ![uniicons/path4568.png](/images/learning/bmfiddle_icons/uniicons/path4568.png) ![uniicons/path4570.png](/images/learning/bmfiddle_icons/uniicons/path4570.png) ![uniicons/path4572.png](/images/learning/bmfiddle_icons/uniicons/path4572.png) ![uniicons/path4574.png](/images/learning/bmfiddle_icons/uniicons/path4574.png) ![uniicons/path4576.png](/images/learning/bmfiddle_icons/uniicons/path4576.png) ![uniicons/path4578.png](/images/learning/bmfiddle_icons/uniicons/path4578.png) ![uniicons/path4580.png](/images/learning/bmfiddle_icons/uniicons/path4580.png) ![uniicons/path4582.png](/images/learning/bmfiddle_icons/uniicons/path4582.png) ![uniicons/path4584.png](/images/learning/bmfiddle_icons/uniicons/path4584.png) ![uniicons/path4586.png](/images/learning/bmfiddle_icons/uniicons/path4586.png) ![uniicons/path4588.png](/images/learning/bmfiddle_icons/uniicons/path4588.png) ![uniicons/path4590.png](/images/learning/bmfiddle_icons/uniicons/path4590.png) ![uniicons/path4592.png](/images/learning/bmfiddle_icons/uniicons/path4592.png) ![uniicons/path4594.png](/images/learning/bmfiddle_icons/uniicons/path4594.png) ![uniicons/path4596.png](/images/learning/bmfiddle_icons/uniicons/path4596.png) ![uniicons/path4598.png](/images/learning/bmfiddle_icons/uniicons/path4598.png) ![uniicons/path4600.png](/images/learning/bmfiddle_icons/uniicons/path4600.png) ![uniicons/path4602.png](/images/learning/bmfiddle_icons/uniicons/path4602.png) ![uniicons/path4604.png](/images/learning/bmfiddle_icons/uniicons/path4604.png) ![uniicons/path4606.png](/images/learning/bmfiddle_icons/uniicons/path4606.png) ![uniicons/path4608.png](/images/learning/bmfiddle_icons/uniicons/path4608.png) ![uniicons/path4610.png](/images/learning/bmfiddle_icons/uniicons/path4610.png) ![uniicons/path4612.png](/images/learning/bmfiddle_icons/uniicons/path4612.png) ![uniicons/path4614.png](/images/learning/bmfiddle_icons/uniicons/path4614.png) ![uniicons/path4616.png](/images/learning/bmfiddle_icons/uniicons/path4616.png) ![uniicons/path4618.png](/images/learning/bmfiddle_icons/uniicons/path4618.png) ![uniicons/path4620.png](/images/learning/bmfiddle_icons/uniicons/path4620.png) ![uniicons/path4622.png](/images/learning/bmfiddle_icons/uniicons/path4622.png) ![uniicons/path4624.png](/images/learning/bmfiddle_icons/uniicons/path4624.png) ![uniicons/path4626.png](/images/learning/bmfiddle_icons/uniicons/path4626.png) ![uniicons/path4628.png](/images/learning/bmfiddle_icons/uniicons/path4628.png) ![uniicons/path4630.png](/images/learning/bmfiddle_icons/uniicons/path4630.png) ![uniicons/path4632.png](/images/learning/bmfiddle_icons/uniicons/path4632.png) ![uniicons/path4634.png](/images/learning/bmfiddle_icons/uniicons/path4634.png) ![uniicons/path4636.png](/images/learning/bmfiddle_icons/uniicons/path4636.png) ![uniicons/path4638.png](/images/learning/bmfiddle_icons/uniicons/path4638.png) ![uniicons/path4640.png](/images/learning/bmfiddle_icons/uniicons/path4640.png) ![uniicons/path4642.png](/images/learning/bmfiddle_icons/uniicons/path4642.png) ![uniicons/path4644.png](/images/learning/bmfiddle_icons/uniicons/path4644.png) ![uniicons/path4646.png](/images/learning/bmfiddle_icons/uniicons/path4646.png) ![uniicons/path4648.png](/images/learning/bmfiddle_icons/uniicons/path4648.png) ![uniicons/path4650.png](/images/learning/bmfiddle_icons/uniicons/path4650.png) ![uniicons/path4652.png](/images/learning/bmfiddle_icons/uniicons/path4652.png) ![uniicons/path4654.png](/images/learning/bmfiddle_icons/uniicons/path4654.png) ![uniicons/path4656.png](/images/learning/bmfiddle_icons/uniicons/path4656.png) ![uniicons/path4658.png](/images/learning/bmfiddle_icons/uniicons/path4658.png) ![uniicons/path4660.png](/images/learning/bmfiddle_icons/uniicons/path4660.png) ![uniicons/path4662.png](/images/learning/bmfiddle_icons/uniicons/path4662.png) ![uniicons/path4664.png](/images/learning/bmfiddle_icons/uniicons/path4664.png) ![uniicons/path4666.png](/images/learning/bmfiddle_icons/uniicons/path4666.png) ![uniicons/path4668.png](/images/learning/bmfiddle_icons/uniicons/path4668.png) ![uniicons/path4670.png](/images/learning/bmfiddle_icons/uniicons/path4670.png) ![uniicons/path4672.png](/images/learning/bmfiddle_icons/uniicons/path4672.png) ![uniicons/path4674.png](/images/learning/bmfiddle_icons/uniicons/path4674.png) ![uniicons/path4676.png](/images/learning/bmfiddle_icons/uniicons/path4676.png) ![uniicons/path4678.png](/images/learning/bmfiddle_icons/uniicons/path4678.png) ![uniicons/path4680.png](/images/learning/bmfiddle_icons/uniicons/path4680.png) ![uniicons/path4682.png](/images/learning/bmfiddle_icons/uniicons/path4682.png) ![uniicons/path4684.png](/images/learning/bmfiddle_icons/uniicons/path4684.png) ![uniicons/path4686.png](/images/learning/bmfiddle_icons/uniicons/path4686.png) ![uniicons/path4688.png](/images/learning/bmfiddle_icons/uniicons/path4688.png) ![uniicons/path4690.png](/images/learning/bmfiddle_icons/uniicons/path4690.png) ![uniicons/path4692.png](/images/learning/bmfiddle_icons/uniicons/path4692.png) ![uniicons/path4694.png](/images/learning/bmfiddle_icons/uniicons/path4694.png) ![uniicons/path4696.png](/images/learning/bmfiddle_icons/uniicons/path4696.png) ![uniicons/path4698.png](/images/learning/bmfiddle_icons/uniicons/path4698.png) ![uniicons/path4700.png](/images/learning/bmfiddle_icons/uniicons/path4700.png) Download the full zip of the [bmfiddle uniicons](/images/learning/bmfiddle_icons/uniicons/bmfiddle_uniicons.zip) pngs. The easiest way to get these into the canvas resources are is to e-mail them to <canvas_<EMAIL> from the address used to create your bmfiddle.com account. On linux, this can look like: ``` cd uniicons/ mutt <canvas_id>@<EMAIL> -s "PNGs" $( printf -- '-a %q ' *.png ) ``` As of 2017-09-29 16:01, mailing these 100 files to bmfiddle will trigger them to be re-added at least 3 times, resulting in duplicates and confusion in the resources pane. Send them in groups of ten instead with: ``` #!/bin/bash # # bmfiddle_resource_mailer.sh script located in: # nathanharrington.github.io/content/images/learning/bmfiddle_icons/uniicons # # Assumes a fully functional mutt configuration. # # Usage: cd to the directory above (with all the folder? entires) # # run the script lke: ./bmfiddle_resource_mailer.sh CANVASID # if [[ $# -eq 0 ]] ; then echo 'You must specify a bmfiddle CANVASID' exit 0 fi CANVASID="$1" EMAIL=<EMAIL> COUNTER=1 while [ $COUNTER -lt 11 ]; do echo "Mail folder$COUNTER group" FILES=$( printf -- '-a %q ' folder${COUNTER}/*.png ) mutt $EMAIL -s 'PNGs ${COUNTER} of 10' $FILES < /dev/null # Change intervals for primitive spam avoidance sleep $COUNTER let COUNTER=COUNTER+1 done ``` You can use the sketch tool on bmfiddle, but it will not have a transparent background. If you're making your own icons like those shown below, remember to create or verify the icons as SVG's with a transparent background. Save them in the bmfiddle_icons directory, then run the convert_svg_to_png.sh script, which will create the transparent png thumbnails. These are what will be uploaded to the resources area on bmfiddle. [![channels](/images/learning/bmfiddle_icons/thumbnails/channels.png)](/images/learning/bmfiddle_icons/channels.png) [![costs](/images/learning/bmfiddle_icons/thumbnails/costs.png)](/images/learning/bmfiddle_icons/costs.png) [![customer relationships](/images/learning/bmfiddle_icons/thumbnails/customer_relationships.png)](/images/learning/bmfiddle_icons/customer_relationships.png) [![customer segments](/images/learning/bmfiddle_icons/thumbnails/customer_segments.png)](/images/learning/bmfiddle_icons/customer_segments.png) [![key activities](/images/learning/bmfiddle_icons/thumbnails/key_activities.png)](/images/learning/bmfiddle_icons/key_activities.png) [![key partners](/images/learning/bmfiddle_icons/thumbnails/key_partners.png)](/images/learning/bmfiddle_icons/key_partners.png) [![key resources](/images/learning/bmfiddle_icons/thumbnails/key_resources.png)](/images/learning/bmfiddle_icons/key_resources.png) [![revenue streams](/images/learning/bmfiddle_icons/thumbnails/revenue_streams.png)](/images/learning/bmfiddle_icons/revenue_streams.png) [![value propositions](/images/learning/bmfiddle_icons/thumbnails/value_proposition.png)](/images/learning/bmfiddle_icons/value_proposition.png) ``` #!/bin/bash # convert_svg_to_png.sh for i in *.svg do convert -background none "$i" "${i%svg}png" done # Now convert them to thumbnails for i in *.png do convert -resize 50x50 "$i" "thumbnails/$i" done ``` Remember, the idea here is to tune bmfiddle.com into a tool you can use for the next 3 months at least. Don't get frustrated, don't give up. Don't think you are over-optimizing at this stage. The bare bones best version is still probably sticky notes on a white piece of paper with a team of people. You can make a better version that is fully digital and auto-backed up and is actually easier to share with people if you put in the tools up front, and have the disciplined flow in the future. The next disciplined flow will be: ``` Log in to bmfiddle.com Fork from the clarity canvas. Upload the imagery resources. Now for each update: Take a snapshot first. when in doubt, just hit that snapshot button Move stickies on and off to the stack, or maybe the archive. Never delete them. ``` The process above was used to create a bmfiddle.com canvas that looks like this: [![BMfiddle step3](/images/learning/thumbnails/bmfiddle_step3.png)](/images/learning/bmfiddle_step3.png) <file_sep>/content/patents/patent_7,872,572.md Title: Method and system for vehicle mounted infrared wavelength information displays for traffic camera viewers Date: 2011-01-18 template: patent patent_number: 7,872,572 Systems and methods for vehicle mounted infrared wavelength information displays for traffic camera viewers are disclosed. A method includes obtaining vehicle positioning data associated with at least one vehicle and, based upon the vehicle positioning data, selectively emitting infrared wavelength light from a set of a plurality of light emitting diodes (LEDs) arranged on exterior surfaces of the at least one vehicle. <file_sep>/content/developerworks/os-sphinxspeechrec.md Title: Create automated verbal conversation annotations Date: 2007-11-13 Category: articles template: developerworks devworks_link: http://www-128.ibm.com/developerworks/library/ shortname: os-sphinxspeechrec Use the open source Sphinx-4 speech-recognition package to capture letters and numbers from spoken conversations in near real time to create notes. Employ a custom Sphinx-4 dictionary file to extract likely matches to spoken letters and numbers. Process the text for higher order values such as phone numbers and acronyms, and create a meeting annotator through search-engine lookups and local databases. <file_sep>/content/posts/amazon_free_tier.md Title: Amazon Free Tier SSH etc. Date: 2018-02-09 Category: articles Tags: system administration Free Tier amazon instances are a game changer. Here's how to set the windows micro instances to function as an ssh server for easier transfer of files. Skip to the bottom for billing considerations. Tested using: Microsoft Windows Server 2016 Base - ami-fe446c9b t2-micro Fedora Core 26 client (rdesktop) <pre> Using the Amazon EC2 web interface: Create a key-pair name: amazon_key_pair.pem Download the keypair file. Create notifications to email when usage exceed free tier. This in practice should never happen, but it feels good. After instance launches, click connect. Click Get password. </pre> Then start the remote desktop session with a command like: <pre> rdesktop long_hostname.us-east-2.compute.amazonaws.com -u \ Administrator -p '<PASSWORD>' -g <PASSWORD> -K On the linux machine, you may see an error message like: Failed to connect, CredSSP required by server. Fix this by installing freerdp, then running: xfreerdp /u:"Administrator" \ /v:long_hostname.us-east-2.compute.amazonaws.com:3389 </pre> <pre> Directly on the Windows Server virtual machine: CRITICAL! Seriously consider turning off all windows defender options immediately. These can effectively make the system unusable. Alternatively, let them run and plan to use the server a day later once it has stabilized. CRITICAL! Start internet explorer, install Google Chrome Add all google domains (including ad trackers) that appear during the process to the whitelist. Install ublock origin from google chrome Change timezone and time if necessary Restart system The details steps below for ssh server installation are based heavily on the article on [LifeHacker](https://lifehacker.com/205090/geek-to-live--set-up-a-personal-home-ssh-server) Go to cygwin.com Download and run setup-x86_64.exe Accept default until mirror selection. Select clarkson.edu as mirror search for openssh in Net group, install Make sure to select version 7.9p1-1 for the instructions below to work. (2019-06-03) Launch a cygwin command line window Execute command: ssh-host-config Strictmodes? Yes New local account sshd? Yes Install sshd as a service? Yes Enter the value of CYGWIN for the daemon: ntsec tty Do you want to use a different name? No Create a new priviledged account? Yes Set password: type in 8 character password with number and capital After setup is complete, change the ssh server port to 6787 Edit the file: /c/cygwin64/etc/sshd_config Change: #Port 22 to Port 6787 Then in a cygwin window, issue: net start sshd Then add the firewall port 6787 inbound rule to open. Firewall -> Advanced settings Inbound rules -> New Rule -> Port Port 6787, name Cygwin SSH Then change the amazon instance network rules to open port 6787 EC2 Dashboard -> Network and security -> Security Groups (Find most recent launch wizard, select) Actions -> Edit inbound rules Add rule for inbound port 6787 Actions -> Edit inbound rules Delete rule for inbound port 3389 </pre> From the Linux client machine: <pre> # Create the ssh folder on the windows system. Make sure to use the same # Administrator password that you pulled down from the EC2 interface to # connect over remote desktop ssh Administrator@long_hostname.aws.com "mkdir ~/.ssh" # Append the linux public key file to the remote list of authorized # keys. Not the .pem file, just your local system public key cat ~/.ssh/id_rsa.pub | ssh Administrator@ec2_hostname \ "cat >> ~/.ssh/authorized_keys" </pre> You can now ssh in with the command below, and tunnel the remote desktop connections over ssh: <pre> autossh \ -M 0 \ -o "ServerAliveInterval 30" \ -o "ServerAliveCountMax 3" \ -o StrictHostKeyChecking=no \ -o port=6787 \ -i ~/.ssh/id_rsa \ -L 9833:localhost:3389 \ -R 6703:localhost:22 \ Administrator@ec2_hostname </pre> Then on the windows computer, open a cygwin command prompt and verify the tunnel back to the host linux machine with: <pre> ssh -o port=6703 localhost </pre> To connect from a linux laptop to the remote windows instance over rdp, setup the tunnel in the autossh command above, then run the rdesktop command below. <pre> rdesktop localhost:9983 -u \ Administrator -p 'from EC2 get password' -g 1920x1000 -K </pre> ## Use the tagging strategy to track the costs on a per-project basis. 1. At each new EC2 instance created, have the discipline to add a tag named 'project', with the value 'project_name'. For example: <pre> project: predicatesai project: lls project: xgut </pre> 2. Go to the AWS billing console: https://console.aws.amazon.com/billing/home 3. Cost Allocation tags -> Activate 4. Wait about 10 minutes 5. Select the 'project' tag, then click activate. 6. Wait 24 hours, now the tags will become available in the AWS Cost Explorer. ## Now that you have some base windows images, you want to encrypt the disks. Specifically the elastic block store volumes. The instructions below are based heavily on: https://aws.amazon.com/blogs/aws/new-encrypted-ebs-boot-volumes/ 1. Configure a machine according to the instructions above. 2. Select Instance -> Actions -> Image -> Create image 3. Wait for the instance image to appear in the "AMI" section. 4. Select the AMI you have just created then Actions -> Copy AMI 5. Select the same destination region. Append the word 'encrypted' to teh AMI name. Check 'Encryption', accept defaults. ## Now you are running an encrypted base image. <pre> Install the development environment. After that is complete, make another AMI image of the encrypted development environment. This is now the basic image you use to pull down new code, setup long term tests, etc. </pre>
7372a6b1a4f5ada61c45f4facb2dd734d4aa8096
[ "Markdown", "Python", "HTML", "Shell" ]
122
Markdown
NathanHarrington/NathanHarrington.github.io
1c09a109a6cc0fc681163844f077693b58c140a4
a4a41b3567f1fa9c17040a3f4ce0b8435fded921
refs/heads/master
<repo_name>TheChill/Game_Project<file_sep>/Game_project/Game.h #pragma once #include <iostream> #include "SDL.h" #include "SDL_image.h" #include <vector> class ColliderComponent; class Game { private: bool is_running; SDL_Window* window; //int count; public: Game(); void initiate(const char* title, int x_pos, int y_pos, int width, int height, bool fullscreen); void handle_events(); void update(); void render(); void clean(); static void add_tile(int id, int x, int y); static SDL_Renderer* renderer; static SDL_Event event; bool running(); static std::vector<ColliderComponent*> colliders; ~Game(); };<file_sep>/Game_project/TileComponent.h #pragma once #include "ECS.h" #include "TransformComponent.h" #include "SpriteComponent.h" #include "SDL.h" class TileComponent : public Component { public: TransformComponent * transform; SpriteComponent *sprite; SDL_Rect tile_rect; int tile_ID; const char* path; TileComponent() = default; TileComponent(int x, int y, int w, int h, int id) { tile_rect.x = x; tile_rect.y = y; tile_rect.w = w; tile_rect.h = h; tile_ID = id; switch (tile_ID) { case 0: path = "C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Water_shallow_mid.png"; break; case 1: path = "C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Grass_mid.png"; break; case 2: path = "C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Grass_south.png"; break; case 3: path = "C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Tree_stomp.png"; break; default: break; } } void init() override { entity->add_component<TransformComponent>((float)tile_rect.x, (float)tile_rect.y, tile_rect.w, tile_rect.h, 1); transform = &entity->get_component<TransformComponent>(); entity->add_component<SpriteComponent>(path); sprite = &entity->get_component<SpriteComponent>(); } };<file_sep>/README.md # Game Project *WIP* A simple top-down RPG using **Simple DirectMedia Layer** (SDL2 and SDL2_image) and tilemap *This project has been done by following a tutorial*<file_sep>/Game_project/GameObject.h #pragma once #include "Game.h" class GameObject { private: int x_pos; int y_pos; SDL_Texture* object_texture; SDL_Rect sorce_rect; SDL_Rect destination_rect; public: GameObject(const char* texture_sheet, int x, int y); void update(); void render(); ~GameObject(); };<file_sep>/Game_project/ECS.cpp #include "ECS.h" void Entity::add_group(Group group) { group_bit_set[group] = true; manager.add_to_group(this, group); } <file_sep>/Game_project/Collision.cpp #include "Collision.h" #include "ColliderComponent.h" bool Collision::AABB(const SDL_Rect& rec_a, const SDL_Rect& rec_b) { if (rec_a.x + rec_a.w >= rec_b.x && rec_b.x + rec_b.w >= rec_a.x && rec_a.y + rec_a.h >= rec_b.y && rec_b.y + rec_b.h >= rec_a.y) { return true; } else { return false; } } bool Collision::AABB(const ColliderComponent& col_a, const ColliderComponent& col_b) { if (AABB(col_a.collider, col_b.collider)) { std::cout << col_a.tag << "hit: " << col_b.tag << std::endl; return true; } else { return false; } } <file_sep>/Game_project/TextureManager.cpp #include "TextureManager.h" SDL_Texture* TextureManager::load_texture(const char* texture_name) { SDL_Surface* temporary_surface = IMG_Load(texture_name); SDL_Texture* texture = SDL_CreateTextureFromSurface(Game::renderer, temporary_surface); SDL_FreeSurface(temporary_surface); return texture; } void TextureManager::draw(SDL_Texture * texture, SDL_Rect source, SDL_Rect destination) { SDL_RenderCopy(Game::renderer, texture, &source, &destination); } <file_sep>/Game_project/Collision.h #pragma once #include "SDL.h" class ColliderComponent; class Collision { public: static bool AABB(const SDL_Rect& rec_a, const SDL_Rect& rec_b); static bool AABB(const ColliderComponent& col_a, const ColliderComponent& col_b); };<file_sep>/Game_project/SpriteComponent.h #pragma once #include "Components.h" #include "SDL.h" #include "TextureManager.h" #include "Animation.h" #include <map> class SpriteComponent : public Component { private: TransformComponent * transform; SDL_Texture *texture; SDL_Rect sorce_rect; SDL_Rect destination_rect; bool animated = false; int frames = 0; int speed = 100; public: SpriteComponent() = default; SpriteComponent(const char* path) { set_texture(path); } SpriteComponent(const char* path, int frames, int speed) { animated = true; this->frames = frames; this->speed = speed; set_texture(path); } void set_texture(const char* path) { texture = TextureManager::load_texture(path); } void init() override { transform = &entity->get_component<TransformComponent>(); sorce_rect.x = 0; sorce_rect.y = 0; sorce_rect.w = transform->width; sorce_rect.h = transform->height; //destination_rect.w = 32; //*2 //destination_rect.h = 32; //*2 } void update() override { if (animated) { sorce_rect.x = sorce_rect.w * static_cast<int>((SDL_GetTicks() / speed) % frames); } destination_rect.x = static_cast<int>(transform->position.x); destination_rect.y = static_cast<int>(transform->position.y); destination_rect.w = transform->width * transform->scale; destination_rect.h = transform->height * transform->scale; } void draw() override { TextureManager::draw(texture, sorce_rect, destination_rect); } ~SpriteComponent() { SDL_DestroyTexture(texture); } };<file_sep>/Game_project/GameObject.cpp #include "GameObject.h" #include "TextureManager.h" GameObject::GameObject(const char* texture_sheet, int x, int y) { object_texture = TextureManager::load_texture(texture_sheet); x_pos = x; y_pos = y; } void GameObject::update() { x_pos++; y_pos++; sorce_rect.h = 32; sorce_rect.w = 32; sorce_rect.x = 0; sorce_rect.y = 0; destination_rect.x = x_pos; destination_rect.y = y_pos; destination_rect.w = sorce_rect.w; destination_rect.h = sorce_rect.h; } void GameObject::render() { SDL_RenderCopy(Game::renderer, object_texture, &sorce_rect, &destination_rect); } GameObject::~GameObject() { }<file_sep>/Game_project/Source.cpp #include "Game.h" Game* game = nullptr; int main(int argc, char* args[]){ const int fps = 60; const int frame_delay = 1000 / fps; Uint32 frame_start; int frame_time; game = new Game(); game->initiate("Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 512, 512, false); while (game->running()) { frame_start = SDL_GetTicks(); game->handle_events(); game->update(); game->render(); frame_time = SDL_GetTicks() - frame_start; if (frame_delay > frame_time) { SDL_Delay(frame_delay - frame_time); } } game->clean(); //system("pause"); return 0; }<file_sep>/Game_project/Game.cpp #include "Game.h" #include "TextureManager.h" #include "Map.h" #include "Components.h" #include "Vector2D.h" #include "Collision.h" Map* map; Manager manager; SDL_Renderer* Game::renderer = nullptr; SDL_Event Game::event; std::vector<ColliderComponent*> Game::colliders; auto& new_player(manager.add_entity()); auto& wall(manager.add_entity()); enum group_labels : std::size_t { group_map, group_players, group_enemies, group_colliders }; Game::Game() { //count = 0; } void Game::initiate(const char* title, int x_pos, int y_pos, int width, int height, bool fullscreen) { int flags = 0; if (fullscreen == true) { flags = SDL_WINDOW_FULLSCREEN; } if (SDL_Init(SDL_INIT_EVERYTHING) == 0) { std::cout << "SDL_Init" << std::endl; window = SDL_CreateWindow(title, x_pos, y_pos, width, height, flags); if (window) { std::cout << "SDL_CreateWindow" << std::endl; } renderer = SDL_CreateRenderer(window, -1, 0); if (renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); std::cout << "SDL_CreateRenderer" << std::endl; } is_running = true; } else { is_running = false; } map = new Map(); Map::load("C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Simple_map_16x16.txt", 16, 16); new_player.add_component<TransformComponent>(); //new_player.add_component<TransformComponent>(0.0f, 0.0f, 32, 32, 2); //new_player.add_component<SpriteComponent>("C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Player_walking.png", 4, 150); new_player.add_component<SpriteComponent>("C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Charecter/Animated_knight_walking_south.png", 4, 200); //new_player.add_component<SpriteComponent>("C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Charecter/Knight_outline_color.png"); new_player.add_component<KeyboardController>(); new_player.add_component<ColliderComponent>("player"); new_player.add_group(group_players); //wall wall.add_component<TransformComponent>(320.0f, 320.0f, 32, 32, 1); wall.add_component<SpriteComponent>("C:/Users/krist/source/repos/Game_project/Game_project/Tilemap/Grass_rock.png"); wall.add_component<ColliderComponent>("wall"); wall.add_group(group_map); } void Game::handle_events() { SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: is_running = false; break; default: break; } } void Game::update() { //count++; //std::cout << count << std::endl; manager.refresh(); manager.update(); for (auto cc : colliders) { Collision::AABB(new_player.get_component<ColliderComponent>(), *cc); } } auto& tiles(manager.get_group(group_map)); auto& players(manager.get_group(group_players)); auto& enemies(manager.get_group(group_enemies)); void Game::render() { SDL_RenderClear(renderer); for (auto& t : tiles) { t->draw(); } for (auto& p : players) { p->draw(); } for (auto& e : enemies) { e->draw(); } SDL_RenderPresent(renderer); } void Game::clean() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); std::cout << "Cleaned" << std::endl; } void Game::add_tile(int id, int x, int y) { auto& tile(manager.add_entity()); tile.add_component<TileComponent>(x, y, 32, 32, id); tile.add_group(group_map); } bool Game::running() { return is_running; } Game::~Game() { } <file_sep>/Game_project/Map.h #pragma once #include <string> class Map { private: public: Map(); static void load(std::string path, int size_x, int size_y); ~Map(); };<file_sep>/Game_project/TextureManager.h #pragma once #include "Game.h" class TextureManager { private: public: static SDL_Texture* load_texture(const char* file_name); static void draw(SDL_Texture* texture, SDL_Rect source, SDL_Rect destination); }; <file_sep>/Game_project/ECS.h #pragma once #include <iostream> #include <vector> #include <memory> #include <algorithm> #include <bitset> #include <array> class Component; class Entity; class Manager; using ComponentID = std::size_t; using Group = std::size_t; inline ComponentID get_new_component_type_ID() { static ComponentID last_ID = 0u; return last_ID++; } template <typename T> inline ComponentID get_component_type_ID() noexcept { static ComponentID type_ID = get_new_component_type_ID(); return type_ID; } constexpr std::size_t max_components = 32; constexpr std::size_t max_groups = 32; using ComponentBitSet = std::bitset<max_components>; using GroupBitSet = std::bitset<max_groups>; using ComponentArray = std::array<Component*, max_components>; class Component { private: public: Entity* entity; virtual void init() {} virtual void update() {} virtual void draw() {} virtual ~Component() {} }; class Entity { private: Manager & manager; bool active = true; std::vector<std::unique_ptr<Component> > components; ComponentArray component_array; ComponentBitSet component_bit_set; GroupBitSet group_bit_set; public: Entity(Manager& manager) : manager(manager) { } void update() { for (auto& c : components) c->update(); } void draw() { for (auto& c : components) c->draw(); } bool is_active() const { return active; } void destroy() { active = false; } bool has_group(Group group) { return group_bit_set[group]; } void add_group(Group group); void del_group(Group group) { group_bit_set[group] = false; } template <typename T> bool has_component() const { return component_bit_set[get_component_type_ID<T>()]; } template <typename T, typename... TArgs> T& add_component(TArgs&&... mArgs) { T* c(new T(std::forward<TArgs>(mArgs)...)); c->entity = this; std::unique_ptr<Component> uPtr{ c }; components.emplace_back(std::move(uPtr)); component_array[get_component_type_ID<T>()] = c; component_bit_set[get_component_type_ID<T>()] = true; c->init(); return *c; } template<typename T> T& get_component() const { auto ptr(component_array[get_component_type_ID<T>()]); return *static_cast<T*>(ptr); } }; class Manager { private: std::vector<std::unique_ptr<Entity> > entities; std::array<std::vector<Entity*>, max_groups> grouped_entities; public: void update() { for (auto& e : entities) e->update(); } void draw() { for (auto& e : entities) e->draw(); } void refresh() { for (auto i(0u); i < max_groups; i++) { auto& v(grouped_entities[i]); v.erase(std::remove_if(std::begin(v), std::end(v), [i](Entity* entity) { return !entity->is_active() || !entity->has_group(i); }), std::end(v)); } entities.erase(std::remove_if(std::begin(entities), std::end(entities), [](const std::unique_ptr<Entity> &mEntity) { return !mEntity->is_active(); }), std::end(entities)); } void add_to_group(Entity* entity, Group group) { grouped_entities[group].emplace_back(entity); } std::vector<Entity*>& get_group(Group group) { return grouped_entities[group]; } Entity& add_entity() { Entity* e = new Entity(*this); std::unique_ptr<Entity> uPtr{ e }; entities.emplace_back(std::move(uPtr)); return *e; } };
4f212a8a9726b68e7bbea7eac371a030d884afc9
[ "Markdown", "C++" ]
15
C++
TheChill/Game_Project
49d1666af33eddecf230dd69816fe857ee211e6e
2abc5f56d36751192a64ed3dfdcd260427b11e56
refs/heads/master
<repo_name>vineethk123/Design-Patterns-Assignment<file_sep>/subway recipes/Salad.java public class Salad { private boolean tomato; private boolean capsicum; private boolean carrot; private boolean radish; public double price; public Salad(SaladBuilder sbuild) { this.tomato = sbuild.tomato; this.capsicum = sbuild.capsicum; this.carrot = sbuild.carrot; this.radish = sbuild.radish; } public boolean hasTomato() { return this.tomato; } public boolean hasCapsicum() { return this.capsicum; } public boolean hasCarrot() { return this.carrot; } public boolean hasRadish() { return this.radish; } public double getPrice() { if(hasTomato()) { price += 3; } if(hasCapsicum()) { price += 3; } if(hasCarrot()) { price += 3; } if(hasRadish()) { price += 3; } return price; } public String toString() { return "Salad:\n" + "Tomatoes: " + hasTomato() + "\nCapsicum: " + hasCapsicum() + "\nCarrot: " + hasCarrot() + "\nRadish: " + hasRadish(); } public static class SaladBuilder { private boolean tomato; private boolean capsicum; private boolean carrot; private boolean radish; public SaladBuilder() {} public SaladBuilder addTomatoes() { this.tomato = true; return this; } public SaladBuilder addCapsicum() { this.capsicum = true; return this; } public SaladBuilder addCarrot() { this.carrot = true; return this; } public SaladBuilder addRadish() { this.radish = true; return this; } public Salad build() { return new Salad(this); } } } <file_sep>/Utoo Cab Service/HyderabadChart.java public class HyderabadChart implements Chart { private Micro micro; private Mini mini; private SUV suv; public HyderabadChart() { this.micro = new Micro(); this.mini = new Mini(); this.suv = new SUV(); } @Override public void getRateChart() { System.out.println("\nRate Chart for Hyderabad(In INR):\n"); System.out.println("Micro: " + micro.getPrice() + "\nMini: " + mini.getPrice() + "\nSUV: " + suv.getPrice()); } } <file_sep>/XE India/ConversionWebsite.java import java.util.*; public class ConversionWebsite implements Subscriber{ double usd_in_inr; double gbp_in_inr; double euro_in_inr; List<Update> subscribers; public ConversionWebsite() { subscribers = new ArrayList<Update>(); } // Set the Currency rates and notify subscribers public void setCurrencyRates(double usd_in_inr, double euro_in_inr, double gbp_in_inr) { this.usd_in_inr = usd_in_inr; this.gbp_in_inr = gbp_in_inr; this.euro_in_inr = euro_in_inr; subscribersNotify(); } // Add subscription public void subscribe(Update sb) { subscribers.add(sb); } // Remove subscription public void unsubscribe(Update sb) { int index = subscribers.indexOf(sb); if(index>=0) { subscribers.remove(index); } } // Update the currency rates in all subscribers public void subscribersNotify() { for(Update s: subscribers) { s.update(usd_in_inr, gbp_in_inr, euro_in_inr); } } } <file_sep>/Utoo Cab Service/Micro.java public class Micro extends Cab{ public Micro() { super(6.0, 1.0, 0.6); } } <file_sep>/Utoo Cab Service/HyderabadChartFactory.java public class HyderabadChartFactory implements AbstractChartFactory{ public HyderabadChartFactory() {} @Override public Chart createChart() { return new HyderabadChart(); } } <file_sep>/Payments India/PaymentGateway.java import java.util.*; public class PaymentGateway { public static void main(String args[]) { // Payment Declines if the randomly generated balance is less than the amount passed Payment method1 = PaymentFactory.getPaymentMethod("creditcard", null, 364823412, 123, 5000); Payment method2 = PaymentFactory.getPaymentMethod("debitcard", null, 364823412, 123, 5000); Payment method3 = PaymentFactory.getPaymentMethod("wallet", null, 364823412, 123, 5000); Payment method4 = PaymentFactory.getPaymentMethod("Netbanking", null, 364823412, 123, 5000); Payment method5 = PaymentFactory.getPaymentMethod("cashondelivery", null, 364823412, 123, 5000); List<Payment> payment_methods= new ArrayList<Payment>(); payment_methods.add(method1); payment_methods.add(method2); payment_methods.add(method3); payment_methods.add(method4); payment_methods.add(method5); for(Payment i: payment_methods) { if(i == null) { System.out.println("Invalid Payment Type"); } else { method1.makeTransaction(); } } } } <file_sep>/Payments India/NetBanking.java public class NetBanking extends Payment{ private long acc_no; private String bank_name; private int otp; public NetBanking(String bank_name, long acc_no, int otp, double amount) { super(amount); this.bank_name = bank_name; this.acc_no = acc_no; this.otp = otp; } } <file_sep>/XE India/Subscriber.java public interface Subscriber { void subscribe(Update sb); void unsubscribe(Update sb); void subscribersNotify(); }<file_sep>/Utoo Cab Service/BengaluruChart.java public class BengaluruChart implements Chart { private Micro micro; private Mini mini; private Sedan sedan; private SUV suv; public BengaluruChart() { this.micro = new Micro(); this.mini = new Mini(); this.sedan = new Sedan(); this.suv = new SUV(); } @Override public void getRateChart() { System.out.println("\nRate Chart for Bengaluru(In INR):\n"); System.out.println("Micro: " + micro.getPrice() + "\nMini: " + mini.getPrice() + "\nSedan: " + sedan.getPrice() + "\nSUV: " + suv.getPrice()); } } <file_sep>/SyncDoc/Doctor.java public interface Doctor { void getAppointment(String day, String time); } <file_sep>/subway recipes/Addons.java public class Addons { private boolean cheese; private boolean veggies; public double price; private Addons() {} private Addons(AddonsBuilder addbuilder) { this.cheese = addbuilder.cheese; this.veggies = addbuilder.veggies; } public boolean hasCheese() { return cheese; } public boolean hasVeggies() { return veggies; } public double getPrice() { if(hasCheese()) { price += 15; } if(hasVeggies()) { price += 10; } return price; } public String toString() { return "Addons:\n" + "Cheese: " + hasCheese() + "\n" + "Veggies: " + hasVeggies() + "\n"; } public static class AddonsBuilder { private boolean cheese; private boolean veggies; public AddonsBuilder() {} public AddonsBuilder addCheese() { this.cheese = true; return this; } public AddonsBuilder addVeggies() { this.veggies = true; return this; } public Addons build() { return new Addons(this); } } } <file_sep>/XE India/Update.java public interface Update { public void update(double usd_to_inr, double euro_to_inr, double gbp_to_inr); }<file_sep>/Payments India/DebitCard.java public class DebitCard extends Payment{ private long card_no; private int cvv; public DebitCard(long card_no, int cvv, double amount) { super(amount); this.card_no = card_no; this.cvv = cvv; } } <file_sep>/Utoo Cab Service/Mini.java public class Mini extends Cab{ public Mini() { super(9, 1.0, 0.9); } } <file_sep>/Utoo Cab Service/ChartFactory.java public class ChartFactory { public static Chart getChart(AbstractChartFactory factory) { return factory.createChart(); } } <file_sep>/SyncDoc/Dermatologist.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Dermatologist implements Doctor{ private String name; private int id; private Integer count; Map<Integer, ArrayList> appointments; public Dermatologist(String name, int id) { this.name = name; this.id = id; this.count = new Integer(0); this.appointments = new HashMap<Integer, ArrayList>(); } public void getAppointment(String day, String time) { ArrayList<String> details = new ArrayList<String>(); details.add(day); details.add(time); register(details); } private void register(ArrayList<String> details) { this.count += 1; this.appointments.put(this.count, details); System.out.println("Appointment with " + this.name + " on " + details.get(0) + " at " + details.get(1) + " is booked"); } } <file_sep>/Utoo Cab Service/ChennaiChartFactory.java public class ChennaiChartFactory implements AbstractChartFactory { public ChennaiChartFactory() {} @Override public Chart createChart() { return new ChennaiChart(); } } <file_sep>/subway recipes/OrderSub.java public class OrderSub { public static void main(String args[]) { double total_price; // Make the Bread Bread sub_bread = new Bread.BreadBuilder("medium").setBake("mild").build(); // Add Sauces Sauce sub_sauce = new Sauce.SauceBuilder().addChilli().addMayonnaise().build(); // Addons Addons sub_addons = new Addons.AddonsBuilder().addCheese().addVeggies().build(); // Salad Salad sub_salad = new Salad.SaladBuilder().addTomatoes().addCapsicum().addCarrot().build(); // Calculate Total Price total_price = sub_bread.getPrice() + sub_sauce.getPrice() + sub_addons.getPrice() + sub_salad.getPrice(); // Order Summary System.out.println("Your Sub:"); System.out.println(sub_bread); System.out.println(sub_sauce); System.out.println(sub_addons); System.out.println(sub_salad); System.out.println("\nTotal Price: " + total_price); } }
4d1e88e0d2151a592a7c50f4dc7d5921107913eb
[ "Java" ]
18
Java
vineethk123/Design-Patterns-Assignment
f3ea6b1d61eee79b40c8230420b6448d8e0f4845
24a1b7b530fce120a654c946e026143782ac5b64
refs/heads/master
<file_sep>import { combineReducers } from "redux"; import dataHelpers from './dataHelpers'; export default combineReducers({ dataHelpers });<file_sep>export const LIST_DATA = "LIST_DATA"; export const GET_YEARS = "GET_YEARS"; export const UPDATE_DATA = "UPDATE_DATA"; export const SUCCESS_LAUNCH = "SUCCESS_LAUNCH"; export const SUCCESS_LANDING = "SUCCESS_LANDING";<file_sep>import React, { Component } from 'react' export default class Sidebar extends Component { constructor(props) { super(props); this.state = { oddYear: [], evenYear: [], years: [], active: true, activeID: 2020, successLaunch: 'True', successLanding: 'True' } } handleClick = (yr) => { this.setState({ activeID: yr }); this.props.getYears(yr) this.props.handleFilteredData() }; handleSuccessLaunch = (opt) => { this.setState({ successLaunch: opt }) this.props.getSuccessLaunch(opt) } handleSuccessLanding = (opt) => { this.setState({ successLanding: opt }) this.props.getSuccessLanding(opt) } componentDidMount() { const year = 2006; const years = Array.from(new Array(15), (val, index) => { return index + year }); this.setState({ years: years }) } render() { const { years } = this.state; const option = ['True', 'False'] return ( <div className="sidebar"> <div className="filter"> <h3>Filters</h3> <div className="field"> <input className="launchField" type="text" name="launchYear" placeholder="Launch Year" disabled /> </div> <div className="badges"> <div className="row"> <div className="column"> {(years && years.length > 0) && years.map((yrs) => { return <button className={`year ${this.state.activeID === yrs ? "active" : ""}`} onClick={() => this.handleClick(yrs)}> <label> {yrs} </label> </button> })} </div> </div> </div> <div className="field"> <input className="launchField" type="text" name="successLaunch" placeholder="Successful Launch" disabled /> </div> <div className="successbadges"> <div className="row"> <div className="column"> {option.map((opt) => { return <button className={`year ${this.state.successLaunch === opt ? "active" : ""}`} onClick={() => this.handleSuccessLaunch(opt)} > <label> {opt} </label> </button> })} </div> </div> </div> <div className="field"> <input className="launchField" type="text" name="successLanding" placeholder="Successful Landing" disabled /> </div> <div className="successbadges"> <div className="row"> <div className="column"> {option.map((opt) => { return <button className={`year ${this.state.successLanding === opt ? "active" : ""}`} onClick={() => this.handleSuccessLanding(opt)} > <label> {opt} </label> </button> })} </div> </div> </div> </div> </div> ) } }<file_sep>import React, { Component } from 'react' import Content from '../Components/Content'; import { connect } from 'react-redux'; import { getSpaceList } from '../api/apiHelpers'; import { LIST_DATA, UPDATE_DATA } from "../constants/ActionTypes"; export class ContentContainer extends Component { constructor(props) { super(props); this.state = { } } render() { const { launch_years, Space } = this.props; // const filterYear = Space.length > 0 && Space.filter((item) => { // console.log('item--------', item) // return item.launch_year == launch_years // }) // console.log('check((((((((((', filterYear ) return ( <Content Space={this.props.Space} handleFetchDetails={this.props.handleFetchDetails} launch_years={this.props.launch_years} successLaunch={this.props.successLaunch} successLanding={this.props.successLanding} // filterYear={filterYear} // handleFilteredData={this.props.handleFilteredData} /> ) } } const mapStateToProps = store => { console.log('store in content container', store.dataHelpers) return { Space: store.dataHelpers.space, launch_years: store.dataHelpers.years, successLaunch: store.dataHelpers.successLaunch, successLanding: store.dataHelpers.successLanding }; }; const mapDispatchToProps = dispatch => { return { handleFetchDetails: () => { getSpaceList() .then(data => dispatch({ type: LIST_DATA, payload: data })) } } }; export default connect(mapStateToProps, mapDispatchToProps)(ContentContainer);<file_sep>import React, { Component } from 'react' export default class Content extends Component { constructor(props) { super(props); this.state = { } } componentDidMount = () => { this.props.handleFetchDetails(); } render() { const { Space, launch_years, successLaunch, successLanding } = this.props; const checkData = Space.length > 0 && Space.filter(el => { const landingData = el.rocket.first_stage.cores[0].land_success == null ? false : true; return el.launch_year == launch_years && el.launch_success == successLaunch && landingData == successLanding }) return ( <div className="content"> <div className="contentRow"> {checkData.length > 0 ? (checkData.map((space, i) => { return ( <div className="contentColumn"> <div className="imageContent"> <img src={space.links.mission_patch} className="image" /> </div> <div className="details"> <div className="detailHeading"> <label>{space.mission_name}</label> </div> <div className="detailContent"> <label className="mission">Mission Ids:</label> {space.mission_id.length > 0 ? space.mission_id.map((id) => { return <ul className="missionList"> <li>{id}</li> </ul> }) : <span className="answer"> {"-"} </span>} <div className="detailRow"> <span>Launch Year: &nbsp;</span> <span className="answer">{space.launch_year}</span> </div> <div className="detailRow"> <span>Successful Launch: &nbsp;</span> <span className="answer">{space.launch_success == true ? "true" : "false"}</span> </div> <div className="detailRow"> <span>Successful Landing: &nbsp;</span> <span className="answer">{space.rocket.first_stage.cores[0].land_success == true ? "true" : "false"}</span> </div> </div> </div> </div> ) })) : <div class="alert"> <strong>Alert!</strong> In {launch_years} there is no success launch nor success landing. </div> } </div> </div> ) } } <file_sep>import { LIST_DATA, GET_YEARS, UPDATE_DATA, SUCCESS_LAUNCH, SUCCESS_LANDING } from "../constants/ActionTypes"; const initialState = { space: [], years: '2020', successLaunch: 'True' && true, successLanding: 'True' && true, loading: true } export default (state = initialState, action) => { console.log('action.type', action.type) switch (action.type) { case LIST_DATA: return Object.assign({}, state, { space: action.payload }) case GET_YEARS: return Object.assign({}, state, { years: action.payload }) case SUCCESS_LAUNCH: return Object.assign({}, state, { successLaunch: action.payload == "True" ? true : false }) case SUCCESS_LANDING: return Object.assign({}, state, { successLanding: action.payload == "True" ? true : false }) // case UPDATE_DATA: // console.log('state', state) // const filterYear = state.space.length > 0 && state.space.filter((item) => { // return item.launch_year == state.years // }) // return Object.assign({}, state, { // ...state, // space: filterYear // }) default: return state; } };<file_sep>import React, { Component } from 'react' import Sidebar from '../Components/Sidebar'; import { connect } from "react-redux"; import { GET_YEARS, SUCCESS_LANDING, SUCCESS_LAUNCH, UPDATE_DATA } from "../constants/ActionTypes"; class SidebarContainer extends Component { constructor(props) { super(props); this.state = { } } render() { return ( <Sidebar getYears={this.props.getYears} getSuccessLaunch={this.props.getSuccessLaunch} getSuccessLanding={this.props.getSuccessLanding} handleFilteredData={this.props.handleFilteredData} /> ) } } export const mapStateToProps = store => { return { }; }; export const mapDispatchToProps = dispatch => { return { getYears: (data) => { dispatch({ type: GET_YEARS, payload: data }) }, getSuccessLaunch: (data) => { dispatch({ type: SUCCESS_LAUNCH, payload: data }) }, getSuccessLanding: (data) => { dispatch({ type: SUCCESS_LANDING, payload: data }) }, handleFilteredData: (data) => { dispatch({ type: UPDATE_DATA, payload: data }) } } }; export default connect(mapStateToProps, mapDispatchToProps)(SidebarContainer);
2279c373f1c1272e141b599d469ecd7006a1d347
[ "JavaScript" ]
7
JavaScript
Sharrumathi/SpaceX
8ef4aa374053613cde68e90824ee4c3b7618e0e5
25d376b7e5055d8e31e3363757f00c9b29b4ec4f
refs/heads/master
<file_sep>class Log < ActiveRecord::Base validates_length_of :entry, :minimum => 2 class << self def find_today Log.find( :all, :conditions => ["created_at BETWEEN ? AND ?", Date.today, Date.today + 1 ], :order => "created_at ASC" ) end def find_past Log.find(:all, :select => 'DISTINCT date', :order => "created_at DESC") end end end<file_sep>require 'rubygems' require 'redcloth' module Merb module GlobalHelpers def textile(text) RedCloth.new(text).to_html end def log_permalink(log) "log-#{log.id}-#{log.created_at.strftime("%m-%d-%Y")}" end def time_of_day(date) "#{relative_date(date)}::#{date.strftime("%I:%M %p")}" end def past_logs Log.find_past end end end <file_sep>class Logs < Application def index @logs = Log.find_today render end def view @logs = Log.find_all_by_date(params[:id]) render end def create Log.create!( :entry => params[:entry], :date => Date.today.strftime("%m-%d-%Y") ) redirect url( :action => "index" ) end end <file_sep>= Hacking Log Personal code/solution log Copyright (c) 2008 <NAME> <carlosgab<EMAIL>>, released under the MIT license project page: http://github.com/CarlosGabaldon/hacking-log/ project repo: git://github.com/CarlosGabaldon/hacking-log.git = SET UP ~ $ sudo gem install merb activerecord merb_activerecord merb_helpers rspec merb_rspec ~ $ git clone git://github.com/CarlosGabaldon/hacking-log.git ~ $ cd ./hacking-log ~/hacking-log $ rake db:create:all ~/hacking-log $ rake db:migrate ~/hacking-log $ rake db:test:clone ~/hacking-log $ rake specs ~/hacking-log $ merb ~ $ open http://localhost:4000/logs/ <file_sep>require File.join( File.dirname(__FILE__), "..", "spec_helper" ) describe Log do it "should NOT be valid when new" do log = Log.new log.should_not be_valid end it "should require at least two entry characters to be valid" do log = Log.new log.should_not be_valid log.errors.on( :entry ).should include( "is too short (minimum is 2 characters)" ) end end<file_sep>module Merb module LogsHelper end end<file_sep>require File.join(File.dirname(__FILE__), "..", 'spec_helper.rb') describe Logs, "#index" do it "should respond correctly" do dispatch_to( Logs, :index ).should respond_successfully end end describe Logs, "#create" do before( :each ) do @params = { :date => Date.today.strftime("%m-%d-%Y") , :entry => "I was working though this issue today with MySQL.." } end it "should redirect to #index after successfully creating a Log" do lambda { dispatch_to( Logs, :create, @params ).should redirect_to( "/logs/index" ) }.should change( Log, :count ) end it "should raise an exception when insufficient entry text is submitted" do lambda { dispatch_to( Logs, :create ).should redirect_to( "/logs/index" ) }.should raise_error( ActiveRecord::RecordInvalid ) end end <file_sep>require File.join(File.dirname(__FILE__), "..", "..", "spec_helper.rb") describe "logs/index" do before( :each ) do @controller = Logs.new( fake_request ) @logs = [Log.create( :entry => "I started playing with Merb today..", :date => Date.today.strftime("%m-%d-%Y") , :created_at => Time.now ), Log.create( :entry => "I had some issues with Merb..", :date => Date.today.strftime("%m-%d-%Y") , :created_at => Time.now )] @controller.instance_variable_set( :@logs, @logs ) @entry = @controller.render( :index ) end it "should have a containing pre for the line numbers" do @entry.should have_selector( "pre.textmate-source-numbers" ) end it "should have a containing div for the logs" do @entry.should have_selector( "div.logs" ) end after( :each ) do Log.destroy_all end end
5c7f2258325956dc01bf41772b57d3e2089eade0
[ "RDoc", "Ruby" ]
8
Ruby
CarlosGabaldon/hacking-log
033928e3f94a7d345f3db5f43386596dd6ad1110
9498fbc65e5af45852fcad67ea497e0b2d5655d8
refs/heads/master
<file_sep># Change log for WooCommerce Razer Merchant Services Normal Plugin ## v3.0.0 - Mar 13, 2020 - Release version 3.0.0 **Updates:** - Rebrand to Razer Merchant Services. ## v2.7.1 - Apr 18, 2019 **Bug Fix:** - Prevent duplicate record update into system after succeed payment. ## v2.7.0 - Apr 16, 2019 - Release version 2.7.0 **Updates:** - Implement function to handle response. - Ordering plugins: - Support ordering plugins like Sequential Order Numbers and Sequential Order Numbers Pro. - Payment title: - Showing channel instead of gateway title in order summary, invoice, etc. ## v2.6.0 - Apr 2, 2019 - Release version 2.6.0 **Updates:** - Update author & plugin link. - Restructure response handling. - When failed response handling, inquiry before update record. ## v2.5.1 - Oct 22, 2018 **Bug Fix:** - Order status updating in returnURL handling. ## v2.5.0 - Oct 19, 2018 - Release version 2.5.0 **Updates:** - Parameter naming: - change type to account_type - Algorithm optimizing: - payment url definition. ## v2.4.1 - Jul 9, 2018 **Bug Fix:** - NBCB parameter handling - check isset NBCB parameter. ## v2.4.0 - Jun 7, 2018 - Release version 2.4.0 **Bug Fix:** - Redirecting to merchant site after payment. ## v2.3.7 - Apr 13, 2018 **Bug Fix:** - Fixing syntax error. ## v2.3.6 - Mar 29, 2018 **Updates:** - Addon condition in returnURL handling. ## v2.3.5 - Feb 23, 2018 **Updates:** - Addon returnIPN for sandbox environment. ## v2.3.4 - Feb 22, 2018 **Updates:** - Addon sandbox feature. ## v2.3.4 - Sept 27, 2017 **Bug Fix:** - Admin Configuration Missing Message. ## v2.3.3 - Sept 21, 2017 **Updates:** - Addon secret key feature. ## v2.3.2 - Jun 23, 2017 **Bug Fix:** - Return URL correction. ## v2.3.1 - Oct 22, 2015 **Bug Fix:** - Admin Configuration Missing Message ## v2.3.1 - Oct 12, 2015 **Bug Fix:** - URL correction ## v2.3.0 - Jun 9, 2015 - Release MOLPay Normal Integration Plugin for WooCommerce<file_sep># Change log for WP eCommerce MOLPay Normal Plugin ## v2.1.1 - May 20, 2016 **Bug Fix:** - Order Information Correction - URL correction ## v2.1.0 - Jun 9, 2015 - Release MOLPay Normal Integration Plugin for WP eCommerce<file_sep><?php /** * MOLPay Wordpress e-Commerce Plugin * * @package Payment Method * @author MOLPay Technical Team <<EMAIL>> * @version 2.1.1 * */ $nzshpcrt_gateways[$num] = array( 'name' => 'MOLPay Malaysia Online Payment Gateway', 'display_name' => 'MOLPay Malaysia Online Payment Gateway', 'internalname' => 'molpay', 'function' => 'gateway_molpay', 'form' => 'form_molpay', 'submit_function' => 'submit_molpay' ); /** * Initialize the order if MOLPay payment method was selected * * @global object $wpdb * @global object $wp_object_cache * @param type $seperator * @param int $sessionid * @return void */ function gateway_molpay($seperator, $sessionid) { global $wpdb, $wp_object_cache; $ob_cache = $wp_object_cache->cache; $cur = $ob_cache['options']['alloptions']; $cur_type = $cur['currency_type']; $cur_sql = "SELECT * FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id`= ".$cur_type." LIMIT 1"; $cur_res = $wpdb->get_results($cur_sql,ARRAY_A) ; $cur_code = $cur_res[0]['code']; $cur_code = (strnatcasecmp($cur_code,"myr")=="0")? "rm" : strtolower($cur_code); $purchase_log_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `sessionid`= ".$sessionid." LIMIT 1"; $purchase_log = $wpdb->get_results($purchase_log_sql,ARRAY_A); $cart_sql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`='".$purchase_log[0]['id']."'"; $cart = $wpdb->get_results($cart_sql,ARRAY_A) ; $molpay_get_url = get_option('molpay_url'); $data['merchant_id'] = get_option('molpay_merchant_id'); $data['verify_key'] = get_option('molpay_vkey'); $data['returnurl'] = get_option('transact_url'); $data['callbackurl'] = get_option('transact_url'); $molpay_url = "https://www.onlinepayment.com.my/MOLPay/pay/" . $data['merchant_id'] . "/"; //User details if($_POST['collected_data'][get_option('molpay_form_first_name')] != '') { $data['f_name'] = $_POST['collected_data'][get_option('molpay_form_first_name')]; } if($_POST['collected_data'][get_option('molpay_form_last_name')] != "") { $data['s_name'] = $_POST['collected_data'][get_option('molpay_form_last_name')]; } if($_POST['collected_data'][get_option('molpay_form_address')] != '') { $data['street'] = str_replace("\n",', ', $_POST['collected_data'][get_option('molpay_form_address')]); } if($_POST['collected_data'][get_option('molpay_form_city')] != '') { $data['city'] = $_POST['collected_data'][get_option('molpay_form_city')]; } if(preg_match("/^[a-zA-Z]{2}$/",$_SESSION['selected_country'])) { $data['country'] = $_SESSION['selected_country']; } //Get user email $email_data = $wpdb->get_results("SELECT `id`,`type` FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `type` IN ('email') AND `active` = '1'",ARRAY_A); foreach((array)$email_data as $email) { $data['email'] = $_POST['collected_data'][$email['id']]; } if(($_POST['collected_data'][get_option('email_form_field')] != null) && ($data['email'] == null)) { $data['email'] = $_POST['collected_data'][get_option('email_form_field')]; } //collect item(s) in cart information $prod_sql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`='".$cart[0]['purchaseid']."'"; $prod_res = $wpdb->get_results($prod_sql,ARRAY_A) ; $prod_size = sizeof($prod_res); for ($i=0; $i<$prod_size; $i++) { $p_name[] = $prod_res[$i]['name']." x ".$prod_res[$i]['quantity']; } if($p_name){ $p_desc = implode("\n",$p_name); } $ship_sql = "SELECT form_id,value FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE `log_id`='".$cart[0]['purchaseid']."' "; $ship_res = $wpdb->get_results($ship_sql,ARRAY_A); $size_ship = sizeof($ship_res); for($k = 0; $k < $size_ship; $k++) { $form_id = $ship_res[$k]['form_id']; switch($form_id) { // ------------------- billing information ------------------- //Billing first name case "2" : $b_name = $ship_res[$k]['value']; break; //Billing last name case "3" : $b_name.= " ".$ship_res[$k]['value']; break; //Billing contact case "18" : $b_fon = $ship_res[$k]['value']; break; //Billing address case "4" : $b_address = $ship_res[$k]['value']; break; //Billing city case "5" : $b_city = $ship_res[$k]['value']; break; //Billing state case "6" : $b_state = $ship_res[$k]['value']; break; //Billing country case "7" : $b_county = $ship_res[$k]['value']; break; //Billing postcode case "8" : $b_postcode = $ship_res[$k]['value']; break; // ------------------- shipping information ------------------- // case "11" : $s_name = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[0]['value']; $_SESSION['shippingSameBilling'] = 1; break; case "12" : $s_name2 = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[1]['value']; break; case "13" : $s_address = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[2]['value']; break; case "14" : $s_address2 = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[3]['value']; break; case "15" : $s_address3 = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[4]['value']; break; case "16" : $s_address4 = (strlen(preg_replace('/\s+/', '', $ship_res[$k]['value'])) != 0)? $ship_res[$k]['value'] : $ship_res[5]['value']; break; default: echo ""; } } //Construct information about buying $desc .= "------------------------\nProduct(s) Information\n------------------------\n"; $desc .= $p_desc . "\n"; $desc .= "------------------------\nShipping Information\n------------------------\n"; $desc .= $s_name . ' ' . $s_name2; $desc .= "\n" . $s_address . "\n" . $s_address2 . "\n" . $s_address3 . "\n" . $s_address4; $data['product_price'] = $total_price; //This data cannot be used in MOLPay system $data['amount'] = $purchase_log[0]['totalprice']; $data['orderid'] = $purchase_log[0]['id']; $data['bill_mobile'] = $b_fon; $data['bill_name'] = $b_name; $data['bill_email'] = $data['email']; $data['bill_desc'] = $desc; $data['currency'] = $cur_code; $data['country'] = "MY"; $data['returnurl'] = $data['returnurl']; $data['vcode'] = md5($data['amount'] . $data['merchant_id'] . $data['orderid'] . $data['verify_key']); //Generate verfication code //Create Form to post to MOLPay Online Payment Gateway $output= "<center><form id='molpay_form' name='molpay_form' method='post' action='$molpay_url'>\n"; foreach($data as $n => $v) { $output .= "<input type='hidden' name='$n' value='$v' />\n"; } $plugins_url = plugins_url(); $output .= "<br><br>"; $output .= "<input type='image' src='$plugins_url/wp-e-commerce/images/molpay_logo.gif' name='submit'></form>"; $output .= "<br><input type='image' src='$plugins_url/wp-e-commerce/images/connect_molpay.gif' width='44' length='44'>"; $output .= "<br><br><font face='arial' size='2'>Please wait for a while.. You'll redirect to MOLPay Online Payment Gateway.</font></center>"; //flush all the form to the browser view echo($output); if(get_option('molpay_debug') == 0) { //Auto submit javascript echo "<script language='javascript'type='text/javascript'>setTimeout(\"document.getElementById('molpay_form').submit()\",1500);</script>"; } exit(); } /** * Received status about the order * * @global object $wpdb */ function nzshpcrt_molpay_callback() { global $wpdb; //Check skey $key0 = md5($_REQUEST['tranID'] . $_REQUEST['orderid'] . $_REQUEST['status'] . get_option('molpay_merchant_id') . $_REQUEST['amount'] . $_REQUEST['currency']); $key1 = md5($_REQUEST['paydate'] . get_option('molpay_merchant_id') . $key0 . $_REQUEST['appcode'] . get_option('molpay_vkey')); if(isset($_REQUEST['skey']) && $_REQUEST['skey'] == $key1) { $data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `id` = ".$_REQUEST['orderid'].""); $ship_res = molpay_inline_classes_object_function::query_data($wpdb, $_REQUEST['orderid']); $_POST['sessionid'] = $sessionid = $data->sessionid; $transid = $_REQUEST['tranID']; $retStatus = $_REQUEST['status']; $url = get_option('transact_url') . "?sessionid=" . $sessionid; if($retStatus == '00') { $data = array( 'processed' => 3, 'transactid' => $transid, 'date' => time() ); $where = array( 'sessionid' => $sessionid ); $format = array( '%d', '%s', '%s' ); $wpdb->update( WPSC_TABLE_PURCHASE_LOGS, $data, $where, $format ); transaction_results($sessionid, false, $transid); $bodyContent = " MOLPay Plugin Auto-Sender\n\n Be inform that we have capture for payment : \n Order ID : " . $_REQUEST['orderid'] . "\n Approval code : " . $_REQUEST['appcode'] . "\n Amount : " . $_REQUEST['currency'] . $_REQUEST['amount'] . "\n\n --------------------------------------------------------------\n Buyer Name : " . $ship_res[0]['value'] . ' ' . $ship_res[1]['value'] . "\n Buyer Phone : " . $ship_res[15]['value'] . "\n Buyer Email : " . $ship_res[7]['value'] . "\n Buyer Address : " . $ship_res[2]['value'] . ', ' . $ship_res[6]['value'] . ', ' . $ship_res[3]['value'] . ', ' . $ship_res[4]['value'] . "\n Shipping Name : " . $ship_res[8]['value'] . ' ' . $ship_res[9]['value'] . "\n Shipping Address : " . $ship_res[10]['value'] . ', ' . $ship_res[14]['value'] . ', ' . $ship_res[11]['value'] . ', ' . $ship_res[12]['value'] . "\n "; wp_mail( get_option('admin_email'), 'Accepted Payment Notification | MOLPay', $bodyContent); } else if($retStatus == '11') { $data = array( 'processed' => 2, 'transactid' => $transid, 'date' => time() ); $where = array( 'sessionid' => $sessionid ); $format = array( '%d', '%s', '%s' ); $wpdb->update( WPSC_TABLE_PURCHASE_LOGS, $data, $where, $format ); transaction_results($sessionid, false, $transid); } echo '<script>window.location.href = "'.$url.'"</script>'; } //Callback else if (isset($_REQUEST['nbcb'])) { $key0 = md5($_REQUEST['tranID'].$_REQUEST['orderid'].$_REQUEST['status'].get_option('molpay_merchant_id').$_REQUEST['amount'].$_REQUEST['currency']); $key1 = md5($_REQUEST['paydate'].get_option('molpay_merchant_id').$key0.$_REQUEST['appcode'].get_option('molpay_vkey')); if( $skey != $key1 ) $status= -1; switch($status) { case '00': $data = array( 'processed' => 3, 'transactid' => $tranID, 'date' => time() ); $where = array( 'sessionid' => $sessionid ); $format = array( '%d', '%s', '%s' ); $wpdb->update( WPSC_TABLE_PURCHASE_LOGS, $data, $where, $format ); break; case '11': // if it fails, delete it -- changed status to job dispatched/closed order (2009 April 15) $data = array( 'processed' => 2, 'transactid' => $tranID, 'date' => time() ); $where = array( 'sessionid' => $sessionid ); $format = array( '%d', '%s', '%s' ); $wpdb->update( WPSC_TABLE_PURCHASE_LOGS, $data, $where, $format ); break; default: // do nothing, safest course of action here. break; } } //Either merchant missconfigure the merchantID or vcode else if(isset($_REQUEST['skey']) && $_REQUEST['skey'] != $key1) { echo '<h1>There was an error during processing the information</h1>'; echo '<p>Incorrect merchantID or vcode was provided. Please recheck!'; } } function nzshpcrt_molpay_results() { if($_POST['orderid'] !='' && $_GET['sessionid'] == '') { $_GET['sessionid'] = $_POST['sessionid']; } } function submit_molpay() { if($_POST['molpay_merchant_id'] != null) { update_option('molpay_merchant_id', $_POST['molpay_merchant_id']); } if($_POST['molpay_vkey'] != null) { update_option('molpay_vkey', $_POST['molpay_vkey']); } if($_POST['molpay_url'] != null) { update_option('molpay_url', $_POST['molpay_url']); } if($_POST['molpay_debug'] != null) { update_option('molpay_debug', $_POST['molpay_debug']); } foreach((array)$_POST['molpay_form'] as $form => $value) { update_option(('molpay_form_'.$form), $value); } return true; } function form_molpay() { $select_currency[get_option('molpay_curcode')] = "selected='true'"; $molpay_debug = get_option('molpay_debug'); $molpay_debug1 = ""; $molpay_debug2 = ""; $output = " <tr> <td>Merchant ID</td> <td><input type='text' size='40' value='".get_option('molpay_merchant_id')."' name='molpay_merchant_id' /></td> </tr> <tr> <td>Verify Key</td> <td><input type='text' size='40' value='".get_option('molpay_vkey')."' name='molpay_vkey' /></td> </tr> <tr> <td>Return URL</td> <td><input type='text' size='40' value='".get_option('transact_url')."' name='molpay_return_url' readonly/></td> </tr> <tr> <td>Callback URL</td> <td><input type='text' size='40' value='".get_option('transact_url')."' name='molpay_callback_url' readonly/></td> </tr> "; return $output; } add_action('init', 'nzshpcrt_molpay_callback'); add_action('init', 'nzshpcrt_molpay_results'); /** * Add molpay class to prevent name conflict * */ class molpay_inline_classes_object_function { /** * Get the order cart details * * @param object $wpdb */ static function query_data( $wpdb, $orderId ) { $cart_sql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`='".$orderId."'"; $cart = $wpdb->get_results($cart_sql, ARRAY_A) ; $ship_sql = "SELECT form_id,value FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE `log_id`='".$cart[0]['purchaseid']."' "; return $wpdb->get_results($ship_sql, ARRAY_A); } } ?> <file_sep>Razer Merchant Services WordPress Plugin ===================== <img src="https://user-images.githubusercontent.com/38641542/74420753-eacb5600-4e86-11ea-9389-5427e4c6840d.jpg"> Razer Merchant Services Plugin for Wordpress developed by RMS technical team. Notes ----- Razer Merchant Services is not responsible for any problems that might arise from the use of this module. Use at your own risk. Please backup any critical data before proceeding. For any query or assistance, please email <EMAIL>. Installations for Wordpress Plugin ----------------------------- [ClassiPress Version 3.2.1](https://github.com/RazerMS/WordPress_WooCommerce_WP-eCommerce_ClassiPress/wiki/Installation-for-Classipress-Plugins) [WooCommerce Version 2.3.x & 2.4.x & 2.6.x & 3.4.x & 3.5.x](https://github.com/RazerMS/WordPress_WooCommerce_WP-eCommerce_ClassiPress/wiki/Installation-for-WooCommerce-Plugins) [WP-eCommerce Version 3.9.x](https://github.com/RazerMS/WordPress_WooCommerce_WP-eCommerce_ClassiPress/wiki/Installation-for-WP-e-Commerce-Plugins) Contribution ------------ You can contribute to this plugin by sending the pull request to this repository. Issues ------------ Submit issue to this repository or email to our <EMAIL> Support ------- Merchant Technical Support / Customer Care : <EMAIL> <br> Sales/Reseller Enquiry : <EMAIL> <br> Marketing Campaign : <EMAIL> <br> Channel/Partner Enquiry : <EMAIL> <br> Media Contact : <EMAIL> <br> R&D and Tech-related Suggestion : <EMAIL> <br> Abuse Reporting : <EMAIL> <file_sep><?php /* Plugin Name: Classipress MOLPay Plugin URI: http://www.github.com/MOLPay Description: MOLPay | The leading payment gateway in South East Asia Grow your business with MOLPay payment solutions & free features: Physical Payment at 7-Eleven, Seamless Checkout, Tokenization, Loyalty Program and more. Author: MOLPay Tech Team Author URI: http://www.molpay.com/ Version: 1.0 */ /** * Payment gateways admin values plugin * This is pulled into the WordPress backend admin * * * Array param definitions are as follows: * name = field name * desc = field description * tip = question mark tooltip text * id = database column name or the WP meta field name * css = any on-the-fly styles you want to add to that field * type = type of html field or tab start/end * req = if the field is required or not (1=required) * min = minimum number of characters allowed before saving data * std = default value. not being used * js = allows you to pass in javascript for onchange type events * vis = if field should be visible or not. used for dropdown values field * visid = this is the row css id that must correspond with the dropdown value that controls this field * options = array of drop-down option value/name combo * * */ /***** MOLPAY ADMIN SETTING *********/ function molpay_add_gateway_values(){ global $app_abbr, $action_gateway_values; $mol_gateway_values = array( array('type' => 'tab', 'tabname' => __('MOLPay', MOL_TD), 'id' => ''), array('name' => __('<b>MOLPay Online Payment</b>', MOL_TD), 'type' => 'title', 'id' => ''), array('name' => __('Enable MOLPay', MOL_TD), 'desc' => sprintf(__("<i>You must have a <a target='_new' href='%s'>MOLPay</a> account setup before using this feature.</i>", MOL_TD), 'http://www.molpay.com/v2/contact/merchant-enquiry'), 'tip' => __('Set this to yes if you want to enable MOLPay as a payment option on your site.'), 'id' => $app_abbr.'_enable_molpay', 'css' => 'width:100px;', 'std' => '', 'js' => '', 'type' => 'select', 'options' => array('yes' => __('Yes', MOL_TD), 'no' => __('No', MOL_TD))), array('name' => __('Merchant ID', MOL_TD), 'desc' => sprintf(__("<i>Please enter your MOLPay Merchant ID. You can to get this information in: <a target='_new' href='%s'>MOLPay Account</i>", MOL_TD), 'https://www.onlinepayment.com.my/MOLPay/'), 'tip' => '', 'id' => $app_abbr.'_molpay_merchant_id', 'css' => 'min-width:250px;', 'type' => 'text', 'req' => '', 'min' => '', 'std' => '', 'vis' => ''), array('name' => __('Verify Key', MOL_TD), 'desc' => sprintf(__("<i>Please enter your MOLPay Verify Key. You can to get this information in: <a target='_new' href='%s'>MOLPay Account</i>", MOL_TD), 'https://www.onlinepayment.com.my/MOLPay/'), 'tip' => '', 'id' => $app_abbr.'_molpay_verify_key', 'css' => 'min-width:250px;', 'type' => 'text', 'req' => '', 'min' => '', 'std' => '', 'vis' => ''), array('type' => 'tabend', 'id' => ''), ); // merge the above options with any passed into via the hook $action_gateway_values = array_merge((array)$action_gateway_values,(array)$mol_gateway_values); } add_action( 'cp_action_gateway_values', 'molpay_add_gateway_values' ); /** * add the option to the payment drop-down list on checkout * * @param array $order_vals contains all the order values * */ function molpay_add_gateway_option(){ global $app_abbr, $gateway_name; if(get_option($app_abbr.'_enable_molpay') == 'yes') echo '<option value="molpay">'.__('MOLPay (Visa/MasterCard,M2U,FPX,etc.)', MOL_TD).'</option>'; } add_action('cp_action_payment_method','molpay_add_gateway_option'); /** * do all the payment processing work here * @param array $order_vals contains all the order values **/ function gateway_molpay($order_vals){ global $wpdb, $gateway_name, $app_abbr, $post_url, $userdata; //if gateway wasn't selected then exit if($order_vals['cp_payment_method'] != 'molpay') return; $query = "SELECT * FROM $wpdb->users WHERE ID = ".$order_vals['user_id']; $stmt = $wpdb->get_results($query,ARRAY_A); $username = urlencode($stmt[0]['user_nicename']); $usermail = $stmt[0]['user_email']; //pack id $pack = $_POST['pack']; //get the merchant id $merchant_id = get_option($app_abbr.'_molpay_merchant_id'); //get the verify key $verify_key = get_option($app_abbr.'_molpay_verify_key'); $amount = $order_vals['item_amount']; $orderid = urlencode($order_vals['oid'].'U'.$order_vals['user_id'].'P'.$pack); $vcode = md5($amount.$merchant_id.$orderid.$verify_key); $molpay_url = "https://www.onlinepayment.com.my/MOLPay/pay/".$merchant_id.'/'; $return_url = add_query_arg(array('oid' => $order_vals['oid'], 'molpay' => $order_vals['oid'].'_'.$userdata->ID), CP_DASHBOARD_URL); $return_url = wp_nonce_url($return_url,$order_vals['oid']); ?> <form name='paymentform' method='post' action='<?php echo $molpay_url; ?>' accept-charset="utf-8"> <input type="hidden" name="bill_name" value="<?php echo $username; ?>" /> <input type="hidden" name="bill_email" value="<?php echo $usermail; ?>" /> <input type="hidden" name="bill_desc" value="Membership Purchase" /> <input type="hidden" name="merchant_id" value="<?php echo esc_attr( $merchant_id ); ?>"/> <input type="hidden" name="orderid" value="<?php echo $orderid; ?>"/> <input type="hidden" name="amount" value="<?php echo esc_attr( urlencode($order_vals['item_amount']) ); ?>" /> <input type="hidden" name="currency" value="<?php echo esc_attr( $curr_code ); ?>" /> <input type="hidden" name="vcode" value="<?php echo $vcode; ?>" /> <input type="hidden" name="_charset_" value="utf-8" /> <input type="hidden" name="returnurl" value="<?php echo esc_attr( $return_url ); ?>"/> <center><input type="submit" class="btn_orange" value="<?php _e('Continue &rsaquo;&rsaquo;', MOL_TD); ?>" /></center> <script type="text/javascript"> setTimeout("document.paymentform.submit();", 500); </script> </form> <?php } add_action( 'cp_action_gateway', 'gateway_molpay', 10, 1 ); /** * Payment processing for ad dashboard so ad owners can pay for unpaid ads **/ function dashboard_button_molpay($the_id,$type=''){ global $wpdb, $app_abbr, $userdata; if(get_option($app_abbr.'_enable_molpay') != "yes") return; get_currentuserinfo(); $pack = get_pack($the_id); //figure out the numbers of days this ad was listed for if(get_post_meta($the_id,'cp_sys_ad_duration',true)) $prun_period = get_post_meta($the_id,'cp_sys_ad_duration',true); else $prun_period = get_option('cp_prun_period'); //setup the variables based on purchase type if(isset($pack->pack_name) && stristr($pack->pack_status, 'membership')){ //membership buttons not supported return; }else{ $item_name = sprintf( __('Classified ad listing on %s for %s days', MOL_TD), get_bloginfo('name'), $prun_period); $item_number = get_post_meta($the_id, 'cp_sys_ad_conf_id', true); $amount = get_post_meta($the_id, 'cp_sys_total_ad_cost', true); $orderid = get_post_meta( $the_id, 'cp_sys_ad_conf_id', true ); $return_url = add_query_arg( array( 'oid' => $orderid, 'molpay' => $orderid .'_'. $userdata->ID ), CP_DASHBOARD_URL ); $return_url = wp_nonce_url( $return_url, $orderid ); } $username = urlencode($userdata->user_nicename); $usermail = $userdata->user_email; //get the merchant id $merchant_id = get_option($app_abbr.'_molpay_merchant_id'); //get the verify key $verify_key = get_option($app_abbr.'_molpay_verify_key'); $vcode = md5($amount.$merchant_id.$orderid.$verify_key); $molpay_url = "https://www.onlinepayment.com.my/MOLPay/pay/".$merchant_id.'/'; $return_url = add_query_arg(array('oid' => $orderid, 'molpay' => $orderid.'_'.$userdata->ID), CP_DASHBOARD_URL); $return_url = wp_nonce_url($return_url,$orderid); ?> <form name='paymentform' method='post' action='<?php echo $molpay_url; ?>' accept-charset="utf-8"> <input type="hidden" name="bill_name" value="<?php echo $username; ?>" /> <input type="hidden" name="bill_email" value="<?php echo $usermail; ?>" /> <input type="hidden" name="bill_desc" value="Purchase Ads" /> <input type="hidden" name="merchant_id" value="<?php echo esc_attr( $merchant_id ); ?>"/> <input type="hidden" name="orderid" value="<?php echo $orderid; ?>"/> <input type="hidden" name="amount" value="<?php echo esc_attr( urlencode($amount) ); ?>" /> <input type="hidden" name="currency" value="<?php echo esc_attr( $curr_code ); ?>" /> <input type="hidden" name="vcode" value="<?php echo $vcode; ?>" /> <input type="hidden" name="_charset_" value="utf-8" /> <input type="hidden" name="returnurl" value="<?php echo esc_attr( $return_url ); ?>"/> <center> <button style="cursor:pointer;"> <img src="<?php echo plugins_url('/images/molpay.png', __FILE__); ?>" style='width:50px;height:15px;' /> </button> <!-- <input type="submit" class="btn_orange" value="<?php _e('Continue &rsaquo;&rsaquo;', MOL_TD); ?>" /> --> </center> <script type="text/javascript"> setTimeout("document.paymentform.submit();", 500); </script> </form> <?php } add_action('cp_action_payment_button','dashboard_button_molpay',10,1); /** * Process Ads Payment **/ function molpay_to_merchant(){ global $wpdb, $app_abbr; $vkey = get_option($app_abbr.'_molpay_verify_key'); $_POST['treq'] = "1"; $skey = $_POST['skey']; $tranID = $_POST['tranID']; $domain = $_POST['domain']; $status = $_POST['status']; $amount = $_POST['amount']; $currency = $_POST['currency']; $paydate = $_POST['paydate']; $multiorder = $_POST['orderid']; $appcode = $_POST['appcode']; $error_code = $_POST['error_code']; $error_desc = $_POST['error_desc']; $channel = $_POST['channel']; $str1 = explode("U",$multiorder); $str2 = explode("P",$str1[1]); $orderid = $str1[0]; // $usrid = $str2[0]; $packid = $str2[1]; //backend acknowledge method for IPN while(list($k,$v) = each($_POST)){ $postData[] = $k."=".$v; } $postdata = implode("&",$postData); $url = "https://www.onlinepayment.com.my/MOLPAY/API/chkstat/returnipn.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); $output = curl_exec($ch); curl_close($ch); $key0 = md5($tranID.$multiorder.$status.$domain.$amount.$currency); $key1 = md5($paydate.$domain.$key0.$appcode.$vkey); if(isset($_GET['molpay']) && !empty($_GET['_wpnonce'])){ //step functions required to process orders include_once('wp-load.php'); include_once(TEMPLATEPATH.'/includes/forms/step-functions.php'); $pid = explode("_", $_GET['molpay']); if(!wp_verify_nonce($_GET['_wpnonce'],$pid[0])) return; $order_processed = false; $order = get_option("cp_order_".$pid[1]."_".$pid[0]); $the_user = get_userdata($pid[1]); if($status == "00"){ if($skey != $key1){ // Invalid transaction. $pay_status = "FAILED"; $pending_reason = ""; }else{ // Success $pay_status = "SUCCESSFUL"; $pending_reason = ""; // make sure the order sent from payment gateway is logged in the database and that the current user created item_number if (isset($order['order_id']) && $order['order_id'] == $pid[0]){ $the_user = get_userdata($order['user_id']); $order['order_id'] = $pid[0]; //activated membership or renew/extend membership pack $order_processed = appthemes_process_membership_order($the_user, $order); } if(!$order_processed){ $sql = $wpdb->prepare("SELECT p.ID, p.post_status FROM $wpdb->posts p, $wpdb->postmeta m WHERE p.ID = m.post_id AND p.post_status <> 'publish' AND m.meta_key = 'cp_sys_ad_conf_id' AND m.meta_value = %s ", $pid[0]); $newadid = $wpdb->get_row($sql); } } }else if($status == "22"){ // Pending transaction $pay_status = "PENDING"; $pending_reason = "AWAITING FOR PAYMENT"; }else{ // status 11 which is failed $pay_status = "FAILED"; $pending_reason = ""; } // if the ad is found, then publish it if ( $newadid ) { $the_ad = array(); $the_ad['ID'] = $newadid->ID; $the_ad['post_status'] = 'publish'; $ad_id = wp_update_post($the_ad); $ad_length = get_post_meta($ad_id, 'cp_sys_ad_duration', true); $ad_length = empty($ad_length) ? get_option('cp_prun_period') : $ad_length; // set the ad listing expiration date $ad_expire_date = date_i18n('m/d/Y H:i:s', strtotime('+' . $ad_length . ' days')); // don't localize the word 'days' //now update the expiration date on the ad update_post_meta($ad_id, 'cp_sys_expire_date', $ad_expire_date); $the_ad = get_post( $ad_id ); $tr_subject = __('Ad Purchase', MOL_TD); $tr_amount = get_post_meta($ad_id, 'cp_sys_total_ad_cost', true); }else{ $tr_amount = $order['total_cost']; if($tr_amount == ""){ $tr_subject = __('Ad Purchase', MOL_TD); $tr_amount = $amount; }else{ $ad_id = ''; $tr_subject = __('Membership Purchase', MOL_TD); } } $data = array( 'ad_id' => appthemes_clean($ad_id), 'user_id' => appthemes_clean($the_user->ID), 'first_name' => appthemes_clean($the_user->first_name), 'last_name' => appthemes_clean($the_user->last_name), 'payer_email' => appthemes_clean($the_user->user_email), 'residence_country' => '', 'transaction_subject' => appthemes_clean($pid[0]), 'item_name' => appthemes_clean($tr_subject), 'item_number' => appthemes_clean($pid[0]), 'payment_type' => $channel, 'payer_status' => '', 'payer_id' => '', 'receiver_id' => '', 'parent_txn_id' => '', 'txn_id' => appthemes_clean($pid[0]), 'mc_gross' => appthemes_clean($tr_amount), 'mc_fee' => '', 'payment_status' => $pay_status, 'pending_reason' => $pending_reason, 'txn_type' => '', 'tax' => '', 'mc_currency' => $currency, 'reason_code' => $status, 'custom' => appthemes_clean($pid[0]), 'test_ipn' => '', 'payment_date' => current_time('mysql'), 'create_date' => current_time('mysql'), ); // check and make sure this transaction hasn't already been added $item_number = $wpdb->get_var($wpdb->prepare("SELECT item_number FROM $wpdb->cp_order_info WHERE item_number = %s LIMIT 1", appthemes_clean($pid[0]))); $paystat = $wpdb->get_var($wpdb->prepare("SELECT payment_status FROM $wpdb->cp_order_info WHERE item_number = %s", $item_number)); if($item_number){ if($paystat == "SUCCESSFUL" && $status == "11"){ return; }else{ $wpdb->update($wpdb->cp_order_info,$data,array("item_number"=>$item_number)); } }else{ $wpdb->insert($wpdb->cp_order_info,$data); } } } add_action('init', 'molpay_to_merchant'); /* * This part is callback function for MOLPay */ function molpay_response_callback(){ if(isset($_REQUEST['mode'])){ if($_REQUEST['mode'] == "callback"){ global $wpdb, $app_abbr; $vkey = get_option($app_abbr.'_molpay_verify_key'); $nbcb = $_POST['nbcb']; $skey = $_POST['skey']; $tranID = $_POST['tranID']; $domain = $_POST['domain']; $status = $_POST['status']; $amount = $_POST['amount']; $currency = $_POST['currency']; $paydate = $_POST['paydate']; $multiorder = $_POST['orderid']; $appcode = $_POST['appcode']; $error_code = $_POST['error_code']; $error_desc = $_POST['error_desc']; $channel = $_POST['channel']; $str1 = explode("U",$multiorder); $str2 = explode("P",$str1[1]); $orderid = $str1[0]; $_REQUEST['oid'] = $orderid; $usrid = $str2[0]; $packid = $str2[1]; $key0 = md5($tranID.$multiorder.$status.$domain.$amount.$currency); $key1 = md5($paydate.$domain.$key0.$appcode.$vkey); //step functions required to process orders include_once('wp-load.php'); include_once(TEMPLATEPATH.'/includes/forms/step-functions.php'); // $pid = explode("_", $_GET['molpay']); // if(!wp_verify_nonce($_GET['_wpnonce'],$pid[0])) // return; $order_processed = false; $order = get_option("cp_order_".$usrid."_".$orderid); $the_user = get_userdata($usrid); if($status == "00"){ if($skey != $key1){ // Invalid transaction. $pay_status = "FAILED"; $pending_reason = ""; }else{ // Success $pay_status = "SUCCESSFUL"; $pending_reason = ""; //add meta options for callback function only if(!is_array($order) || count($order) == 0){ $pack = $wpdb->get_results("SELECT * FROM $wpdb->cp_ad_packs WHERE pack_id = ".$packid); $package = json_decode(json_encode($pack),true); $spack = array_pop($package); $opt_name = "cp_order_".$usrid."_".$orderid; $add_on = array( "user_id" => $usrid, "order_id" => $orderid, "option_order_id" => $opt_name, "total_cost" => $amount, ); $addin = array_merge($add_on, $spack); $opt_val = serialize($addin); $opt_data = array( "option_name" => $opt_name, "option_value" => $opt_val, "autoload" => "yes", ); $tblname = $wpdb->prefix.'options'; $wpdb->insert($tblname,$opt_data); $order = unserialize($opt_val); } // make sure the order sent from payment gateway is logged in the database and that the current user created item_number if (isset($order['order_id']) && $order['order_id'] == $orderid){ $the_user = get_userdata($order['user_id']); $order['order_id'] = $orderid; //activated membership or renew/extend membership pack $order_processed = appthemes_process_membership_order($the_user, $order); } if(!$order_processed){ $sql = $wpdb->prepare("SELECT p.ID, p.post_status FROM $wpdb->posts p, $wpdb->postmeta m WHERE p.ID = m.post_id AND p.post_status <> 'publish' AND m.meta_key = 'cp_sys_ad_conf_id' AND m.meta_value = %s ", $orderid); $newadid = $wpdb->get_row($sql); } } }else if($status == "22"){ // Pending transaction $pay_status = "PENDING"; $pending_reason = "AWAITING FOR PAYMENT"; }else{ // status 11 which is failed $pay_status = "FAILED"; $pending_reason = ""; } // if the ad is found, then publish it if ( $newadid ) { $the_ad = array(); $the_ad['ID'] = $newadid->ID; $the_ad['post_status'] = 'publish'; $ad_id = wp_update_post($the_ad); $ad_length = get_post_meta($ad_id, 'cp_sys_ad_duration', true); $ad_length = empty($ad_length) ? get_option('cp_prun_period') : $ad_length; // set the ad listing expiration date $ad_expire_date = date_i18n('m/d/Y H:i:s', strtotime('+' . $ad_length . ' days')); // don't localize the word 'days' //now update the expiration date on the ad update_post_meta($ad_id, 'cp_sys_expire_date', $ad_expire_date); $the_ad = get_post( $ad_id ); $tr_subject = __('Ad Purchase', MOL_TD); $tr_amount = get_post_meta($ad_id, 'cp_sys_total_ad_cost', true); }else{ $tr_amount = $order['total_cost']; if($tr_amount == ""){ $tr_subject = __('Ad Purchase', MOL_TD); $tr_amount = $amount; }else{ $ad_id = ''; $tr_subject = __('Membership Purchase', MOL_TD); } } $data = array( 'ad_id' => appthemes_clean($ad_id), 'user_id' => appthemes_clean($the_user->ID), 'first_name' => appthemes_clean($the_user->first_name), 'last_name' => appthemes_clean($the_user->last_name), 'payer_email' => appthemes_clean($the_user->user_email), 'residence_country' => '', 'transaction_subject' => appthemes_clean($orderid), 'item_name' => appthemes_clean($tr_subject), 'item_number' => appthemes_clean($orderid), 'payment_type' => $channel, 'payer_status' => '', 'payer_id' => '', 'receiver_id' => '', 'parent_txn_id' => '', 'txn_id' => appthemes_clean($orderid), 'mc_gross' => appthemes_clean($tr_amount), 'mc_fee' => '', 'payment_status' => $pay_status, 'pending_reason' => $pending_reason, 'txn_type' => '', 'tax' => '', 'mc_currency' => $currency, 'reason_code' => $status, 'custom' => appthemes_clean($orderid), 'test_ipn' => '', 'payment_date' => current_time('mysql'), 'create_date' => current_time('mysql'), ); // check and make sure this transaction hasn't already been added $item_number = $wpdb->get_var($wpdb->prepare("SELECT item_number FROM $wpdb->cp_order_info WHERE item_number = %s LIMIT 1", appthemes_clean($orderid))); $paystat = $wpdb->get_var($wpdb->prepare("SELECT payment_status FROM $wpdb->cp_order_info WHERE item_number = %s", $item_number)); if($item_number){ if($paystat == "SUCCESSFUL" && $status == "11"){ return; }else{ $wpdb->update($wpdb->cp_order_info,$data,array("item_number"=>$item_number)); } }else{ $wpdb->insert($wpdb->cp_order_info,$data); } if($nbcb == 1){ echo "CBTOKEN:MPSTATOK"; exit; } } } } add_action('init','molpay_response_callback'); ?><file_sep># Change log for WooCommerce Razer Merchant Services Seamless Plugin for Sequential Order Numbers Pro ## v3.0.1 - Apr 21, 2020 - Release version 3.0.1 **Updates:** - Minor improvement on payment UI. ## v3.0.0 - Mar 13, 2020 - Release version 3.0.0 **Updates:** - Rebrand to Razer Merchant Services. - Update FPX channel logos in accordance to FPX Compliance. - Add support for e-wallet channels. - Remove FPX-TPA and MOLWallet channels. ## v2.6.0 - Apr 2, 2019 - Release version 2.6.0 **Updates:** - Update author & plugin link. - Restructure response handling. - When failed response handling, inquiry before update record. ## v2.5.2 - Oct 23, 2018 **Updates:** - Plugin naming changes. ## v2.5.1 - Oct 22, 2018 **Bug Fix:** - Order status updating in returnURL handling. - Missing parameter when submitting order. ## v2.5.0 - Oct 19, 2018 - Release version 2.5.0 **Updates:** - Addon Channel: - Cash-SAM - eNets - China Union Pay - Alipay - WeChatPay Cross Border - Remove Channel: - credit3 - Parameter naming: - change type to account_type - Algorithm optimizing: - payment url definition. ## v2.4.3 - Jul 9, 2018 **Bug Fix:** - NBCB parameter handling - check isset NBCB parameter. ## v2.4.2 - Jun 18, 2018 **Bug Fix:** - NBCB parameter handling - check callbackURL or notificationURL. ## v2.4.1 - Jun 7, 2018 **Updates:** - Remove error log feature. ## v2.4.0 - Jun 5, 2018 - Release MOLPay seamless plugin for sequential order numbers pro. <file_sep># Change log for WooCommerce Razer Merchant Services Seamless Plugin ## v3.0.1 - Apr 21, 2020 - Release version 3.0.1 **Updates:** - Minor improvement on payment UI. ## v3.0.0 - Mar 13, 2020 - Release version 3.0.0 **Updates:** - Rebrand to Razer Merchant Services. - Update FPX channel logos in accordance to FPX Compliance. - Add support for e-wallet channels. - Remove FPX-TPA and MOLWallet channels. ## v2.7.1 - Apr 18, 2019 **Bug Fix:** - Prevent duplicate record update into system after succeed payment. ## v2.7.0 - Apr 16, 2019 - Release version 2.7.0 **Updates:** - Implement function to handle response. - Ordering plugins: - Support ordering plugins like Sequential Order Numbers and Sequential Order Numbers Pro. - Payment title: - Showing channel instead of gateway title in order summary, invoice, etc. ## v2.6.0 - Apr 2, 2019 - Release version 2.6.0 **Updates:** - Update author & plugin link. - Restructure response handling. - When failed response handling, inquiry before update record. ## v2.5.1 - Oct 22, 2018 **Bug Fix:** - Order status updating in returnURL handling. - Missing parameter when submitting order. ## v2.5.0 - Oct 19, 2018 - Release version 2.5.0 **Updates:** - Addon Channel: - Cash-SAM - eNets - Unionpay - Alipay - WeChatPay Cross Border - Remove Channel: - credit3 - Parameter naming: - change type to account_type - Algorithm optimizing: - payment url definition. ## v2.4.4 - Aug 29, 2018 **Updates:** - Parameter naming: - change channel fpx_mb2u to maybank2u ## v2.4.3 - Jul 20, 2018 **Updates:** - Channel routing: - route online banking to fpx. ## v2.4.2 - Jul 9, 2018 **Bug Fix:** - NBCB parameter handling - check isset NBCB parameter. ## v2.4.1 - Jun 18, 2018 **Bug Fix:** - NBCB parameter handling - check callbackURL or notificationURL. ## v2.4.0 - Jun 7, 2018 - Release version 2.4.0 **Bug Fix:** - Redirecting to merchant site after payment. ## v2.3.17 - Apr 10, 2018 **Updates:** - Remove unused channel logo: - maybank2u ## v2.3.16 - Apr 9, 2018 **Bug Fix:** - Fixing syntax error. ## v2.3.15 - Apr 6, 2018 **Bug Fix:** - Channel logo src path correction. ## v2.3.14 - Mar 29, 2018 **Updates:** - Addon condition in returnURL handling. ## v2.3.13 - Jan 3, 2018 **Updates:** - Addon sandbox feature. - Channel routing: - maybank2u to FPX maybank ## v2.3.12 - Sept 27, 2017 **Updates:** - Addon secret key feature. ## v2.3.11 - Sept 13, 2017 **Updates:** - Addon phone number on submit parameters. ## v2.3.10 - May 29, 2017 **Bug Fix:** - Return URL correction. ## v2.3.9 - May 22, 2017 **Updates:** - MOLPay seamless JS library from 3.12 to latest. ## v2.3.8 - Apr 25, 2017 **Updates:** - MOLPay seamless JS library from 3.11 to 3.12. ## v2.3.7 - Apr 25, 2017 **Updates:** - Addon tcctype for credit card channel. ## v2.3.6 - Dec 29, 2016 **Updates:** - MOLPay seamless JS library from 3.7 to 3.11. - MOLPay Logo. ## v2.3.5 - Dec 29, 2016 **Bug Fix:** - Return URL correction. ## v2.3.4 - Jun 24, 2016 **Updates:** - MOLPay seamless JS library from 3.3 to 3.7. ## v2.3.3 - Nov 24, 2015 **Updates:** - Addon new channel: - credit ## v2.3.2 - Oct 22, 2015 **Bug Fix:** - Admin Configuration Missing Message. ## v2.3.1 - Sept 4, 2015 **Updates:** - Channel logo. - MOLPay seamless JS library from 3.0 to 3.3. ## v2.3.0 - Jun 9, 2015 - Release MOLPay Seamless Integration Plugin for WooCommerce<file_sep># Change log for WP ClassicPress MOLPay Normal Plugin ## v1.0 - Jun 5, 2015 - Release MOLPay Normal Integration Plugin for WP ClassiPress.<file_sep><?php /** * Razer Merchant Services WooCommerce Shopping Cart Plugin * * @author Razer Merchant Services Technical Team <<EMAIL>> * @version 3.0.0 * @example For callback : http://shoppingcarturl/?wc-api=WC_Molpay_Gateway * @example For notification : http://shoppingcarturl/?wc-api=WC_Molpay_Gateway */ /** * Plugin Name: WooCommerce Razer Merchant Services Seamless * Plugin URI: https://github.com/RazerMS/WordPress_WooCommerce_WP-eCommerce_ClassiPress * Description: WooCommerce Razer Merchant Services | The leading payment gateway in South East Asia Grow your business with Razer Merchant Services payment solutions & free features: Physical Payment at 7-Eleven, Seamless Checkout, Tokenization, Loyalty Program and more for WooCommerce * Author: Razer Merchant Services Tech Team * Author URI: https://merchant.razer.com/ * Version: 3.0.1 * License: MIT * Text Domain: wcmolpay * Domain Path: /languages/ * For callback : http://shoppingcarturl/?wc-api=WC_Molpay_Gateway * For notification : http://shoppingcarturl/?wc-api=WC_Molpay_Gateway * Invalid Transaction maybe is because vkey not found / skey wrong generated */ /** * If WooCommerce plugin is not available * */ function wcmolpay_woocommerce_fallback_notice() { $message = '<div class="error">'; $message .= '<p>' . __( 'WooCommerce Razer Merchant Services Gateway depends on the last version of <a href="http://wordpress.org/extend/plugins/woocommerce/">WooCommerce</a> to work!' , 'wcmolpay' ) . '</p>'; $message .= '</div>'; echo $message; } //Load the function add_action( 'plugins_loaded', 'wcmolpay_gateway_load', 0 ); /** * Load Razer Merchant Services gateway plugin function * * @return mixed */ function wcmolpay_gateway_load() { if ( !class_exists( 'WC_Payment_Gateway' ) ) { add_action( 'admin_notices', 'wcmolpay_woocommerce_fallback_notice' ); return; } //Load language load_plugin_textdomain( 'wcmolpay', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); add_filter( 'woocommerce_payment_gateways', 'wcmolpay_add_gateway' ); /** * Add Razer Merchant Services gateway to ensure WooCommerce can load it * * @param array $methods * @return array */ function wcmolpay_add_gateway( $methods ) { $methods[] = 'WC_Molpay_Gateway'; return $methods; } /** * Define the Razer Merchant Services gateway * */ class WC_Molpay_Gateway extends WC_Payment_Gateway { /** * Construct the Razer Merchant Services gateway class * * @global mixed $woocommerce */ public function __construct() { global $woocommerce; $this->id = 'molpay'; $this->icon = plugins_url( 'images/logo_RazerMerchantServices.png', __FILE__ ); $this->has_fields = false; $this->method_title = __( 'Razer Merchant Services', 'wcmolpay' ); $this->method_description = __( 'Proceed payment via Razer Merchant Services Seamless Integration Plugin', 'woocommerce' ); // Load the form fields. $this->init_form_fields(); // Load the settings. $this->init_settings(); // Define user setting variables. $this->title = $this->settings['title']; $this->ordering_plugin = $this->get_option('ordering_plugin'); $this->payment_title = $this->settings['payment_title']; $this->description = $this->settings['description']; $this->merchant_id = $this->settings['merchant_id']; $this->verify_key = $this->settings['verify_key']; $this->secret_key = $this->settings['secret_key']; $this->account_type = $this->settings['account_type']; // Define hostname based on account_type $this->url = ($this->get_option('account_type')=='1') ? "https://www.onlinepayment.com.my/" : "https://sandbox.merchant.razer.com/" ; $this->inquiry_url = ($this->get_option('account_type')=='1') ? "https://api.merchant.razer.com/" : "https://sandbox.merchant.razer.com/" ; // Define channel setting variables $this->credit = ($this->get_option('credit')=='yes' ? true : false); $this->fpx_mb2u = ($this->get_option('fpx_mb2u')=='yes' ? true : false); $this->fpx_cimbclicks = ($this->get_option('fpx_cimbclicks')=='yes' ? true : false); $this->fpx_hlb = ($this->get_option('fpx_hlb')=='yes' ? true : false); $this->fpx_rhb = ($this->get_option('fpx_rhb')=='yes' ? true : false); $this->fpx_amb = ($this->get_option('fpx_amb')=='yes' ? true : false); $this->fpx_pbb = ($this->get_option('fpx_pbb')=='yes' ? true : false); $this->fpx_abb = ($this->get_option('fpx_abb')=='yes' ? true : false); $this->fpx_bimb = ($this->get_option('fpx_bimb')=='yes' ? true : false); $this->fpx_abmb = ($this->get_option('fpx_abmb')=='yes' ? true : false); $this->fpx_bkrm = ($this->get_option('fpx_bkrm')=='yes' ? true : false); $this->fpx_bmmb = ($this->get_option('fpx_bmmb')=='yes' ? true : false); $this->fpx_bsn = ($this->get_option('fpx_bsn')=='yes' ? true : false); $this->fpx_hsbc = ($this->get_option('fpx_hsbc')=='yes' ? true : false); $this->fpx_kfh = ($this->get_option('fpx_kfh')=='yes' ? true : false); $this->fpx_ocbc = ($this->get_option('fpx_ocbc')=='yes' ? true : false); $this->fpx_scb = ($this->get_option('fpx_scb')=='yes' ? true : false); $this->fpx_uob = ($this->get_option('fpx_uob')=='yes' ? true : false); $this->Point_BCard = ($this->get_option('Point-BCard')=='yes' ? true : false); $this->dragonpay = ($this->get_option('dragonpay')=='yes' ? true : false); $this->NGANLUONG = ($this->get_option('NGANLUONG')=='yes' ? true : false); $this->paysbuy = ($this->get_option('paysbuy')=='yes' ? true : false); $this->cash_711 = ($this->get_option('cash-711')=='yes' ? true : false); $this->ATMVA = ($this->get_option('ATMVA')=='yes' ? true : false); $this->enetsD = ($this->get_option('enetsD')=='yes' ? true : false); $this->singpost = ($this->get_option('singpost')=='yes' ? true : false); $this->UPOP = ($this->get_option('UPOP')=='yes' ? true : false); $this->alipay = ($this->get_option('alipay')=='yes' ? true : false); $this->WeChatPay = ($this->get_option('WeChatPay')=='yes' ? true : false); $this->WeChatPayMY = ($this->get_option('WeChatPayMY')=='yes' ? true : false); $this->BOOST = ($this->get_option('BOOST')=='yes' ? true : false); $this->MB2U_QRPay_Push = ($this->get_option('MB2U_QRPay-Push')=='yes' ? true : false); $this->RazerPay = ($this->get_option('RazerPay')=='yes' ? true : false); $this->TNG_EWALLET = ($this->get_option('TNG-EWALLET')=='yes' ? true : false); $this->GrabPay = ($this->get_option('GrabPay')=='yes' ? true : false); // Transaction Type for Credit Channel $this->credit_tcctype = ($this->get_option('credit_tcctype')=='SALS' ? 'SALS' : 'AUTH'); // Actions. add_action( 'valid_molpay_request_returnurl', array( &$this, 'check_molpay_response_returnurl' ) ); add_action( 'valid_molpay_request_callback', array( &$this, 'check_molpay_response_callback' ) ); add_action( 'valid_molpay_request_notification', array( &$this, 'check_molpay_response_notification' ) ); add_action( 'woocommerce_receipt_molpay', array( &$this, 'receipt_page' ) ); //save setting configuration add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); // Payment listener/API hook add_action( 'woocommerce_api_wc_molpay_gateway', array( $this, 'check_ipn_response' ) ); // Checking if merchant_id is not empty. $this->merchant_id == '' ? add_action( 'admin_notices', array( &$this, 'merchant_id_missing_message' ) ) : ''; // Checking if verify_key is not empty. $this->verify_key == '' ? add_action( 'admin_notices', array( &$this, 'verify_key_missing_message' ) ) : ''; // Checking if secret_key is not empty. $this->secret_key == '' ? add_action( 'admin_notices', array( &$this, 'secret_key_missing_message' ) ) : ''; // Checking if account_type is not empty. $this->account_type == '' ? add_action( 'admin_notices', array( &$this, 'account_type_missing_message' ) ) : ''; } /** * Checking if this gateway is enabled and available in the user's country. * * @return bool */ public function is_valid_for_use() { if ( !in_array( get_woocommerce_currency() , array( 'MYR' ) ) ) { return false; } return true; } /** * Admin Panel Options * - Options for bits like 'title' and availability on a country-by-country basis. * */ public function admin_options() { ?> <h3><?php _e( 'Razer Merchant Services', 'wcmolpay' ); ?></h3> <p><?php _e( 'Razer Merchant Services works by sending the user to Razer Merchant Services to enter their payment information.', 'wcmolpay' ); ?></p> <table class="form-table"> <?php $this->generate_settings_html(); ?> </table><!--/.form-table--> <?php } /** * Gateway Settings Form Fields. * */ public function init_form_fields() { $this->form_fields = array( 'enabled' => array( 'title' => __( 'Enable/Disable', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( 'Enable Razer Merchant Services', 'wcmolpay' ), 'default' => 'yes' ), 'ordering_plugin' => array( 'title' => __( '<p style="color:red;">Installed Ordering Plugins</p>', 'wcmolpay' ), 'type' => 'select', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'Sequential Order Numbers', 'options' => array( '0' => __( 'Not install any ordering plugin', 'wcmolpay'), '1' => __( 'Sequential Order Numbers', 'wcmolpay' ), '2' => __( 'Sequential Order Numbers Pro', 'wcmolpay' ) ), 'description' => __( 'Please select correct ordering plugin as it will affect your order result!!', 'wcmolpay' ), 'desc_tip' => true, ), 'title' => array( 'title' => __( 'Title', 'wcmolpay' ), 'type' => 'text', 'description' => __( 'This controls the title which the user sees during checkout.', 'wcmolpay' ), 'default' => __( 'Razer Merchant Services', 'wcmolpay' ), 'desc_tip' => true, ), 'payment_title' => array( 'title' => __( 'Payment Title', 'wcmolpay'), 'type' => 'checkbox', 'label' => __( 'Showing channel instead of gateway title after payment.'), 'description' => __( 'This controls the payment method which the user sees after payment.', 'wcmolpay' ), 'default' => 'no', 'desc_tip' => true ), 'description' => array( 'title' => __( 'Description', 'wcmolpay' ), 'type' => 'textarea', 'description' => __( 'This controls the description which the user sees during checkout.', 'wcmolpay' ), 'default' => __( 'Razer Merchant Services', 'wcmolpay' ), 'desc_tip' => true, ), 'merchant_id' => array( 'title' => __( 'Merchant ID', 'wcmolpay' ), 'type' => 'text', 'description' => __( 'Please enter your Razer Merchant Services Merchant ID.', 'wcmolpay' ) . ' ' . sprintf( __( 'You can to get this information in: %sRazer Merchant Services Account%s.', 'wcmolpay' ), '<a href="https://portal.merchant.razer.com/" target="_blank">', '</a>' ), 'default' => '' ), 'verify_key' => array( 'title' => __( 'Verify Key', 'wcmolpay' ), 'type' => 'text', 'description' => __( 'Please enter your Razer Merchant Services Verify Key.', 'wcmolpay' ) . ' ' . sprintf( __( 'You can to get this information in: %sRazer Merchant Services Account%s.', 'wcmolpay' ), '<a href="https://portal.merchant.razer.com/" target="_blank">', '</a>' ), 'default' => '' ), 'secret_key' => array( 'title' => __( 'Secret Key', 'wcmolpay' ), 'type' => 'text', 'description' => __( 'Please enter your Razer Merchant Services Secret Key.', 'wcmolpay' ) . ' ' . sprintf( __( 'You can to get this information in: %sRazer Merchant Services Account%s.', 'wcmolpay' ), '<a href="https://portal.merchant.razer.com/" target="_blank">', '</a>' ), 'default' => '' ), 'account_type' => array( 'title' => __( 'Account Type', 'wcmolpay' ), 'type' => 'select', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'PRODUCTION', 'options' => array( '1' => __('PRODUCTION', 'wcmolpay' ), '2' => __( 'SANDBOX', 'wcmolpay' ) ) ), 'channel' => array( 'title' => 'Channel to be Enabled', 'type' => 'title', 'description' => '', ), 'credit' => array( 'title' => __( 'Credit Card/ Debit Card', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_mb2u' => array( 'title' => __( 'FPX Maybank (Maybank2u)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_cimbclicks' => array( 'title' => __( 'FPX CIMB Bank (CIMB Clicks)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_hlb' => array( 'title' => __( 'FPX Hong Leong Bank (HLB Connect)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_rhb' => array( 'title' => __( 'FPX RHB Bank (RHB Now)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_amb' => array( 'title' => __( 'FPX Am Bank (Am Online)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_pbb' => array( 'title' => __( 'FPX PublicBank (PBB Online)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_abb' => array( 'title' => __( 'FPX Affin Bank (Affin Online)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_bimb' => array( 'title' => __( 'FPX Bank Islam', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_abmb' => array( 'title' => __( 'FPX Alliance Bank (Alliance Online)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_bkrm' => array( 'title' => __( 'FPX Bank Kerjasama Rakyat Malaysia', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_bmmb' => array( 'title' => __( 'FPX Bank Muamalat', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_bsn' => array( 'title' => __( 'FPX Bank Simpanan Nasional (myBSN)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_hsbc' => array( 'title' => __( 'FPX Hongkong and Shanghai Banking Corporation', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_kfh' => array( 'title' => __( 'FPX Kuwait Finance House', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_ocbc' => array( 'title' => __( 'FPX OCBC Bank', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_scb' => array( 'title' => __( 'FPX Standard Chartered Bank', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'fpx_uob' => array( 'title' => __( 'FPX United Overseas Bank (UOB)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'Point-BCard' => array( 'title' => __( 'Point-BCard', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'dragonpay' => array( 'title' => __( 'Dragonpay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'NGANLUONG' => array( 'title' => __( 'NGANLUONG', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'paysbuy' => array( 'title' => __( 'PaysBuy', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'cash-711' => array( 'title' => __( '7-Eleven (Razer Cash)', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'ATMVA' => array( 'title' => __( 'ATM Transfer via Permata Bank', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'enetsD' => array( 'title' => __( 'eNETS', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'singpost' => array( 'title' => __( 'Cash-SAM', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'UPOP' => array( 'title' => __( 'China Union Pay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'alipay' => array( 'title' => __( 'Alipay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'WeChatPay' => array( 'title' => __( 'WeChatPay Cross Border', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'WeChatPayMY' => array( 'title' => __( 'WeChatPayMY', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'BOOST' => array( 'title' => __( 'Boost', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'MB2U_QRPay-Push' => array( 'title' => __( 'Maybank QRPay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'RazerPay' => array( 'title' => __( 'Razer Pay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'TNG-EWALLET' => array( 'title' => __( 'Touch `n Go eWallet', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'GrabPay' => array( 'title' => __( 'Grab Pay', 'wcmolpay' ), 'type' => 'checkbox', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'no' ), 'tcctype' => array( 'title' => 'Transaction Type for Credit Card / Debit Card Channel', 'type' => 'title', 'description' => '', ), 'credit_tcctype' => array( 'title' => __( 'Credit Card/ Debit Card', 'wcmolpay' ), 'type' => 'select', 'label' => __( ' ', 'wcmolpay' ), 'default' => 'SALS', 'options' => array( 'SALS' => __('SALS', 'wcmolpay' ), 'AUTH' => __( 'AUTH', 'wcmolpay' ) ) ) ); } /** * Generate the form. * * @param mixed $order_id * @return string */ public function generate_form( $order_id ) { $order = new WC_Order( $order_id ); $pay_url = $this->url.'MOLPay/pay/'.$this->merchant_id; $total = $order->order_total; $order_number = $order->get_order_number(); $vcode = md5($order->order_total.$this->merchant_id.$order_number.$this->verify_key); if ( sizeof( $order->get_items() ) > 0 ) foreach ( $order->get_items() as $item ) if ( $item['qty'] ) $item_names[] = $item['name'] . ' x ' . $item['qty']; $desc = sprintf( __( 'Order %s' , 'woocommerce'), $order_number ) . " - " . implode( ', ', $item_names ); $molpay_args = array( 'vcode' => $vcode, 'orderid' => $order_number, 'amount' => $total, 'bill_name' => $order->billing_first_name." ".$order->billing_last_name, 'bill_mobile' => $order->billing_phone, 'bill_email' => $order->billing_email, 'bill_desc' => $desc, 'country' => $order->billing_country, 'cur' => get_woocommerce_currency(), 'returnurl' => add_query_arg( 'wc-api', 'WC_Molpay_Gateway', home_url( '/' ) ) ); $molpay_args_array = array(); foreach ($molpay_args as $key => $value) { $molpay_args_array[] = "<input type='hidden' name='".$key."' value='". $value ."' />"; } $mpsreturn = add_query_arg( 'wc-api', 'WC_Molpay_Gateway', home_url( '/' )); return "<form action='".$pay_url."/' method='post' id='molpay_payment_form' name='molpay_payment_form'>" . implode('', $molpay_args_array) // . "<input type='submit' class='button-alt' id='submit_molpay_payment_form' value='" . __('Pay via MOLPay', 'woothemes') . "' /> " // . "<a class='buttoncancel' href='" . $order->get_cancel_order_url() . "'>".__('Cancel order &amp; restore cart', 'woothemes')."</a>" ."<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>" ."<script src='".$this->url."MOLPay/API/seamless/latest/js/MOLPay_seamless.deco.js'></script>" ."<h3><u>Pay via</u>:</h3><img src='".plugins_url( 'images/logo_RazerMerchantServices.png', __FILE__ )."' width='200px'>" ."<br/>" .($this->credit ? "<button type='button' style='background:none; padding:0px' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpstcctype='".$this->credit_tcctype."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='credit' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/credit.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->fpx_mb2u ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_mb2u' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_mb2u.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_cimbclicks ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_cimbclicks' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_cimbclicks.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_hlb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_hlb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_hlb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_rhb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_rhb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_rhb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_amb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_amb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_amb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_pbb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_pbb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_pbb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/> </button>" : '') .($this->fpx_abb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_abb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_abb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/> </button>" : '') .($this->fpx_bimb ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_bimb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_bimb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/> </button>" : '') .($this->fpx_abmb ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_abmb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_abmb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_bkrm ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_bkrm' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_bkrm.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_bmmb ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_bmmb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_bmmb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_bsn ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_bsn' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_bsn.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_hsbc ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_hsbc' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_hsbc.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_kfh ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_kfh' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_kfh.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_ocbc ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_ocbc' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_ocbc.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_scb ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_scb' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_scb.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->fpx_uob ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='fpx_uob' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/fpx_uob.png', __FILE__ )."' width='100px' height='50px' style='border: 1px solid; border-radius: 5px; border-color: #DDD;'/></button>" : '') .($this->Point_BCard ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='Point-BCard' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/Point-BCard.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->dragonpay ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='dragonpay' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/dragonpay.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->NGANLUONG ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='NGANLUONG' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/NGANLUONG.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->paysbuy ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='paysbuy' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/paysbuy.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->cash_711 ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='cash-711' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/cash-711.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->ATMVA ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='ATMVA' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/ATMVA.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->enetsD ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='enetsD' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/enetsD.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->singpost ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='singpost' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/singpost.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->UPOP ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='UPOP' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/UPOP.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->alipay ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='alipay' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/alipay.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->WeChatPay ? "<button type='button' style='background:none; padding:0px' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='WeChatPay' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/WeChatPay.png', __FILE__ )."' width='100px' height='50px'/> </button>" : '') .($this->WeChatPayMY ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='WeChatPayMY' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/wechatpay_my.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->BOOST ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='BOOST' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/boost.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->MB2U_QRPay_Push ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='MB2U_QRPay-Push' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/maybankQR.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->RazerPay ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='RazerPay' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/razerpay.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->TNG_EWALLET ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='TNG-EWALLET' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/touchngo_ewallet.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') .($this->GrabPay ? "<button type='button' style='background:none; padding:0px;' data-toggle='molpayseamless' data-mpsbill_mobile='".$order->billing_phone."' data-mpsmerchantid='".$this->merchant_id."' data-mpsbill_desc='".$desc."' data-mpsbill_email='".$order->billing_email."' data-mpscountry='".$order->billing_country."' data-mpscurrency='".get_woocommerce_currency()."' data-mpschannel='GrabPay' data-mpsamount='".$total."' data-mpsorderid='".$order_number."' data-mpsbill_name='".$order->billing_first_name." ".$order->billing_last_name."' data-mpsvcode='".$vcode."' data-mpsreturnurl='".$mpsreturn."'><img src='".plugins_url( 'images/grabpay.png', __FILE__ )."' width='100px' height='50px'/></button>" : '') . "</form>"; } /** * Order error button. * * @param object $order Order data. * @return string Error message and cancel button. */ protected function molpay_order_error( $order ) { $html = '<p>' . __( 'An error has occurred while processing your payment, please try again. Or contact us for assistance.', 'wcmolpay' ) . '</p>'; $html .='<a class="buttoncancel" href="' . esc_url( $order->get_cancel_order_url() ) . '">' . __( 'Click to try again', 'wcmolpay' ) . '</a>'; return $html; } /** * Process the payment and return the result. * * @param int $order_id * @return array */ public function process_payment( $order_id ) { $order = new WC_Order( $order_id ); return array( 'result' => 'success', 'redirect' => $order->get_checkout_payment_url( true ) ); } /** * Output for the order received page. * * @param object $order Order data. */ public function receipt_page( $order ) { echo $this->generate_form( $order ); } /** * Check for Razer Merchant Services Response * * @access public * @return void */ function check_ipn_response() { @ob_clean(); if ( !( isset($_POST['nbcb']) )) { do_action( "valid_molpay_request_returnurl", $_POST ); } else if ( $_POST['nbcb']=='1' ) { do_action ( "valid_molpay_request_callback", $_POST ); } else if ( $_POST['nbcb']=='2' ) { do_action ( "valid_molpay_request_notification", $_POST ); } else { wp_die( "Razer Merchant Services Request Failure" ); } } /** * This part is handle return response * * @global mixed $woocommerce */ function check_molpay_response_returnurl() { global $woocommerce; $verifyresult = $this->verifySkey($_POST); $status = $_POST['status']; if( !$verifyresult ) $status = "-1"; $WCOrderId = $this->get_WCOrderIdByOrderId($_POST['orderid']); $order = new WC_Order( $WCOrderId ); $referer = "<br>Referer: ReturnURL"; $getStatus = $order->get_status(); if(!in_array($getStatus,array('processing','completed'))) { if ($status == "11") { $referer .= " (Inquiry)"; $status = $this->inquiry_status( $_POST['tranID'], $_POST['amount'], $_POST['domain']); } $this->update_Cart_by_Status($WCOrderId, $status, $_POST['tranID'], $referer, $_POST['channel']); if (in_array($status, array("00","22"))) { wp_redirect($order->get_checkout_order_received_url()); } else { wp_redirect($order->get_cancel_order_url()); } } else { wp_redirect($order->get_checkout_order_received_url()); } $this->acknowledgeResponse($_POST); exit; } /** * This part is handle notification response * * @global mixed $woocommerce */ function check_molpay_response_notification() { global $woocommerce; $verifyresult = $this->verifySkey($_POST); $status = $_POST['status']; if ( !$verifyresult ) $status = "-1"; $WCOrderId = $this->get_WCOrderIdByOrderId($_POST['orderid']); $referer = "<br>Referer: NotificationURL"; $this->update_Cart_by_Status($WCOrderId, $status, $_POST['tranID'], $referer, $_POST['channel']); $this->acknowledgeResponse($_POST); } /** * This part is handle callback response * * @global mixed $woocommerce */ function check_molpay_response_callback() { global $woocommerce; $verifyresult = $this->verifySkey($_POST); $status = $_POST['status']; if ( !$verifyresult ) $status = "-1"; $WCOrderId = $this->get_WCOrderIdByOrderId($_POST['orderid']); $referer = "<br>Referer: CallbackURL"; $this->update_Cart_by_Status($WCOrderId, $status, $_POST['tranID'], $referer, $_POST['channel']); $this->acknowledgeResponse($_POST); } /** * Adds error message when not configured the merchant_id. * */ public function merchant_id_missing_message() { $message = '<div class="error">'; $message .= '<p>' . sprintf( __( '<strong>Gateway Disabled</strong> You should fill in your Merchant ID in Razer Merchant Services. %sClick here to configure!%s' , 'wcmolpay' ), '<a href="' . get_admin_url() . 'admin.php?page=wc-settings&tab=checkout&section=wc_molpay_gateway">', '</a>' ) . '</p>'; $message .= '</div>'; echo $message; } /** * Adds error message when not configured the verify_key. * */ public function verify_key_missing_message() { $message = '<div class="error">'; $message .= '<p>' . sprintf( __( '<strong>Gateway Disabled</strong> You should fill in your Verify Key in Razer Merchant Services. %sClick here to configure!%s' , 'wcmolpay' ), '<a href="' . get_admin_url() . 'admin.php?page=wc-settings&tab=checkout&section=wc_molpay_gateway">', '</a>' ) . '</p>'; $message .= '</div>'; echo $message; } /** * Adds error message when not configured the secret_key. * */ public function secret_key_missing_message() { $message = '<div class="error">'; $message .= '<p>' . sprintf( __( '<strong>Gateway Disabled</strong> You should fill in your Secret Key in Razer Merchant Services. %sClick here to configure!%s' , 'wcmolpay' ), '<a href="' . get_admin_url() . 'admin.php?page=wc-settings&tab=checkout&section=wc_molpay_gateway">', '</a>' ) . '</p>'; $message .= '</div>'; echo $message; } /** * Adds error message when not configured the account_type. * */ public function account_type_missing_message() { $message = '<div class="error">'; $message .= '<p>' . sprintf( __( '<strong>Gateway Disabled</strong> Select account type in Razer Merchant Services. %sClick here to configure!%s' , 'wcmolpay' ), '<a href="' . get_admin_url() . 'admin.php?page=wc-settings&tab=checkout&section=wc_molpay_gateway">', '</a>' ) . '</p>'; $message .= '</div>'; echo $message; } /** * Inquiry transaction status * * @param int $tranID * @param double $amount * @param string $domain * @return status */ public function inquiry_status($tranID, $amount, $domain) { $verify_key = $this->verify_key; $requestUrl = $this->inquiry_url."MOLPay/q_by_tid.php"; $request_param = array( "amount" => number_format($amount,2), "txID" => intval($tranID), "domain" => urlencode($domain), "skey" => urlencode(md5(intval($tranID).$domain.$verify_key.number_format($amount,2))) ); $post_data = http_build_query($request_param); $header[] = "Content-Type: application/x-www-form-urlencoded"; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch,CURLOPT_URL, $requestUrl); curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $response = trim($response); $temp = explode("\n", $response); foreach ( $temp as $value ) { $array = explode(':', $value); $key = trim($array[0], "[]"); $result[$key] = trim($array[1]); } $verify = md5($result['Amount'].$this->secret_key.$result['Domain'].$result['TranID'].$result['StatCode']); if ($verify != $result['VrfKey']) { $result['StatCode'] = "99"; } return $result['StatCode']; } /** * Update Cart based on Razer Merchant Services status * * @global mixed $woocommerce * @param int $order_id * @param int $MOLPay_status * @param int $tranID * @param string $referer */ public function update_Cart_by_Status($orderid, $MOLPay_status, $tranID, $referer, $channel) { global $woocommerce; $order = new WC_Order( $orderid ); switch ($MOLPay_status) { case '00': $M_status = 'SUCCESSFUL'; break; case '22': $M_status = 'PENDING'; $W_status = 'pending'; break; case '11': $M_status = 'FAILED'; $W_status = 'failed'; break; default: $M_status = 'Invalid Transaction'; $W_status = 'on-hold'; break; } $getStatus = $order->get_status(); if(!in_array($getStatus,array('processing','completed'))) { $order->add_order_note('Razer Merchant Services Payment Status: '.$M_status.'<br>Transaction ID: ' . $tranID . $referer); if ($MOLPay_status == "00") { $order->payment_complete(); } else { $order->update_status($W_status, sprintf(__('Payment %s via Razer Merchant Services.', 'woocommerce'), $tranID ) ); } if ($this->payment_title == 'yes') { $paytitle = $this->form_fields[strtolower($channel)]['title']; $order->set_payment_method_title($paytitle); $order->save(); } } } /** * Obtain the original order id based using the returned transaction order id * * @global mixed $woocommerce * @param int $orderid * @return int $real_order_id */ public function get_WCOrderIdByOrderId($orderid) { switch($this->ordering_plugin) { case '1' : $WCOrderId = wc_sequential_order_numbers()->find_order_by_order_number( $orderid ); break; case '2' : $WCOrderId = wc_seq_order_number_pro()->find_order_by_order_number( $orderid ); break; case '0' : default : $WCOrderId = $orderid; break; } return $WCOrderId; } /** * Acknowledge transaction result * * @global mixed $woocommerce * @param array $response */ public function acknowledgeResponse($response) { if ($response['nbcb'] == '1') { echo "CBTOKEN:MPSTATOK"; exit; } else { $response['treq']= '1'; // Additional parameter for IPN foreach($response as $k => $v) { $postData[]= $k."=".$v; } $postdata = implode("&",$postData); $url = $this->url."MOLPay/API/chkstat/returnipn.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST , 1 ); curl_setopt($ch, CURLOPT_POSTFIELDS , $postdata ); curl_setopt($ch, CURLOPT_URL , $url ); curl_setopt($ch, CURLOPT_HEADER , 1 ); curl_setopt($ch, CURLINFO_HEADER_OUT , TRUE ); curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , FALSE); curl_setopt($ch, CURLOPT_SSLVERSION , CURL_SSLVERSION_TLSv1 ); $result = curl_exec( $ch ); curl_close( $ch ); } } /** * To verify transaction result using merchant secret key setting. * * @global mixed $woocommerce * @param array $response * @return boolean verifyresult */ public function verifySkey($response) { $amount = $response['amount']; $orderid = $response['orderid']; $tranID = $response['tranID']; $status = $response['status']; $domain = $response['domain']; $currency = $response['currency']; $appcode = $response['appcode']; $paydate = $response['paydate']; $skey = $response['skey']; $vkey = $this->secret_key; $key0 = md5($tranID.$orderid.$status.$domain.$amount.$currency); $key1 = md5($paydate.$domain.$key0.$appcode.$vkey); if ($skey != $key1) return false; else return true; } } }
c1150ad42ac53e0b8b7aad25f877e99013f3f4df
[ "Markdown", "PHP" ]
9
Markdown
MOLPay/WordPress_WooCommerce_WP-eCommerce_ClassiPress
7050c25d206a8a33def50e6ba399f7d8eb21e193
fc3d3fa56e680e4927c889023fe81d08dfbf1552
refs/heads/master
<repo_name>michifehr/simpsons_quote<file_sep>/Simpsons_Quote/wwwroot/js/site.js var charName = ""; function myFunction(){ if (charName == ""){ document.getElementById("lanza").removeChild(document.getElementById("image_lanza")); } fetch('https://thesimpsonsquoteapi.glitch.me/quotes') .then(function(response) { return response.json(); }) .then(function(myArray) { console.log(myArray[0]); var obj = myArray[0]; var imgElm = document.getElementById("generated_image"); imgElm.src = obj.image; console.log(obj.characterDirection + " ("+(obj.characterDirection === "Right")+")"); if(obj.characterDirection === "Left"){ console.log(imgElm); imgElm.style.transform = "scaleX(-1)"; } else { imgElm.style.transform = "scaleX(1)"; } charName = obj.character; document.getElementById("name").innerHTML = charName; document.getElementById("quote").innerHTML = obj.quote; gapi.client.load('youtube', 'v3', onYouTubeApiLoad); }); } function onYouTubeApiLoad() { gapi.client.setApiKey('<KEY>'); var request = gapi.client.youtube.search.list({ part: 'snippet', q: charName }); console.log(onSearchResponse); request.execute(onSearchResponse); } function onSearchResponse(response) { console.log(response); var videos = response; console.log(videos.items[0].id.videoId); console.log(document.getElementById('video')); document.getElementById('video').src = "https://www.youtube.com/embed/" + videos.items[0].id.videoId; } <file_sep>/Simpsons_Quote/wwwroot/images/Simpsons Quote_files/site.js // Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code. function myFunction(){ fetch('https://thesimpsonsquoteapi.glitch.me/quotes') .then(function(response) { return response.json(); }) .then(function(myArray) { console.log(myArray[0]); var obj = myArray[0]; var imgElm = document.getElementById("generated_image"); imgElm.src = obj.image; console.log(obj.characterDirection); if(obj.characterDirection === "Right"){ imgElm.style.transform = "scaleX(-1)"; } document.getElementById("name").innerHTML = obj.character; document.getElementById("quote").innerHTML = obj.quote; }); }
230496e1f277d9275a19c73fa8c33c29fa09a8d9
[ "JavaScript" ]
2
JavaScript
michifehr/simpsons_quote
a6e85f22583323d65a31c6dce70669a9f0570bc8
90e80dcae6f0957584f8dee3de3924947b4273a2
refs/heads/master
<file_sep>(function(){ function MenuService (apiProxy){ var self = this; this.data = []; this.loading = false; this.apiProxy = apiProxy; this.tags="Organic, Gluten-free, Vegetarian" this.presets = [ { name: 'Burger Toppings', type: 'Add Ons', required: false, limit: 2, options: [ { name: 'Bacon', price: 2.0000 }, { name: "Pickles", price: 0.0000 } ] }, { name: "Bun Options", type: "Required Choice", required: true, limit: 1, options : [ { name: "Wheat", price: 0.0000 }, { name: 'White Bread', price: 0.0000 }, { name: 'Organic SourDough', price: 1.0000 } ] } ]; this.hours = [ { name: 'Sunday', times: [ { start: '', end: '' } ] }, { name: 'Monday', times: [ { start: '', end: '' } ] }, { name: 'Tuesday', times: [ { start: '', end: '' } ] }, { name: 'Wednesday', times: [ { start: '', end: '' } ] }, { name: 'Thursday', times: [ { start: '', end: '' } ] }, { name: 'Friday', times: [ { start: '', end: '' } ] }, { name: 'Saturday', times: [ { start: '', end: '' } ] } ]; } MenuService.prototype.get = function() { var self = this; this.loading = true; return this.apiProxy.get('https://menu.me:443/api/2/place/80/menus/').then(function(res){ self.data = res.menus; return res.menus; }).finally(function() { self.loading = false; }); }; angular.module('menuService', ['apiProxy']) .service('menuService', MenuService); })();
2708a736e75d2b11f8b1afb0402f3209535c1ba0
[ "JavaScript" ]
1
JavaScript
imconfused218/menuMeAdmin
e64a0474ffa956e0e0ed4dd97ab9cf287e3e00f6
945068e8878b6b26cc10f17525fc9776dc7910c0
refs/heads/master
<file_sep>var myName = '<NAME>' console.log(`Hello my name is ${myName}`) var number = 2 var newNumber = (((number * 2) * 5) / number) - 7 console.log(`output id ${newNumber}`) <file_sep># GitJavaScript ## <NAME>
e3c47160a2119e0a3b8d93946f2765a4a3182fc2
[ "JavaScript", "Markdown" ]
2
JavaScript
rubelbhinder24/git-javascript
79cbbd1aa516e6e34d7ef4e74cffa12bb280bdaa
5860e24c9e0b3ab30fcaf0e50bb6c36a163c748f
refs/heads/main
<file_sep>function updateTime(){ const currentTime= new Date(); let hour=currentTime.getHours(); let minute=currentTime.getMinutes(); let second=currentTime.getSeconds(); if(hour<10){ hour="0"+hour; }if(minute<10){ minute="0"+minute; }if(second<10){ second="0"+second; } document.getElementById("hour").innerHTML=hour+":"; document.getElementById("minute").innerHTML=minute+":"; document.getElementById("second").innerHTML=second; } setInterval(updateTime)
8d654913d26c6a622242250d0756bcf723b4b911
[ "JavaScript" ]
1
JavaScript
sayan9112/Digital_Clock_Project_SkillSanta
d190ec1bfb793497267c85e02402c134364528ed
b59963e20fb18c2529aa9c5a63c3d79a78d4adce
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TV_rename { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void BrowseButton_Click(object sender, EventArgs e) { var f = new FolderBrowserDialog(); f.SelectedPath = RootTextBox.Text; if (f.ShowDialog()== System.Windows.Forms.DialogResult.OK) { RootTextBox.Text = f.SelectedPath.Trim(); } } private void StartButton_Click(object sender, EventArgs e) { var series = SeriesTextBox.Text.Trim(); var season = (int)SeasonNumeric.Value; var folder = Path.Combine(RootTextBox.Text, series, series + " " + (UsRadio.Checked ? "Season" : "Series") + " " + season); var prefix = series + " " + season + "."; if (!Directory.Exists(folder)) { MessageBox.Show("Series directory '" + folder + "' does not exist!"); return; } var correct = EpisodeNamesTextBox.Text .Replace("\r\n", "\n").Replace('\r', '\n').Split('\n') .Select((q, i) => new { Episode = i + 1, Name = q.Trim() }) .ToDictionary(q => q.Episode, q => prefix + q.Episode.ToString().PadLeft(2, '0') + " " + q.Name); var oldnames = Directory.EnumerateFiles(folder) .Select(q => new { Path = q, Episode = GuessEpisode(Path.GetFileNameWithoutExtension(q), season) }).Where(q => q.Episode > 0); var renames = oldnames.Where(q => correct.ContainsKey(q.Episode)) .Select(q => new { Source = q.Path, Destination = Path.ChangeExtension(Path.Combine(folder, correct[q.Episode].Replace("\\", "").Replace(":", "-").Replace("?", "").Replace("/", "-") + ".xxx"), Path.GetExtension(q.Path)) }); if (renames.Count() > 0) { if (MessageBox.Show(string.Join("\n", renames.Select(q => Path.GetFileNameWithoutExtension(q.Source) + " ==> " + Path.GetFileNameWithoutExtension(q.Destination))), renames.Count() + " files to rename", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK) foreach (var f in renames) File.Move(f.Source, f.Destination); } else { MessageBox.Show("No files to rename!"); } } int GuessEpisode(string s, int season) { int i = s.IndexOf("s" + season.ToString().PadLeft(2, '0') + "e", StringComparison.InvariantCultureIgnoreCase); i = (i == -1 ? s.IndexOf(season + "x", StringComparison.InvariantCultureIgnoreCase) - 2 : i); if (i >= 0 && int.TryParse(s.Substring(i + 4, 2), out i)) return i; return -1; } private void WikiButton_Click(object sender, EventArgs e) { try { var n = EpisodeNamesTextBox.Text .Replace("\r\n", "\n").Replace('\r', '\n').Split(new[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(q => { var s = q.Split('\n'); return (s.Length > 1) ? s[1] : "-1 \"Unknown\""; }) .Select(q => new { Episode = int.Parse(q.Substring(0, 2)), Name = ExtractName(q) }) .Where(q => q.Episode != -1) .ToDictionary(q => q.Episode, q => q.Name); EpisodeNamesTextBox.Text = string.Join("\r\n", Enumerable.Range(1, n.Keys.Max()).Select(q => (n.ContainsKey(q) ? n[q] : ""))); } catch { MessageBox.Show("Cannot deduce episode names!"); } } string ExtractName(string s) { s = s.Substring(s.IndexOf("\"") + 1); s = s.Substring(0, s.IndexOf("\"")); return s.Trim(); } private void button1_Click(object sender, EventArgs e) { try { var n = EpisodeNamesTextBox.Text .Replace("\r\n", "\n").Replace('\r', '\n').Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(q => q.Trim()) .Where(q => q.StartsWith("\"") && q.EndsWith("\"")) .Select(q => q.Substring(1, q.Length - 2)); EpisodeNamesTextBox.Text = string.Join("\r\n", n); MessageBox.Show(n.Count() + " episode names found."); } catch { MessageBox.Show("Cannot deduce episode names!"); } } private void button2_Click(object sender, EventArgs e) { try { var n = EpisodeNamesTextBox.Text .Replace("\r\n", "\n").Replace('\r', '\n').Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) .Where(q => q.Count(c => c == '\"') > 1) .Select(q => q.Substring(q.IndexOf('\"') + 1)) .Select(q => q.Substring(0, q.IndexOf('\"')).Trim()); EpisodeNamesTextBox.Text = string.Join("\r\n", n); MessageBox.Show(n.Count() + " episode names found."); } catch { MessageBox.Show("Cannot deduce episode names!"); } } } }
eef3b43abbcc4a1415455d71b14a31703a77d468
[ "C#" ]
1
C#
hnkb/tv-rename
1e28ce084cdcbceb30aaf029e685fd69360b17e5
517646df2ba389942a5f2c31605794957e3a73b3
refs/heads/master
<repo_name>michal-gruszka/ToDoMVC<file_sep>/model.py from task import Task import os.path class Model: """ Class representing tasks database. """ def __init__(self): self._tasks = [] def get_task(self, index): if index in range(0, len(self._tasks)): return self._tasks[index] else: raise IndexError('Invalid index value.') def has_no_tasks(self): if len(self._tasks): return False return True def add_task(self, task): if isinstance(task, Task): self._tasks.append(task) else: raise TypeError("'task' must be an instance of Task class.") def delete_task(self, index): if index in range(0, len(self._tasks)): del self._tasks[index] else: raise IndexError('Invalid index value.') def mark_unmark_task(self, index): task = self.get_task(index) task.toggle_is_done() def archive_tasks(self): self._tasks = [t for t in self._tasks if not t.get_is_done()] def save_to_file(self, filename='tasks.csv'): with open(filename, 'w') as f: for task in self._tasks: line = '{},{},{}\n'.format(task.get_is_done(), task.get_name(), task.get_description()) f.write(line) def load_from_file(self, filename='tasks.csv'): if os.path.isfile(filename): tasks = [] with open(filename, 'r') as f: for line in f: is_done, name, description = line.rstrip('\n').split(',') task = Task(name) task.set_description(description) if is_done == 'True': task.toggle_is_done() tasks.append(task) self._tasks = tasks def __str__(self): if len(self._tasks) == 0: return '-- The list is empty --' string = '' i = 0 for task in self._tasks: string += '({}) [{}] {}\n'.format(i, 'X' if task.get_is_done() else ' ', task.get_name()) i += 1 return string<file_sep>/task.py class Task: """ An object representing a task/to-do item. """ def __init__(self, name): self.set_name(name) self._description = '---' self._is_done = False def set_name(self, name): if type(name) != str: raise TypeError("'name' must be a string.") if len(name) < 1 or len(name) > 20: raise ValueError("'name' must be 1-20 characters long.") self._name = name def get_name(self): return self._name def set_description(self, description): if type(description) != str: raise TypeError("'description' must be a string.") if len(description) < 1 or len(description) > 150: raise ValueError("'description' must be 1-150 characters long.") self._description = description def get_description(self): return self._description def toggle_is_done(self): if self._is_done: self._is_done = False else: self._is_done = True def get_is_done(self): return self._is_done def __str__(self): return '[{}] {}: {}'.format('X' if self._is_done else ' ', self._name, self._description)<file_sep>/view.py import os import time class View: """ Class responsible for user interface and taking user input. """ def welcome_screen(self): os.system('clear') print('========== Task Manager ==========\n\n', ' Welcome!\n') time.sleep(1.5) def menu_screen(self): os.system('clear') print('========== Task Manager ==========\n\n', '(1) Add task\n', '(2) Modify task\n', '(3) Delete task\n', '(4) Mark/unmark task as done\n', '(5) Display all tasks\n', '(6) Display task details\n', '(7) Archive done tasks\n', '(0) Exit\n\n') option = input('Choose option: ') return option def add_task_screen(self): os.system('clear') print('========== Task Manager ==========\n\n') name = input('Enter task name: ') description = input('Enter task description: ') return (name, description) def message_screen(self, msg): os.system('clear') print('========== Task Manager ==========\n\n', msg) time.sleep(1.5) def error_screen(self, error_msg='Invalid input'): os.system('clear') print('========== Task Manager ==========\n\n', 'Error: ' + error_msg) input('\n -- Press Enter to continue -- \n') def modify_task_choice_screen(self, task_name, description): os.system('clear') print('========== Task Manager ==========\n\n', 'Task name: ' + task_name + '\n', 'Description: ' + description + '\n\n', 'Choose the action: \n', '(1) Change name \n', '(2) Change description \n', '(3) Change name and description \n', '(0) Return \n') option = input('Choose option: ') return option def modify_task_screen(self, tasks_str): self._print_tasks_choice(tasks_str) task_id = input('Choose task to be modified: ') return task_id def change_name_screen(self, task_name): os.system('clear') print('========== Task Manager ==========\n\n', 'Task name: ' + task_name + '\n\n') new_name = input('Enter new task name: ') return new_name def change_description_screen(self, description): os.system('clear') print('========== Task Manager ==========\n\n', 'Task description: ' + description + '\n\n') new_description = input('Enter new task description: ') return new_description def change_name_and_description_screen(self, task_name, description): os.system('clear') print('========== Task Manager ==========\n\n', 'Task name: ' + task_name + '\n\n') new_name = 'Enter new task name: ' print('Task description: ' + description + '\n\n') new_description = input('Enter new task description: ') return (new_name, new_description) def delete_task_screen(self, tasks_str): self._print_tasks_choice(tasks_str) task_id = input('Choose task to be deleted: ') return task_id def mark_task_screen(self, tasks_str): self._print_tasks_choice(tasks_str) task_id = input('Choose task to mark/unmark: ') return task_id def display_tasks_screen(self, tasks_str): self._print_tasks_choice(tasks_str) input(' -- Press Enter to return -- \n') def choose_task_for_details_screen(self, tasks_str): self._print_tasks_choice(tasks_str) task_id = input('Choose task to see details: ') return task_id def display_task_details_screen(self, id, is_done, task_name, description): os.system('clear') print('========== Task Manager ==========\n\n' + 'Task id: ' + str(id) + '\n' + 'Done: ' + str(is_done) + '\n' + 'Name: ' + task_name + '\n' + 'Description: ' + description + '\n\n') input(' -- Press Enter to return -- \n') def _print_tasks_choice(self, tasks_str): os.system('clear') print('========== Task Manager ==========\n\n' + tasks_str + '\n')<file_sep>/controller.py from model import Model from view import View from task import Task import os class Controller: """ Class containing business logic and communication with View and Model. """ def __init__(self, model, view): self.model = model self.view = view def start_program(self): self.model.load_from_file() self.view.welcome_screen() while True: option = self.view.menu_screen() if option == '1': self.handle_add_task() elif option == '2': self.handle_modify_task() elif option == '3': self.handle_delete_task() elif option == '4': self.handle_mark_unmark() elif option == '5': self.handle_display_tasks() elif option == '6': self.handle_display_task_details() elif option == '7': self.handle_archive_tasks() elif option == '0': self.handle_exit() def handle_add_task(self): name, description = self.view.add_task_screen() try: new_task = Task(name) new_task.set_description(description) self.model.add_task(new_task) except (TypeError, ValueError) as e: self.view.error_screen(str(e)) else: self.view.message_screen('Task added!') def handle_modify_task(self): if self.model.has_no_tasks(): self.view.message_screen('There are no tasks!') return tasks_str = self.model.__str__() task_index = self.view.modify_task_screen(tasks_str) try: task_index = int(task_index) task = self.model.get_task(task_index) except (TypeError, ValueError, IndexError): self.view.error_screen('Invalid index number!') return while True: option = self.view.modify_task_choice_screen(task.get_name(), task.get_description()) if option == '1': self.handle_change_name(task) elif option == '2': self.handle_change_description(task) elif option == '3': self.handle_change_name_and_description(task) elif option == '0': break def handle_change_name(self, task): new_name = self.view.change_name_screen(task.get_name()) try: task.set_name(new_name) except (TypeError, ValueError) as e: self.view.error_screen(str(e)) else: self.view.message_screen('Task name changed!') def handle_change_description(self, task): new_desc = self.view.change_description_screen(task.get_description()) try: task.set_description(new_desc) except (TypeError, ValueError) as e: self.view.error_screen(str(e)) else: self.view.message_screen('Task description changed!') def handle_change_name_and_description(self, task): new_name = self.view.change_name_and_description_screen(task.get_name(), task.get_description()) try: task.set_name(new_name) task.set_description(new_desc) except (TypeError, ValueError) as e: self.view.error_screen(str(e)) else: self.view.message_screen('Task name and description changed!') def handle_delete_task(self): if self.model.has_no_tasks(): self.view.message_screen('There are no tasks!') return tasks_str = self.model.__str__() task_index = self.view.delete_task_screen(tasks_str) try: task_index = int(task_index) self.model.delete_task(task_index) except (TypeError, ValueError, IndexError): self.view.error_screen('Invalid index value!') else: self.view.message_screen('Task deleted!') def handle_mark_unmark(self): if self.model.has_no_tasks(): self.view.message_screen('There are no tasks!') return tasks_str = self.model.__str__() task_index = self.view.mark_task_screen(tasks_str) try: task_index = int(task_index) self.model.mark_unmark_task(task_index) except (TypeError, ValueError, IndexError): self.view.error_screen('Invalid index value!') else: self.view.message_screen('Task marking updated!') def handle_display_tasks(self): if self.model.has_no_tasks(): self.view.message_screen('There are no tasks!') return tasks_str = self.model.__str__() self.view.display_tasks_screen(tasks_str) def handle_display_task_details(self): if self.model.has_no_tasks(): self.view.message_screen('There are no tasks!') return tasks_str = self.model.__str__() task_index = self.view.choose_task_for_details_screen(tasks_str) try: task_index = int(task_index) chosen_task = self.model.get_task(task_index) except (TypeError, ValueError, IndexError): self.view.error_screen('Invalid index value!') else: self.view.display_task_details_screen(task_index, chosen_task.get_is_done(), chosen_task.get_name(), chosen_task.get_description()) def handle_archive_tasks(self): self.model.archive_tasks() self.view.message_screen('Tasks archived!') def handle_exit(self): self.model.save_to_file() self.view.message_screen(' Goodbye!') os.system('clear') exit()<file_sep>/main.py from model import Model from view import View from controller import Controller def main(): m = Model() v = View() c = Controller(m, v) c.start_program() if __name__ == '__main__': main()
2252ad883bf0b70a47ce4aa4db765e350f4c6cce
[ "Python" ]
5
Python
michal-gruszka/ToDoMVC
00f5cd4997f61ad7d5996c8aae2c6a1111fce32a
3f69c50051f630b3ebda5c38ff5eb9ac96f163a9
refs/heads/master
<repo_name>omer-akbas/stock-data<file_sep>/models/db.go package models import ( "database/sql" "flag" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func dbConnect() *sql.DB { // var ( // host string // port string // database string // user string // password string // ) // flag.StringVar(&host, "host", "172.16.17.32", "host (ip or name)") // flag.StringVar(&port, "port", "3306", "port") // flag.StringVar(&database, "database", "mynet", "database name") // flag.StringVar(&user, "user", "mynet", "username") // flag.StringVar(&password, "password", <PASSWORD>", "<PASSWORD>") flag.Parse() host := "172.16.17.32" port := "3306" database := "mynet" user := "mynet" password := <PASSWORD>" connQuery := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, host, port, database) db, err := sql.Open("mysql", connQuery) if err != nil { log.Println("db connection err: ", err.Error()) return nil } return db } <file_sep>/main.go package main import ( "time" "github.com/omer-akbas/stock-data/models" "github.com/robfig/cron/v3" ) func main() { target := models.Target{Url: "https://finans.mynet.com/borsa/hisseler"} target.ScrapperStart() c := cron.New() c.AddFunc("@every 1h0m0s", target.ScrapperStart) c.Start() time.Sleep(240 * time.Hour) c.Stop() } <file_sep>/go.mod module github.com/omer-akbas/stock-data go 1.15 require ( github.com/go-sql-driver/mysql v1.5.0 github.com/gocolly/colly/v2 v2.1.0 github.com/robfig/cron/v3 v3.0.1 ) <file_sep>/README.md # STOCK-DATA Golang ile yazılmış borsa verilerini saatte bir çekip, MySQL'e kaydeden basit bir uygulama. ## Run ```bash $ stock-data ``` <file_sep>/models/scrapper.go package models import ( "fmt" "strings" "sync" "time" "github.com/gocolly/colly/v2" ) type Target struct { Url string } func (t *Target) ScrapperStart() { defer chronometer(time.Now()) urls := t.urlList() // stocks := []Stock{} var wg sync.WaitGroup var lock sync.Mutex for i, url := range urls { if i%10 == 0 { time.Sleep(3 * time.Second) } wg.Add(1) // go t.urlVisit(url, &stocks, &wg, &lock) go t.urlVisit(url, &wg, &lock) } wg.Wait() // fmt.Println("--------------------------------------") // fmt.Println(stocks) // fmt.Println("ADET: ", len(stocks)) } func (t *Target) urlList() []string { c := colly.NewCollector() urlList := []string{} c.OnHTML("body > section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div > table > tbody > tr", func(e *colly.HTMLElement) { urlList = append(urlList, e.Request.AbsoluteURL(e.ChildAttr("a", "href"))) }) // c.Visit("https://finans.mynet.com/borsa/hisseler") c.Visit(t.Url) return urlList } func (t *Target) urlVisit(url string, wg *sync.WaitGroup, lock *sync.Mutex) { // func (t *Target) urlVisit(url string, stocks *[]Stock, wg *sync.WaitGroup, lock *sync.Mutex) { defer wg.Done() c := colly.NewCollector() var stock Stock c.OnHTML("body", func(e *colly.HTMLElement) { stock = Stock{ Name: e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.data-detay-page-heading > div:nth-child(1) > div.col-9.flex.align-items-center > h1"), Code: strings.ToUpper(e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.data-detay-page-heading > div:nth-child(1) > div.col-9.flex.align-items-center > span")), LastPrice: toFloat(e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.p-3 > div.flex-list-2-col.flex.justify-content-between > ul:nth-child(1) > li:nth-child(1) > span:nth-child(2)")), PreviousPrice: toFloat(e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.p-3 > div.flex-list-2-col.flex.justify-content-between > ul:nth-child(2) > li:nth-child(1) > span:nth-child(2)")), Bid: toFloat(e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.p-3 > div.flex-list-2-col.flex.justify-content-between > ul:nth-child(1) > li:nth-child(2) > span:nth-child(2)")), Ask: toFloat(e.ChildText("section > div.row > div.col-12.col-md-8.col-content > div:nth-child(3) > div > div:nth-child(1) > div.p-3 > div.flex-list-2-col.flex.justify-content-between > ul:nth-child(1) > li:nth-child(3) > span:nth-child(2)")), } }) c.Visit(url) lock.Lock() // *stocks = append(*stocks, stock) stock.Insert() lock.Unlock() fmt.Println(stock) } <file_sep>/models/helper.go package models import ( "log" "strconv" "strings" "time" ) func toFloat(s string) float64 { f, _ := strconv.ParseFloat(s, 8) return f } func chronometer(startTime time.Time) { endTime := time.Since(startTime) log.Println("startTime: ", startTime, "endTime: ", endTime, "=========> ", shortDuration(endTime)) } func shortDuration(d time.Duration) string { s := d.String() if strings.HasSuffix(s, "m0s") { s = s[:len(s)-2] } if strings.HasSuffix(s, "h0m") { s = s[:len(s)-2] } return s } <file_sep>/models/stock.go package models import ( "log" ) //Son işlem fiyatı = last price //Alış fiyatı = bid //Satış fiyatı = ask //Önceki kapanış fiyatı = PreviousPrice type Stock struct { LastPrice, PreviousPrice, Bid, Ask float64 Name, Code string } func (s *Stock) Insert() error { db := dbConnect() defer db.Close() var ( id, count int statement string ) _ = db.QueryRow("SELECT COUNT(*) FROM stock WHERE code = ?", s.Code).Scan(&count) if count == 0 { //first data if s.Name != "" && s.Code != "" { lastInsert, err := db.Exec("INSERT INTO stock(name, code) values(?, ?)", s.Name, s.Code) if err != nil { return err } returnId, err := lastInsert.LastInsertId() if err != nil { return err } id = int(returnId) statement = "-" } } else { //not the first var lstBid float64 err := db.QueryRow("SELECT id FROM stock WHERE code = ? LIMIT 1", s.Code).Scan(&id) if err != nil { log.Println("stock id query err:", err.Error()) return err } err = db.QueryRow("SELECT bid FROM price WHERE stockId = ? ORDER BY id DESC LIMIT 1", id).Scan(&lstBid) if err != nil { log.Println("price bid query err:", err.Error()) return err } if lstBid > s.Bid { statement = "high" } else if lstBid < s.Bid { statement = "low" } else { statement = "-" } } _, err := db.Exec("INSERT INTO price(lastPrice, previousPrice, bid, ask, status, stockId) values(?, ?, ?, ?, ?, ?)", s.LastPrice, s.PreviousPrice, s.Bid, s.Ask, statement, id) if err != nil { log.Println("price insert err:", err.Error()) return err } return nil }
a75f8c1b1393a3ee87a61fa48ac61717bab37b65
[ "Markdown", "Go Module", "Go" ]
7
Go
omer-akbas/stock-data
fbb00cb4d0921e3fcb8ec96f1227af65aa40bdea
c7b49469e2c554095f880a5afe7757d6d0a1aa2b
refs/heads/master
<repo_name>omissis/AgaveeSingleSignOnBundle<file_sep>/Security/AgaveeSSOUserProvider.php <?php // src/Agavee/Bundle/SingleSignOnBundle/Security/AgaveeSSOUserProvider.php namespace Agavee\Bundle\SingleSignOnBundle\Security; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Agavee\SSO\Factory\UserFactoryInterface; use Agavee\SSO\Client as SSOClient; class AgaveeSSOUserProvider implements UserProviderInterface { private $userFactory; private $property; private $secret; private $client; public function __construct(UserFactoryInterface $userFactory, $serverUrl, $secret, $property = null) { $this->userFactory = $userFactory; $this->property = $property; $this->secret = $secret; $this->client = new SSOClient($serverUrl); } public function loadUserByUsername($username) { $userdata = $this->getUserdata($username); if (!empty($userdata)) { return $this->userFactory->fromStdClass($userdata); } throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); } public function refreshUser(UserInterface $user) { $userClass = $this->userFactory->getClass(); if (!$user instanceof $userClass) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } return $this->loadUserByUsername($user->getEmail()); } public function supportsClass($class) { return $class === $this->userFactory->getClass(); } private function getUserdata($username) { return $this->client->getUser($this->property, $username, $this->secret); } }<file_sep>/DependencyInjection/AgaveeSingleSignOnExtension.php <?php namespace Agavee\Bundle\SingleSignOnBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class AgaveeSingleSignOnExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('agavee_single_sign_on.server_url', $config['server_url']); $container->setParameter('agavee_single_sign_on.success_url', $config['success_url']); $container->setParameter('agavee_single_sign_on.failure_url', $config['failure_url']); $container->setParameter('agavee_single_sign_on.property', $config['property']); $container->setParameter('agavee_single_sign_on.secret', $config['secret']); $container->setParameter('agavee_single_sign_on.user_factory.class', $config['user_factory']['class']); $container->setParameter('agavee_single_sign_on.token_factory.class', $config['token_factory']['class']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } } <file_sep>/Controller/SSOController.php <?php namespace Agavee\Bundle\SingleSignOnBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Agavee\SSO\Server as SSOServer; abstract class SSOController extends Controller { protected $ssoServer; protected $formatter; abstract public function tokenAction(); abstract public function userAction(); abstract public function loginAction(); abstract public function logoutAction(); protected function initServer($formatter) { $this->ssoServer = new SSOServer( $this->container->get('agavee_single_sign_on.token_factory'), $this->container->getParameter('secret'), $formatter ); } }<file_sep>/Listener/LoginListener.php <?php namespace Agavee\Bundle\SingleSignOnBundle\Listener; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Routing\Router; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpKernel\KernelEvents; use Agavee\SSO\Client as SSOClient; use Agavee\SSO\Exception\InvalidTokenException; /** * LoginListener. */ class LoginListener { /** * @var SecurityContext $security */ private $security; /** * @var EventDispatcher $dispatcher */ private $dispatcher; /** * @var SSOClient $client */ private $client; /** * @var string $serverUrl */ private $serverUrl; /** * @var string $secret */ private $secret; /** * Constructs a new instance of LoginListener. * * @param SecurityContext $security The security context * @param EventDispatcher $dispatcher The event dispatcher */ public function __construct(SecurityContext $security, EventDispatcher $dispatcher, $serverUrl, $successUrl, $failureUrl, $secret) { $this->dispatcher = $dispatcher; $this->successUrl = $successUrl; $this->failureUrl = $failureUrl; $this->serverUrl = $serverUrl; $this->security = $security; $this->secret = $secret; $this->client = new SSOClient($serverUrl); } /** * Invoked after a successful login. * * @param InteractiveLoginEvent $event The event */ public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { if ($this->security->isGranted('ROLE_USER')) { // since the user is authenticated attach this listener for kernel.response event $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse')); } } /** * Invoked after the response has been created. * * @param FilterResponseEvent $event The event */ public function onKernelResponse(FilterResponseEvent $event) { try { $request = $event->getRequest(); $user = $this->security->getToken()->getUser(); $email = $user->getEmail(); $password = $user-><PASSWORD>(); $agent = $request->server->get('HTTP_USER_AGENT'); $ip = $request->getClientIp(); $token = $this->client->getToken($ip, $agent, $email, $this->secret); $url = $this->client->getLoginUrl(array( 'email' => $email, 'password' => <PASSWORD>, 'token' => $token, 'successUrl' => $this->successUrl, 'failureUrl' => $this->failureUrl, )); } catch (InvalidTokenException $e) { $url = '/'; } $response = new RedirectResponse($url); $event->setResponse($response); } }<file_sep>/Handler/LogoutHandler.php <?php // src/Agavee/Bundle/SingleSignOnBundle/Handler/LogoutHandler.php namespace Agavee\Bundle\SingleSignOnBundle\Handler; use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\HttpFoundation\Request; use Agavee\SSO\Client as SSOClient; use Agavee\SSO\Exception\InvalidTokenException; class LogoutHandler implements LogoutSuccessHandlerInterface { private $client; public function __construct(SecurityContext $security, $serverUrl, $successUrl, $failureUrl, $secret) { $this->successUrl = $successUrl; $this->failureUrl = $failureUrl; $this->serverUrl = $serverUrl; $this->security = $security; $this->secret = $secret; $this->client = new SSOClient($serverUrl); } public function onLogoutSuccess(Request $request) { try { $agent = $request->server->get('HTTP_USER_AGENT'); $ip = $request->getClientIp(); $token = $this->client->getToken($ip, $agent, 'unknown', $this->secret); $url = $this->client->getLogoutUrl(array( 'token' => $token, 'successUrl' => $this->successUrl, 'failureUrl' => $this->failureUrl, )); } catch (InvalidTokenException $e) { $url = '/'; } return new RedirectResponse($url); } }<file_sep>/AgaveeSingleSignOnBundle.php <?php namespace Agavee\Bundle\SingleSignOnBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AgaveeSingleSignOnBundle extends Bundle { }
6905aaf43b4862abc70b5d14b8e24f2172b6d8e3
[ "PHP" ]
6
PHP
omissis/AgaveeSingleSignOnBundle
dde3d67ee16f15bbdd691534583a66aec72f3555
08ebce912dd8d000a0f958c9f79ea9f0ab839bac
refs/heads/master
<file_sep>const reactiveElem = document.querySelector(".cursor-reactive"); console.log("loaded"); reactiveElem.addEventListener("mousemove", (e) => { console.log("hello"); alert("hi"); reactiveElem.style.backgroundPositionX = -e.offsetX + "px"; reactiveElem.style.backgroundPositionY = -e.offsetY + "px"; }); <file_sep>// Get the modal const modal = document.querySelector(".modal"); // Get the image and insert it inside the modal - use its "alt" text as a caption var images = document.querySelectorAll(".gallery-image"); var modalImg = document.querySelector(".img01"); var captionText = document.querySelector(".caption"); images.forEach((img) => { img.onclick = function () { modal.style.display = "block"; modalImg.style.backgroundImage = this.style.backgroundImage; captionText.innerHTML = this.dataset.caption; }; }); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; }; modal.onclick = function () { modal.style.display = "none"; }; <file_sep>const galleryOptions = document.querySelectorAll(".option"); const allPhotos = document.querySelectorAll(".image-container"); function updateGallery(galleryType) { if (galleryType == "All") { allPhotos.forEach((photo) => { photo.style.display = "block"; }); return; } allPhotos.forEach((photo) => { if (photo.childNodes[1].dataset.tag == galleryType) { photo.style.display = "block"; } else { photo.style.display = "none"; } }); } galleryOptions.forEach((element) => { element.addEventListener("click", () => { galleryOptions.forEach((element) => { element.classList.remove("showing"); }); element.classList.add("showing"); updateGallery(element.innerHTML); }); });
7c676e3e4b548d113d57a5ac526252b4ad140f68
[ "JavaScript" ]
3
JavaScript
llllQ/mikepenlingtonwebsite
6ef88edff9dc47b89af800a472ffe67806dd934c
9b16790205b58fd6df9d1e47338e3ea08934e5b9
refs/heads/master
<repo_name>emonmishra/Anastasia<file_sep>/README.md # Anastasia # Testing connectivity # Test starting <file_sep>/src/com/rockyou/command/info/CommandInfo.java package com.rockyou.command.info; import com.rockyou.storage.Key; import com.rockyou.storage.Value; public class CommandInfo implements ICommandInfo { @Override public Key getKey() { return null; } @Override public Value getValue() { return null; } @Override public int expireTime() { return 0; } } <file_sep>/src/com/rockyou/storage/CacheStorage.java package com.rockyou.storage; import java.util.HashMap; import java.util.Map; public class CacheStorage { // TODO: based on xmx size, derive initial capacity Map<Key, Value> defaultCache = new HashMap<>(100000, 1); private Map<Key, Value> cache; public CacheStorage(Map<Key, Value> cache) { this.cache = cache; } public CacheStorage() { this.cache = defaultCache; } public Object get(Key key) { return cache.get(key); } public Object put(Key key, Value value) { return cache.put(key, value); } public Object delete(Key key) { return cache.remove(key); } } <file_sep>/src/com/rockyou/command/info/ICommandInfo.java package com.rockyou.command.info; import com.rockyou.storage.Key; import com.rockyou.storage.Value; public interface ICommandInfo { public Key getKey() ; public Value getValue(); public int expireTime(); } <file_sep>/src/com/rockyou/server/TcpServer.java package com.rockyou.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; import com.rockyou.command.manager.CommandManager; public class TcpServer { private CommandManager commandMgr; private ServerSocketChannel serverSocketChannel; private Selector selector; public TcpServer() { commandMgr = new CommandManager(); } public boolean startServer(int port) { return startServer(new InetSocketAddress(port)); } public boolean startServer(InetSocketAddress sockAddr) { try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(sockAddr); serverSocketChannel.configureBlocking(false); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, null); } catch (ClosedChannelException e1) { return false; } catch (IOException e) { //Log error return false; } while(true){ try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = keys.iterator(); while (keyIterator.hasNext()) { SelectionKey myKey = keyIterator.next(); if (myKey.isAcceptable()) { SocketChannel client = serverSocketChannel.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } else if (myKey.isReadable()) { read(myKey); } keyIterator.remove(); } } catch (IOException e1) { } } } private void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int numRead = -1; numRead = channel.read(buffer); if (numRead == -1) { channel.close(); key.cancel(); return; } } public boolean stopServer() { return true; } } <file_sep>/src/com/rockyou/storage/Key.java package com.rockyou.storage; import java.io.Serializable; public class Key implements StorableEntity, Serializable { private static final long serialVersionUID = 7526471155622776147L; @Override public int hashCode() { //TODO: logic for hashcode return 1; } @Override public boolean equals(Object o) { //TODO: logic to compare, probably at bytes/string return true; } public String encode() { return null; } public String decode() { return null; } } <file_sep>/src/test/com/rockyou/command/CommandManagerTest.java package test.com.rockyou.command; public class CommandManagerTest { }
de2af0b4f47d017454e68e40f35a40970b19ac6b
[ "Markdown", "Java" ]
7
Markdown
emonmishra/Anastasia
6975835e79c62de10e7819f909be3989ec73ba5d
ed02899ab05723c7a93988dce5a219199753e8f5
refs/heads/master
<file_sep>{ 'includes': [ '../build/common.gypi', ], 'variables': { 'sources': [ 'InitializeLLVM.cpp', 'log.cpp', 'CompilerState.cpp', 'IntrinsicRepository.cpp', 'CommonValues.cpp', 'Output.cpp', 'Compile.cpp', 'StackMaps.cpp', 'Link.cpp', ], 'llvmlog_level': 0, }, } <file_sep>{ 'includes': [ 'llvm.gypi', ], 'targets': [ { 'target_name': 'libllvm', 'type': 'static_library', 'sources': [ '<@(sources)',], 'include_dirs': [ '.', ], 'defines': [ 'LLVMLOG_LEVEL=<(llvmlog_level)', ], 'direct_dependent_settings': { 'include_dirs': [ '.', ], 'libraries': [ '<!(llvm-config --libs)', '-ldl', '-lz', '-lpthread', '-lcurses', ], 'ldflags': [ '<!(llvm-config --ldflags)', ], 'defines': [ 'LLVMLOG_LEVEL=<(llvmlog_level)', ], 'cflags_cc': [ '<!(llvm-config --cxxflags)', ], 'cflags': [ '<!(llvm-config --cflags)', ], }, 'cflags_cc': [ '<!(llvm-config --cxxflags)', ], 'cflags': [ '<!(llvm-config --cflags)', ], }, ], } <file_sep>#include "StackMaps.h" namespace jit { Reg DWARFRegister::reg() const { #if __x86_64__ if (m_dwarfRegNum >= 0 && m_dwarfRegNum < 16) { switch (dwarfRegNum()) { case 0: return AMD64::RAX; case 1: return AMD64::RDX; case 2: return AMD64::RCX; case 3: return AMD64::RBX; case 4: return AMD64::RSI; case 5: return AMD64::RDI; case 6: return AMD64::RBP; case 7: return AMD64::RSP; default: // Registers r8..r15 are numbered sensibly. return static_cast<Reg>(m_dwarfRegNum); } } if (m_dwarfRegNum >= 17 && m_dwarfRegNum <= 32) return static_cast<FPRReg>(m_dwarfRegNum - 17); return Reg(); #else #error unsupported arch. #endif } template <typename T> T readObject(StackMaps::ParseContext& context) { T result; result.parse(context); return result; } void StackMaps::Constant::parse(StackMaps::ParseContext& context) { integer = context.view->read<int64_t>(context.offset, true); } void StackMaps::StackSize::parse(StackMaps::ParseContext& context) { switch (context.version) { case 0: functionOffset = context.view->read<uint32_t>(context.offset, true); size = context.view->read<uint32_t>(context.offset, true); break; default: functionOffset = context.view->read<uint64_t>(context.offset, true); size = context.view->read<uint64_t>(context.offset, true); break; } } void StackMaps::Location::parse(StackMaps::ParseContext& context) { kind = static_cast<Kind>(context.view->read<uint8_t>(context.offset, true)); size = context.view->read<uint8_t>(context.offset, true); dwarfReg = DWARFRegister(context.view->read<uint16_t>(context.offset, true)); this->offset = context.view->read<int32_t>(context.offset, true); } void StackMaps::LiveOut::parse(StackMaps::ParseContext& context) { dwarfReg = DWARFRegister(context.view->read<uint16_t>(context.offset, true)); // regnum context.view->read<uint8_t>(context.offset, true); // reserved size = context.view->read<uint8_t>(context.offset, true); // size in bytes } bool StackMaps::Record::parse(StackMaps::ParseContext& context) { int64_t id = context.view->read<int64_t>(context.offset, true); assert(static_cast<int32_t>(id) == id); patchpointID = static_cast<uint32_t>(id); if (static_cast<int32_t>(patchpointID) < 0) return false; instructionOffset = context.view->read<uint32_t>(context.offset, true); flags = context.view->read<uint16_t>(context.offset, true); unsigned length = context.view->read<uint16_t>(context.offset, true); while (length--) locations.push_back(readObject<Location>(context)); if (context.version >= 1) context.view->read<uint16_t>(context.offset, true); // padding unsigned numLiveOuts = context.view->read<uint16_t>(context.offset, true); while (numLiveOuts--) liveOuts.push_back(readObject<LiveOut>(context)); if (context.version >= 1) { if (context.offset & 7) { assert(!(context.offset & 3)); context.view->read<uint32_t>(context.offset, true); // padding } } return true; } RegisterSet StackMaps::Record::locationSet() const { RegisterSet result; for (unsigned i = locations.size(); i--;) { Reg reg = locations[i].dwarfReg.reg(); result.set(reg.val() << (reg.isFloat() ? 32 : 0)); } return result; } RegisterSet StackMaps::Record::liveOutsSet() const { RegisterSet result; for (unsigned i = liveOuts.size(); i--;) { LiveOut liveOut = liveOuts[i]; Reg reg = liveOut.dwarfReg.reg(); // FIXME: Either assert that size is not greater than sizeof(pointer), or actually // save the high bits of registers. // https://bugs.webkit.org/show_bug.cgi?id=130885 result.set(reg.val() << (reg.isFloat() ? 32 : 0)); } return result; } static void merge(RegisterSet& dst, const RegisterSet& input) { for (int i = 0; i < input.size(); ++i) { dst.set(i, dst.test(i) ^ input.test(i) ^ dst.test(i)); } } RegisterSet StackMaps::Record::usedRegisterSet() const { RegisterSet result; merge(result, locationSet()); merge(result, liveOutsSet()); return result; } bool StackMaps::parse(DataView* view) { ParseContext context; context.offset = 0; context.view = view; version = context.version = context.view->read<uint8_t>(context.offset, true); context.view->read<uint8_t>(context.offset, true); // Reserved context.view->read<uint8_t>(context.offset, true); // Reserved context.view->read<uint8_t>(context.offset, true); // Reserved uint32_t numFunctions; uint32_t numConstants; uint32_t numRecords; numFunctions = context.view->read<uint32_t>(context.offset, true); if (context.version >= 1) { numConstants = context.view->read<uint32_t>(context.offset, true); numRecords = context.view->read<uint32_t>(context.offset, true); } while (numFunctions--) stackSizes.push_back(readObject<StackSize>(context)); if (!context.version) numConstants = context.view->read<uint32_t>(context.offset, true); while (numConstants--) constants.push_back(readObject<Constant>(context)); if (!context.version) numRecords = context.view->read<uint32_t>(context.offset, true); while (numRecords--) { Record record; if (!record.parse(context)) return false; records.push_back(record); } return true; } StackMaps::RecordMap StackMaps::computeRecordMap() const { RecordMap result; for (unsigned i = records.size(); i--;) result.insert(std::make_pair(records[i].patchpointID, std::vector<Record>())).first->second.push_back(records[i]); return result; } unsigned StackMaps::stackSize() const { assert(stackSizes.size() == 1); return stackSizes[0].size; } } <file_sep>#include <assert.h> #include <string.h> #include <stdlib.h> #include "InitializeLLVM.h" #include "CompilerState.h" #include "Output.h" #include "Compile.h" #include "Link.h" #include "Registers.h" #include "log.h" typedef jit::CompilerState State; static void myexit(void) { exit(1); } static void buildIR(State& state) { using namespace jit; Output output(state); // LValue arg = output.arg(); LBasicBlock body = output.appendBasicBlock("Body"); output.buildBr(body); output.positionToBBEnd(body); LValue one = output.constIntPtr(1); LValue indicator = output.buildLoadArgIndex(2); LValue val = output.buildLoadArgIndex(0); LValue add = output.buildAdd(val, one); LValue result = output.buildSelect(output.buildICmp(LLVMIntNE, indicator, output.constIntPtr(0)), add, val); output.buildStoreArgIndex(result, 0); LBasicBlock patch = output.appendBasicBlock("Patch"); output.buildBr(patch); output.positionToBBEnd(patch); output.buildDirectPatch(reinterpret_cast<uintptr_t>(myexit)); } static void mydispIndirect(void) { printf("%s.\n", __FUNCTION__); } static void mydispDirect(void) { printf("%s.\n", __FUNCTION__); } static void mydispAssist(void) { printf("%s.\n", __FUNCTION__); } inline static uint8_t rexAMode_R__wrk(unsigned gregEnc3210, unsigned eregEnc3210) { uint8_t W = 1; /* we want 64-bit mode */ uint8_t R = (gregEnc3210 >> 3) & 1; uint8_t X = 0; /* not relevant */ uint8_t B = (eregEnc3210 >> 3) & 1; return 0x40 + ((W << 3) | (R << 2) | (X << 1) | (B << 0)); } static inline unsigned iregEnc3210(unsigned in) { return in; } static uint8_t rexAMode_R(unsigned greg, unsigned ereg) { return rexAMode_R__wrk(iregEnc3210(greg), iregEnc3210(ereg)); } inline static uint8_t mkModRegRM(unsigned mod, unsigned reg, unsigned regmem) { return (uint8_t)(((mod & 3) << 6) | ((reg & 7) << 3) | (regmem & 7)); } inline static uint8_t* doAMode_R__wrk(uint8_t* p, unsigned gregEnc3210, unsigned eregEnc3210) { *p++ = mkModRegRM(3, gregEnc3210 & 7, eregEnc3210 & 7); return p; } static uint8_t* doAMode_R(uint8_t* p, unsigned greg, unsigned ereg) { return doAMode_R__wrk(p, iregEnc3210(greg), iregEnc3210(ereg)); } static uint8_t* emit64(uint8_t* p, uint64_t w64) { *reinterpret_cast<uint64_t*>(p) = w64; return p + sizeof(w64); } static void patchProloge(void*, uint8_t* start, uint8_t* end) { uint8_t* p = start; *p++ = rexAMode_R(jit::RBP, jit::RDI); *p++ = 0x89; p = doAMode_R(p, jit::RBP, jit::RDI); memset(p, 0x90, static_cast<size_t>(end - p)); } static void patchDirect(void*, uint8_t* p) { // epilogue // 3 bytes *p++ = rexAMode_R(jit::RBP, jit::RDI); *p++ = 0x89; p = doAMode_R(p, jit::RBP, jit::RSP); // 1 bytes pop rbp *p++ = 0x5d; /* 10 bytes: movabsq $target, %r11 */ *p++ = 0x49; *p++ = 0xBB; p = emit64(p, reinterpret_cast<uintptr_t>(mydispDirect)); /* movq %r11, RIP(%rbp) */ /* 3 bytes: call*%r11 */ *p++ = 0x41; *p++ = 0xFF; *p++ = 0xD3; } static void patchIndirect(void*, uint8_t* p) { // epilogue // 3 bytes *p++ = rexAMode_R(jit::RBP, jit::RDI); *p++ = 0x89; p = doAMode_R(p, jit::RBP, jit::RSP); // 1 bytes pop rbp *p++ = 0x5d; /* 10 bytes: movabsq $target, %r11 */ *p++ = 0x49; *p++ = 0xBB; p = emit64(p, reinterpret_cast<uintptr_t>(mydispIndirect)); /* movq %r11, RIP(%rbp) */ /* 3 bytes: jmp *%r11 */ *p++ = 0x41; *p++ = 0xFF; *p++ = 0xE3; } static void patchAssist(void*, uint8_t* p) { // epilogue // 3 bytes *p++ = rexAMode_R(jit::RBP, jit::RDI); *p++ = 0x89; p = doAMode_R(p, jit::RBP, jit::RSP); // 1 bytes pop rbp *p++ = 0x5d; /* 10 bytes: movabsq $target, %r11 */ *p++ = 0x49; *p++ = 0xBB; p = emit64(p, reinterpret_cast<uintptr_t>(mydispAssist)); /* movq %r11, RIP(%rbp) */ /* 3 bytes: jmp *%r11 */ *p++ = 0x41; *p++ = 0xFF; *p++ = 0xE3; } static const char* symbolLookupCallback(void* DisInfo, uint64_t ReferenceValue, uint64_t* ReferenceType, uint64_t ReferencePC, const char** ReferenceName) { *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; return nullptr; } static void disassemble(jit::ByteBuffer& code) { LLVMDisasmContextRef DCR = LLVMCreateDisasm("x86_64-pc-linux", nullptr, 0, nullptr, symbolLookupCallback); uint8_t* BytesP = code.data(); unsigned NumBytes = code.size(); unsigned PC = 0; const char OutStringSize = 100; char OutString[OutStringSize]; printf("================================================================================\n"); while (NumBytes != 0) { size_t InstSize = LLVMDisasmInstruction(DCR, BytesP, NumBytes, PC, OutString, OutStringSize); PC += InstSize; BytesP += InstSize; NumBytes -= InstSize; printf("%s\n", OutString); } } static void disassemble(State& state) { for (auto& code : state.m_codeSectionList) { disassemble(code); } } int main() { initLLVM(); using namespace jit; PlatformDesc desc = { 40 * sizeof(intptr_t), /* context size */ 192, /* offset of pc */ 3, /* prologue size */ 17, /* direct size */ 17, /* indirect size */ 17, /* assist size */ nullptr, /* opaque */ patchProloge, patchDirect, patchAssist, }; State state("test", desc); buildIR(state); dumpModule(state.m_module); compile(state); link(state); disassemble(state); return 0; } <file_sep>{ 'includes': [ 'common.gypi', ], 'targets': [ { 'target_name': 'All', 'type': 'none', 'dependencies': [ '<(DEPTH)/main.gyp:*', ] }, ], } <file_sep>#ifndef LLVMHEADERS_H #define LLVMHEADERS_H #pragma once #include <llvm-c/Analysis.h> #include <llvm-c/BitReader.h> #include <llvm-c/Core.h> #include <llvm-c/Disassembler.h> #include <llvm-c/ExecutionEngine.h> #include <llvm-c/Initialization.h> #include <llvm-c/Linker.h> #include <llvm-c/Target.h> #include <llvm-c/TargetMachine.h> #include <llvm-c/Transforms/IPO.h> #include <llvm-c/Transforms/PassManagerBuilder.h> #include <llvm-c/Transforms/Scalar.h> #endif /* LLVMHEADERS_H */ <file_sep>#ifndef OUTPUT_H #define OUTPUT_H #include "IntrinsicRepository.h" namespace jit { struct CompilerState; class Output { public: Output(CompilerState& state); ~Output(); LBasicBlock appendBasicBlock(const char* name = nullptr); void positionToBBEnd(LBasicBlock); LValue constInt32(int); LValue constIntPtr(intptr_t); LValue constInt64(long long); LValue buildStructGEP(LValue structVal, unsigned field); LValue buildLoad(LValue toLoad); LValue buildStore(LValue val, LValue pointer); LValue buildAdd(LValue lhs, LValue rhs); LValue buildBr(LBasicBlock bb); LValue buildRet(LValue ret); LValue buildRetVoid(void); LValue buildLoadArgIndex(int index); LValue buildStoreArgIndex(LValue val, int index); LValue buildSelect(LValue condition, LValue taken, LValue notTaken); LValue buildICmp(LIntPredicate cond, LValue left, LValue right); inline LValue buildCall(LValue function, const LValue* args, unsigned numArgs) { return LLVMBuildCall(m_builder, function, const_cast<LValue*>(args), numArgs, ""); } template <typename VectorType> inline LValue buildCall(LValue function, const VectorType& vector) { return buildCall(function, vector.begin(), vector.size()); } inline LValue buildCall(LValue function) { return buildCall(function, nullptr, 0U); } inline LValue buildCall(LValue function, LValue arg1) { return buildCall(function, &arg1, 1); } template <typename... Args> LValue buildCall(LValue function, LValue arg1, Args... args) { LValue argsArray[] = { arg1, args... }; return buildCall(function, argsArray, sizeof(argsArray) / sizeof(LValue)); } LValue buildCast(LLVMOpcode Op, LLVMValueRef Val, LLVMTypeRef DestTy); void buildDirectPatch(uintptr_t where); void buildIndirectPatch(LValue where); void buildAssistPatch(LValue where); inline IntrinsicRepository& repo() { return m_repo; } inline LType argType() const { return m_argType; } inline LBasicBlock prologue() const { return m_prologue; } inline LValue arg() const { return m_arg; } private: void buildGetArg(); void buildPatchCommon(LValue where, const PatchDesc& desc, size_t patchSize); CompilerState& m_state; IntrinsicRepository m_repo; LBuilder m_builder; LType m_argType; LBasicBlock m_prologue; LValue m_arg; uint32_t m_stackMapsId; }; } #endif /* OUTPUT_H */ <file_sep>#include <assert.h> #include "CompilerState.h" #include "Output.h" namespace jit { Output::Output(CompilerState& state) : m_state(state) , m_repo(state.m_context, state.m_module) , m_builder(nullptr) , m_stackMapsId(1) { m_argType = pointerType(arrayType(repo().intPtr, state.m_platformDesc.m_contextSize / sizeof(intptr_t))); state.m_function = addFunction( state.m_module, "main", functionType(repo().int64, m_argType)); m_builder = LLVMCreateBuilderInContext(state.m_context); m_prologue = appendBasicBlock("Prologue"); positionToBBEnd(m_prologue); buildGetArg(); } Output::~Output() { LLVMDisposeBuilder(m_builder); } LBasicBlock Output::appendBasicBlock(const char* name) { return jit::appendBasicBlock(m_state.m_context, m_state.m_function, name); } void Output::positionToBBEnd(LBasicBlock bb) { LLVMPositionBuilderAtEnd(m_builder, bb); } LValue Output::constInt32(int i) { return jit::constInt(m_repo.int32, i); } LValue Output::constInt64(long long l) { return jit::constInt(m_repo.int64, l); } LValue Output::constIntPtr(intptr_t i) { return jit::constInt(m_repo.intPtr, i); } LValue Output::buildStructGEP(LValue structVal, unsigned field) { return jit::buildStructGEP(m_builder, structVal, field); } LValue Output::buildLoad(LValue toLoad) { return jit::buildLoad(m_builder, toLoad); } LValue Output::buildStore(LValue val, LValue pointer) { return jit::buildStore(m_builder, val, pointer); } LValue Output::buildAdd(LValue lhs, LValue rhs) { return jit::buildAdd(m_builder, lhs, rhs); } LValue Output::buildBr(LBasicBlock bb) { return jit::buildBr(m_builder, bb); } LValue Output::buildRet(LValue ret) { return jit::buildRet(m_builder, ret); } LValue Output::buildRetVoid(void) { return jit::buildRetVoid(m_builder); } LValue Output::buildCast(LLVMOpcode Op, LLVMValueRef Val, LLVMTypeRef DestTy) { return LLVMBuildCast(m_builder, Op, Val, DestTy, ""); } void Output::buildGetArg() { m_arg = LLVMGetParam(m_state.m_function, 0); } void Output::buildDirectPatch(uintptr_t where) { PatchDesc desc = { PatchType::Direct }; buildPatchCommon(constInt64(where), desc, m_state.m_platformDesc.m_directSize); } void Output::buildIndirectPatch(LValue where) { PatchDesc desc = { PatchType::Indirect }; buildPatchCommon(where, desc, m_state.m_platformDesc.m_indirectSize); } void Output::buildAssistPatch(LValue where) { PatchDesc desc = { PatchType::Assist }; buildPatchCommon(where, desc, m_state.m_platformDesc.m_assistSize); } void Output::buildPatchCommon(LValue where, const PatchDesc& desc, size_t patchSize) { LValue constIndex[] = { constInt32(0), constInt32(m_state.m_platformDesc.m_pcFieldOffset / sizeof(intptr_t)) }; buildStore(where, LLVMBuildInBoundsGEP(m_builder, m_arg, constIndex, 2, "")); LValue call = buildCall(repo().patchpointInt64Intrinsic(), constIntPtr(m_stackMapsId), constInt32(patchSize), constNull(repo().ref8), constInt32(0)); LLVMSetInstructionCallConv(call, LLVMAnyRegCallConv); buildUnreachable(m_builder); // record the stack map info m_state.m_patchMap.insert(std::make_pair(m_stackMapsId++, desc)); } LValue Output::buildLoadArgIndex(int index) { LValue constIndex[] = { constInt32(0), constInt32(index) }; return buildLoad(LLVMBuildInBoundsGEP(m_builder, m_arg, constIndex, 2, "")); } LValue Output::buildStoreArgIndex(LValue val, int index) { LValue constIndex[] = { constInt32(0), constInt32(index) }; return buildStore(val, LLVMBuildInBoundsGEP(m_builder, m_arg, constIndex, 2, "")); } LValue Output::buildSelect(LValue condition, LValue taken, LValue notTaken) { return jit::buildSelect(m_builder, condition, taken, notTaken); } LValue Output::buildICmp(LIntPredicate cond, LValue left, LValue right) { return jit::buildICmp(m_builder, cond, left, right); } } <file_sep>#ifndef COMPILE_H #define COMPILE_H namespace jit { struct CompilerState; void compile(CompilerState& state); } #endif /* COMPILE_H */ <file_sep>#ifndef PLATFORMDESC_H #define PLATFORMDESC_H struct PlatformDesc { size_t m_contextSize; size_t m_pcFieldOffset; size_t m_prologueSize; size_t m_directSize; size_t m_indirectSize; size_t m_assistSize; void* m_opaque; void (*m_patchPrologue)(void* opaque, uint8_t* start, uint8_t* end); void (*m_patchDirect)(void* opaque, uint8_t* toFill); void (*m_patchIndirect)(void* opaque, uint8_t* toFill); void (*m_patchAssist)(void* opaque, uint8_t* toFill); }; #endif /* PLATFORMDESC_H */ <file_sep>{ 'includes': [ './build/common.gypi', ], 'targets': [ { 'target_name': 'main', 'type': 'executable', 'sources': [ 'main.cpp' ], 'dependencies': [ '<(DEPTH)/llvm/llvm.gyp:libllvm', ] }, ], } <file_sep>#ifndef ABBREVIATIONS_H #define ABBREVIATIONS_H #include <cstring> #include "AbbreviatedTypes.h" // This file contains short-form calls into the LLVM C API. It is meant to // save typing and make the lowering code clearer. If we ever call an LLVM C API // function more than once in the FTL lowering code, we should add a shortcut for // it here. namespace jit { static inline LType voidType(LContext context) { return LLVMVoidTypeInContext(context); } static inline LType int1Type(LContext context) { return LLVMInt1TypeInContext(context); } static inline LType int8Type(LContext context) { return LLVMInt8TypeInContext(context); } static inline LType int16Type(LContext context) { return LLVMInt16TypeInContext(context); } static inline LType int32Type(LContext context) { return LLVMInt32TypeInContext(context); } static inline LType int64Type(LContext context) { return LLVMInt64TypeInContext(context); } static inline LType intPtrType(LContext context) { return LLVMInt64TypeInContext(context); } static inline LType floatType(LContext context) { return LLVMFloatTypeInContext(context); } static inline LType doubleType(LContext context) { return LLVMDoubleTypeInContext(context); } static inline LType pointerType(LType type) { return LLVMPointerType(type, 0); } static inline LType arrayType(LType type, unsigned count) { return LLVMArrayType(type, count); } static inline LType vectorType(LType type, unsigned count) { return LLVMVectorType(type, count); } enum PackingMode { NotPacked, Packed }; static inline LType structType(LContext context, LType* elementTypes, unsigned elementCount, PackingMode packing = NotPacked) { return LLVMStructTypeInContext(context, elementTypes, elementCount, packing == Packed); } static inline LType structType(LContext context, PackingMode packing = NotPacked) { return structType(context, 0, 0, packing); } static inline LType structType(LContext context, LType element1, PackingMode packing = NotPacked) { return structType(context, &element1, 1, packing); } static inline LType structType(LContext context, LType element1, LType element2, PackingMode packing = NotPacked) { LType elements[] = { element1, element2 }; return structType(context, elements, 2, packing); } // FIXME: Make the Variadicity argument not be the last argument to functionType() so that this function // can use C++11 variadic templates // https://bugs.webkit.org/show_bug.cgi?id=141575 enum Variadicity { NotVariadic, Variadic }; static inline LType functionType(LType returnType, const LType* paramTypes, unsigned paramCount, Variadicity variadicity) { return LLVMFunctionType(returnType, const_cast<LType*>(paramTypes), paramCount, variadicity == Variadic); } template <typename VectorType> inline LType functionType(LType returnType, const VectorType& vector, Variadicity variadicity = NotVariadic) { return functionType(returnType, vector.begin(), vector.size(), variadicity); } static inline LType functionType(LType returnType, Variadicity variadicity = NotVariadic) { return functionType(returnType, 0, 0, variadicity); } static inline LType functionType(LType returnType, LType param1, Variadicity variadicity = NotVariadic) { return functionType(returnType, &param1, 1, variadicity); } static inline LType functionType(LType returnType, LType param1, LType param2, Variadicity variadicity = NotVariadic) { LType paramTypes[] = { param1, param2 }; return functionType(returnType, paramTypes, 2, variadicity); } static inline LType functionType(LType returnType, LType param1, LType param2, LType param3, Variadicity variadicity = NotVariadic) { LType paramTypes[] = { param1, param2, param3 }; return functionType(returnType, paramTypes, 3, variadicity); } static inline LType functionType(LType returnType, LType param1, LType param2, LType param3, LType param4, Variadicity variadicity = NotVariadic) { LType paramTypes[] = { param1, param2, param3, param4 }; return functionType(returnType, paramTypes, 4, variadicity); } static inline LType functionType(LType returnType, LType param1, LType param2, LType param3, LType param4, LType param5, Variadicity variadicity = NotVariadic) { LType paramTypes[] = { param1, param2, param3, param4, param5 }; return functionType(returnType, paramTypes, 5, variadicity); } static inline LType functionType(LType returnType, LType param1, LType param2, LType param3, LType param4, LType param5, LType param6, Variadicity variadicity = NotVariadic) { LType paramTypes[] = { param1, param2, param3, param4, param5, param6 }; return functionType(returnType, paramTypes, 6, variadicity); } static inline LType typeOf(LValue value) { return LLVMTypeOf(value); } static inline LType getElementType(LType value) { return LLVMGetElementType(value); } static inline unsigned mdKindID(LContext context, const char* string) { return LLVMGetMDKindIDInContext(context, string, std::strlen(string)); } static inline LValue mdString(LContext context, const char* string, unsigned length) { return LLVMMDStringInContext(context, string, length); } static inline LValue mdString(LContext context, const char* string) { return mdString(context, string, std::strlen(string)); } static inline LValue mdNode(LContext context, LValue* args, unsigned numArgs) { return LLVMMDNodeInContext(context, args, numArgs); } template <typename VectorType> static inline LValue mdNode(LContext context, const VectorType& vector) { return mdNode(context, const_cast<LValue*>(vector.begin()), vector.size()); } static inline LValue mdNode(LContext context) { return mdNode(context, 0, 0); } static inline LValue mdNode(LContext context, LValue arg1) { return mdNode(context, &arg1, 1); } static inline LValue mdNode(LContext context, LValue arg1, LValue arg2) { LValue args[] = { arg1, arg2 }; return mdNode(context, args, 2); } static inline LValue mdNode(LContext context, LValue arg1, LValue arg2, LValue arg3) { LValue args[] = { arg1, arg2, arg3 }; return mdNode(context, args, 3); } static inline void setMetadata(LValue instruction, unsigned kind, LValue metadata) { LLVMSetMetadata(instruction, kind, metadata); } static inline LValue getFirstInstruction(LBasicBlock block) { return LLVMGetFirstInstruction(block); } static inline LValue getNextInstruction(LValue instruction) { return LLVMGetNextInstruction(instruction); } static inline LValue addFunction(LModule module, const char* name, LType type) { return LLVMAddFunction(module, name, type); } static inline LValue getNamedFunction(LModule module, const char* name) { return LLVMGetNamedFunction(module, name); } static inline LValue getFirstFunction(LModule module) { return LLVMGetFirstFunction(module); } static inline LValue getNextFunction(LValue function) { return LLVMGetNextFunction(function); } static inline void setFunctionCallingConv(LValue function, LCallConv convention) { LLVMSetFunctionCallConv(function, convention); } static inline void addTargetDependentFunctionAttr(LValue function, const char* key, const char* value) { LLVMAddTargetDependentFunctionAttr(function, key, value); } static inline LLVMLinkage getLinkage(LValue global) { return LLVMGetLinkage(global); } static inline void setLinkage(LValue global, LLVMLinkage linkage) { LLVMSetLinkage(global, linkage); } static inline void setVisibility(LValue global, LLVMVisibility viz) { LLVMSetVisibility(global, viz); } static inline LLVMBool isDeclaration(LValue global) { return LLVMIsDeclaration(global); } static inline const char* getValueName(LValue global) { return LLVMGetValueName(global); } static inline LValue getNamedGlobal(LModule module, const char* name) { return LLVMGetNamedGlobal(module, name); } static inline LValue getFirstGlobal(LModule module) { return LLVMGetFirstGlobal(module); } static inline LValue getNextGlobal(LValue global) { return LLVMGetNextGlobal(global); } static inline LValue addExternFunction(LModule module, const char* name, LType type) { LValue result = addFunction(module, name, type); setLinkage(result, LLVMExternalLinkage); return result; } static inline LLVMBool createMemoryBufferWithContentsOfFile(const char* path, LLVMMemoryBufferRef* outMemBuf, char** outMessage) { return LLVMCreateMemoryBufferWithContentsOfFile(path, outMemBuf, outMessage); } static inline LLVMBool parseBitcodeInContext(LLVMContextRef contextRef, LLVMMemoryBufferRef memBuf, LModule* outModule, char** outMessage) { return LLVMParseBitcodeInContext(contextRef, memBuf, outModule, outMessage); } static inline void disposeMemoryBuffer(LLVMMemoryBufferRef memBuf) { LLVMDisposeMemoryBuffer(memBuf); } static inline LModule moduleCreateWithNameInContext(const char* moduleID, LContext context) { return LLVMModuleCreateWithNameInContext(moduleID, context); } static inline void disposeModule(LModule m) { LLVMDisposeModule(m); } static inline void disposeMessage(char* outMsg) { LLVMDisposeMessage(outMsg); } static inline LValue getParam(LValue function, unsigned index) { return LLVMGetParam(function, index); } static inline void getParamTypes(LType function, LType* dest) { return LLVMGetParamTypes(function, dest); } static inline LValue getUndef(LType type) { return LLVMGetUndef(type); } enum BitExtension { ZeroExtend, SignExtend }; static inline LValue constInt(LType type, unsigned long long value, BitExtension extension = ZeroExtend) { return LLVMConstInt(type, value, extension == SignExtend); } static inline LValue constReal(LType type, double value) { return LLVMConstReal(type, value); } static inline LValue constIntToPtr(LValue value, LType type) { return LLVMConstIntToPtr(value, type); } static inline LValue constNull(LType type) { return LLVMConstNull(type); } static inline LValue constBitCast(LValue value, LType type) { return LLVMConstBitCast(value, type); } static inline LBasicBlock getFirstBasicBlock(LValue function) { return LLVMGetFirstBasicBlock(function); } static inline LBasicBlock getNextBasicBlock(LBasicBlock block) { return LLVMGetNextBasicBlock(block); } static inline LBasicBlock appendBasicBlock(LContext context, LValue function, const char* name = "") { return LLVMAppendBasicBlockInContext(context, function, name); } static inline LBasicBlock insertBasicBlock(LContext context, LBasicBlock beforeBasicBlock, const char* name = "") { return LLVMInsertBasicBlockInContext(context, beforeBasicBlock, name); } static inline LValue buildPhi(LBuilder builder, LType type) { return LLVMBuildPhi(builder, type, ""); } static inline void addIncoming(LValue phi, const LValue* values, const LBasicBlock* blocks, unsigned numPredecessors) { LLVMAddIncoming(phi, const_cast<LValue*>(values), const_cast<LBasicBlock*>(blocks), numPredecessors); } static inline LValue buildAlloca(LBuilder builder, LType type) { return LLVMBuildAlloca(builder, type, ""); } static inline LValue buildAdd(LBuilder builder, LValue left, LValue right) { return LLVMBuildAdd(builder, left, right, ""); } static inline LValue buildSub(LBuilder builder, LValue left, LValue right) { return LLVMBuildSub(builder, left, right, ""); } static inline LValue buildMul(LBuilder builder, LValue left, LValue right) { return LLVMBuildMul(builder, left, right, ""); } static inline LValue buildDiv(LBuilder builder, LValue left, LValue right) { return LLVMBuildSDiv(builder, left, right, ""); } static inline LValue buildRem(LBuilder builder, LValue left, LValue right) { return LLVMBuildSRem(builder, left, right, ""); } static inline LValue buildNeg(LBuilder builder, LValue value) { return LLVMBuildNeg(builder, value, ""); } static inline LValue buildFAdd(LBuilder builder, LValue left, LValue right) { return LLVMBuildFAdd(builder, left, right, ""); } static inline LValue buildFSub(LBuilder builder, LValue left, LValue right) { return LLVMBuildFSub(builder, left, right, ""); } static inline LValue buildFMul(LBuilder builder, LValue left, LValue right) { return LLVMBuildFMul(builder, left, right, ""); } static inline LValue buildFDiv(LBuilder builder, LValue left, LValue right) { return LLVMBuildFDiv(builder, left, right, ""); } static inline LValue buildFRem(LBuilder builder, LValue left, LValue right) { return LLVMBuildFRem(builder, left, right, ""); } static inline LValue buildFNeg(LBuilder builder, LValue value) { return LLVMBuildFNeg(builder, value, ""); } static inline LValue buildAnd(LBuilder builder, LValue left, LValue right) { return LLVMBuildAnd(builder, left, right, ""); } static inline LValue buildOr(LBuilder builder, LValue left, LValue right) { return LLVMBuildOr(builder, left, right, ""); } static inline LValue buildXor(LBuilder builder, LValue left, LValue right) { return LLVMBuildXor(builder, left, right, ""); } static inline LValue buildShl(LBuilder builder, LValue left, LValue right) { return LLVMBuildShl(builder, left, right, ""); } static inline LValue buildAShr(LBuilder builder, LValue left, LValue right) { return LLVMBuildAShr(builder, left, right, ""); } static inline LValue buildLShr(LBuilder builder, LValue left, LValue right) { return LLVMBuildLShr(builder, left, right, ""); } static inline LValue buildNot(LBuilder builder, LValue value) { return LLVMBuildNot(builder, value, ""); } static inline LValue buildLoad(LBuilder builder, LValue pointer) { return LLVMBuildLoad(builder, pointer, ""); } static inline LValue buildStructGEP(LBuilder builder, LValue pointer, unsigned idx) { return LLVMBuildStructGEP(builder, pointer, idx, ""); } static inline LValue buildStore(LBuilder builder, LValue value, LValue pointer) { return LLVMBuildStore(builder, value, pointer); } static inline LValue buildSExt(LBuilder builder, LValue value, LType type) { return LLVMBuildSExt(builder, value, type, ""); } static inline LValue buildZExt(LBuilder builder, LValue value, LType type) { return LLVMBuildZExt(builder, value, type, ""); } static inline LValue buildFPToSI(LBuilder builder, LValue value, LType type) { return LLVMBuildFPToSI(builder, value, type, ""); } static inline LValue buildFPToUI(LBuilder builder, LValue value, LType type) { return LLVMBuildFPToUI(builder, value, type, ""); } static inline LValue buildSIToFP(LBuilder builder, LValue value, LType type) { return LLVMBuildSIToFP(builder, value, type, ""); } static inline LValue buildUIToFP(LBuilder builder, LValue value, LType type) { return LLVMBuildUIToFP(builder, value, type, ""); } static inline LValue buildIntCast(LBuilder builder, LValue value, LType type) { return LLVMBuildIntCast(builder, value, type, ""); } static inline LValue buildFPCast(LBuilder builder, LValue value, LType type) { return LLVMBuildFPCast(builder, value, type, ""); } static inline LValue buildIntToPtr(LBuilder builder, LValue value, LType type) { return LLVMBuildIntToPtr(builder, value, type, ""); } static inline LValue buildPtrToInt(LBuilder builder, LValue value, LType type) { return LLVMBuildPtrToInt(builder, value, type, ""); } static inline LValue buildBitCast(LBuilder builder, LValue value, LType type) { return LLVMBuildBitCast(builder, value, type, ""); } static inline LValue buildICmp(LBuilder builder, LIntPredicate cond, LValue left, LValue right) { return LLVMBuildICmp(builder, cond, left, right, ""); } static inline LValue buildFCmp(LBuilder builder, LRealPredicate cond, LValue left, LValue right) { return LLVMBuildFCmp(builder, cond, left, right, ""); } static inline LValue buildInsertElement(LBuilder builder, LValue vector, LValue element, LValue index) { return LLVMBuildInsertElement(builder, vector, element, index, ""); } enum SynchronizationScope { SingleThread, CrossThread }; static inline LValue buildFence(LBuilder builder, LAtomicOrdering ordering, SynchronizationScope scope = CrossThread) { return LLVMBuildFence(builder, ordering, scope == SingleThread, ""); } static inline LValue buildCall(LBuilder builder, LValue function, const LValue* args, unsigned numArgs) { return LLVMBuildCall(builder, function, const_cast<LValue*>(args), numArgs, ""); } template <typename VectorType> inline LValue buildCall(LBuilder builder, LValue function, const VectorType& vector) { return buildCall(builder, function, vector.begin(), vector.size()); } static inline LValue buildCall(LBuilder builder, LValue function) { return buildCall(builder, function, 0, 0); } static inline LValue buildCall(LBuilder builder, LValue function, LValue arg1) { return buildCall(builder, function, &arg1, 1); } template <typename... Args> LValue buildCall(LBuilder builder, LValue function, LValue arg1, Args... args) { LValue argsArray[] = { arg1, args... }; return buildCall(builder, function, argsArray, sizeof(argsArray) / sizeof(LValue)); } static inline void setInstructionCallingConvention(LValue instruction, LCallConv callingConvention) { LLVMSetInstructionCallConv(instruction, callingConvention); } static inline LValue buildExtractValue(LBuilder builder, LValue aggVal, unsigned index) { return LLVMBuildExtractValue(builder, aggVal, index, ""); } static inline LValue buildSelect(LBuilder builder, LValue condition, LValue taken, LValue notTaken) { return LLVMBuildSelect(builder, condition, taken, notTaken, ""); } static inline LValue buildBr(LBuilder builder, LBasicBlock destination) { return LLVMBuildBr(builder, destination); } static inline LValue buildCondBr(LBuilder builder, LValue condition, LBasicBlock taken, LBasicBlock notTaken) { return LLVMBuildCondBr(builder, condition, taken, notTaken); } static inline LValue buildSwitch(LBuilder builder, LValue value, LBasicBlock fallThrough, unsigned numCases) { return LLVMBuildSwitch(builder, value, fallThrough, numCases); } static inline void addCase(LValue switchInst, LValue value, LBasicBlock target) { LLVMAddCase(switchInst, value, target); } template <typename VectorType> static inline LValue buildSwitch(LBuilder builder, LValue value, const VectorType& cases, LBasicBlock fallThrough) { LValue result = buildSwitch(builder, value, fallThrough, cases.size()); for (unsigned i = 0; i < cases.size(); ++i) addCase(result, cases[i].value(), cases[i].target()); return result; } static inline LValue buildRet(LBuilder builder, LValue value) { return LLVMBuildRet(builder, value); } static inline LValue buildRetVoid(LBuilder builder) { return LLVMBuildRetVoid(builder); } static inline LValue buildUnreachable(LBuilder builder) { return LLVMBuildUnreachable(builder); } static inline void setTailCall(LValue callInst, bool istail) { return LLVMSetTailCall(callInst, istail); } static inline void dumpModule(LModule module) { LLVMDumpModule(module); } static inline void verifyModule(LModule module) { char* error = 0; LLVMVerifyModule(module, LLVMAbortProcessAction, &error); LLVMDisposeMessage(error); } static inline LValue constInlineAsm(LType Ty, const char* AsmString, const char* Constraints, bool HasSideEffects, bool IsAlignStack) { return LLVMConstInlineAsm(Ty, AsmString, Constraints, HasSideEffects, IsAlignStack); } } #endif /* ABBREVIATIONS_H */ <file_sep>#include "CommonValues.h" namespace jit { CommonValues::CommonValues(LContext context) : voidType(jit::voidType(context)) , boolean(int1Type(context)) , int8(int8Type(context)) , int16(int16Type(context)) , int32(int32Type(context)) , int64(int64Type(context)) , intPtr(intPtrType(context)) , floatType(jit::floatType(context)) , doubleType(jit::doubleType(context)) , ref8(pointerType(int8)) , ref16(pointerType(int16)) , ref32(pointerType(int32)) , ref64(pointerType(int64)) , refPtr(pointerType(intPtr)) , refFloat(pointerType(floatType)) , refDouble(pointerType(doubleType)) , booleanTrue(constInt(boolean, true, ZeroExtend)) , booleanFalse(constInt(boolean, false, ZeroExtend)) , int8Zero(constInt(int8, 0, SignExtend)) , int32Zero(constInt(int32, 0, SignExtend)) , int32One(constInt(int32, 1, SignExtend)) , int64Zero(constInt(int64, 0, SignExtend)) , intPtrZero(constInt(intPtr, 0, SignExtend)) , intPtrOne(constInt(intPtr, 1, SignExtend)) , intPtrTwo(constInt(intPtr, 2, SignExtend)) , intPtrThree(constInt(intPtr, 3, SignExtend)) , intPtrFour(constInt(intPtr, 4, SignExtend)) , intPtrEight(constInt(intPtr, 8, SignExtend)) , intPtrPtr(constInt(intPtr, sizeof(void*), SignExtend)) , doubleZero(constReal(doubleType, 0)) , rangeKind(mdKindID(context, "range")) , profKind(mdKindID(context, "prof")) , branchWeights(mdString(context, "branch_weights")) , m_context(context) , m_module(0) { } } <file_sep>#include "InitializeLLVM.h" #include "LLVMHeaders.h" #include <assert.h> #include <llvm/Support/CommandLine.h> #include <stdio.h> template <typename... Args> void initCommandLine(Args... args) { const char* theArgs[] = { args... }; llvm::cl::ParseCommandLineOptions(sizeof(theArgs) / sizeof(const char*), theArgs); } static void llvmCrash(const char*) __attribute__((noreturn)); void llvmCrash(const char* reason) { fprintf(stderr, "LLVM fatal error: %s", reason); assert(false); __builtin_unreachable(); } static void initializeAndGetLLVMAPI(void) { LLVMInstallFatalErrorHandler(llvmCrash); if (!LLVMStartMultithreaded()) { llvmCrash("Could not start LLVM multithreading"); } LLVMLinkInMCJIT(); // You think you want to call LLVMInitializeNativeTarget()? Think again. This presumes that // LLVM was ./configured correctly, which won't be the case in cross-compilation situations. LLVMInitializeX86TargetInfo(); LLVMInitializeX86Target(); LLVMInitializeX86TargetMC(); LLVMInitializeX86AsmPrinter(); LLVMInitializeX86Disassembler(); #if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 6) // It's OK to have fast ISel, if it was requested. #else // We don't have enough support for fast ISel. Disable it. *enableFastISel = false; #endif initCommandLine("-enable-patchpoint-liveness=true"); } void initLLVM(void) { initializeAndGetLLVMAPI(); } <file_sep>#!/bin/sh GYP_GENERATORS=ninja ../gyp-read-only/gyp --depth=. build/all.gyp --no-parallel ninja -C out/Debug <file_sep>#ifndef REGISTERS_H #define REGISTERS_H namespace jit { enum AMD64 { RAX = 0, RCX = 1, RDX = 2, RSP = 4, RBP = 5, R11 = 11, RSI = 6, RDI = 7, R8 = 8, R9 = 9, R12 = 12, R13 = 13, R14 = 14, R15 = 15, RBX = 3, }; class Reg { public: Reg(void) : m_val(invalid()) { } Reg(int val) : m_val(val) { } Reg(AMD64 val) : m_val(val) { } int val() const { return m_val; } bool isFloat() const { return m_isFloat; } static inline int invalid() { return -1; } private: int m_val; protected: bool m_isFloat = false; }; class FPRReg : public Reg { public: FPRReg(int val) : Reg(val) { m_isFloat = true; } }; class DWARFRegister { public: DWARFRegister() : m_dwarfRegNum(-1) { } explicit DWARFRegister(int16_t dwarfRegNum) : m_dwarfRegNum(dwarfRegNum) { } int16_t dwarfRegNum() const { return m_dwarfRegNum; } Reg reg() const; private: int16_t m_dwarfRegNum; }; } #endif /* REGISTERS_H */ <file_sep>#include "log.h" #include <stdarg.h> #include <stdio.h> #include <unistd.h> #include <sys/syscall.h> /* For SYS_xxx definitions */ #ifdef __ANDROID__ #include <android/log.h> #define TAG "libhoudini" #endif #include <time.h> #ifdef LLVMLOG_LEVEL static FILE* g_log = stdout; void __my_log(char type, const char* fmt, ...) { if (!g_log) return; va_list args; va_start(args, fmt); int bytes = vsnprintf(nullptr, 0, fmt, args); va_end(args); char buf[bytes + 2]; va_start(args, fmt); vsnprintf(buf, bytes + 1, fmt, args); va_end(args); if (buf[bytes - 1] != '\n') { buf[bytes] = '\n'; buf[bytes + 1] = '\0'; } #ifndef __ANDROID__ fprintf(g_log, "%c:%lu:%lu: ", type, (long)syscall(__NR_gettid, 0), (long)clock()); fputs(buf, g_log); fflush(g_log); #else int android_type; switch (type) { case 'V': android_type = ANDROID_LOG_VERBOSE; break; case 'P': case 'D': android_type = ANDROID_LOG_DEBUG; break; case 'E': android_type = ANDROID_LOG_ERROR; break; default: android_type = ANDROID_LOG_INFO; break; } __android_log_write(android_type, TAG, buf); #endif } void __my_assert_fail(const char* msg, const char* file_name, int lineno) { #ifndef __ANDROID__ if (!g_log) { __builtin_trap(); } fprintf(g_log, "%lu:%lu: ASSERT FAILED:%s:%s:%d.\n", (long)syscall(__NR_gettid, 0), (long)clock(), msg, file_name, lineno); fflush(g_log); #else __android_log_print(ANDROID_LOG_ERROR, TAG, "ASSERT FAILED:%s:%s:%d.", msg, file_name, lineno); #endif __builtin_trap(); } #endif <file_sep>#ifndef STACKMAPS_H #define STACKMAPS_H #include <assert.h> #include <stdint.h> #include <vector> #include <unordered_map> #include <bitset> #include "Registers.h" namespace jit { class DataView { public: DataView(const uint8_t* data) : m_data(data) { } template <typename T> T read(unsigned& off, bool littenEndian) { assert(littenEndian == true); T t = *reinterpret_cast<const T*>(m_data + off); off += sizeof(T); return t; } private: const uint8_t* m_data; }; // lower 32 for gerneral purpose register // upper 32 for fp register typedef std::bitset<64> RegisterSet; struct StackMaps { struct ParseContext { unsigned version; DataView* view; unsigned offset; }; struct Constant { int64_t integer; void parse(ParseContext&); }; struct StackSize { uint64_t functionOffset; uint64_t size; void parse(ParseContext&); }; struct Location { enum Kind : int8_t { Unprocessed, Register, Direct, Indirect, Constant, ConstantIndex }; DWARFRegister dwarfReg; uint8_t size; Kind kind; int32_t offset; void parse(ParseContext&); }; // FIXME: Investigate how much memory this takes and possibly prune it from the // format we keep around in FTL::JITCode. I suspect that it would be most awesome to // have a CompactStackMaps struct that lossily stores only that subset of StackMaps // and Record that we actually need for OSR exit. // https://bugs.webkit.org/show_bug.cgi?id=130802 struct LiveOut { DWARFRegister dwarfReg; uint8_t size; void parse(ParseContext&); }; struct Record { uint32_t patchpointID; uint32_t instructionOffset; uint16_t flags; std::vector<Location> locations; std::vector<LiveOut> liveOuts; bool parse(ParseContext&); RegisterSet liveOutsSet() const; RegisterSet locationSet() const; RegisterSet usedRegisterSet() const; }; unsigned version; std::vector<StackSize> stackSizes; std::vector<Constant> constants; std::vector<Record> records; bool parse(DataView*); // Returns true on parse success, false on failure. Failure means that LLVM is signaling compile failure to us. typedef std::unordered_map<uint32_t, std::vector<Record> > RecordMap; RecordMap computeRecordMap() const; unsigned stackSize() const; }; } #endif /* STACKMAPS_H */ <file_sep>#ifndef INTRINSICREPOSITORY_H #define INTRINSICREPOSITORY_H #include "CommonValues.h" #define FOR_EACH_FTL_INTRINSIC(macro) \ macro(ceil64, "llvm.ceil.f64", functionType(doubleType, doubleType)) \ macro(ctlz32, "llvm.ctlz.i32", functionType(int32, int32, boolean)) \ macro(addWithOverflow32, "llvm.sadd.with.overflow.i32", functionType(structType(m_context, int32, boolean), int32, int32)) \ macro(addWithOverflow64, "llvm.sadd.with.overflow.i64", functionType(structType(m_context, int64, boolean), int64, int64)) \ macro(doubleAbs, "llvm.fabs.f64", functionType(doubleType, doubleType)) \ macro(doubleSin, "llvm.sin.f64", functionType(doubleType, doubleType)) \ macro(doubleCos, "llvm.cos.f64", functionType(doubleType, doubleType)) \ macro(doublePow, "llvm.pow.f64", functionType(doubleType, doubleType, doubleType)) \ macro(doublePowi, "llvm.powi.f64", functionType(doubleType, doubleType, int32)) \ macro(doubleSqrt, "llvm.sqrt.f64", functionType(doubleType, doubleType)) \ macro(doubleLog, "llvm.log.f64", functionType(doubleType, doubleType)) \ macro(frameAddress, "llvm.frameaddress", functionType(pointerType(int8), int32)) \ macro(mulWithOverflow32, "llvm.smul.with.overflow.i32", functionType(structType(m_context, int32, boolean), int32, int32)) \ macro(mulWithOverflow64, "llvm.smul.with.overflow.i64", functionType(structType(m_context, int64, boolean), int64, int64)) \ macro(patchpointInt64, "llvm.experimental.patchpoint.i64", functionType(int64, int64, int32, ref8, int32, Variadic)) \ macro(patchpointVoid, "llvm.experimental.patchpoint.void", functionType(voidType, int64, int32, ref8, int32, Variadic)) \ macro(stackmap, "llvm.experimental.stackmap", functionType(voidType, int64, int32, Variadic)) \ macro(subWithOverflow32, "llvm.ssub.with.overflow.i32", functionType(structType(m_context, int32, boolean), int32, int32)) \ macro(subWithOverflow64, "llvm.ssub.with.overflow.i64", functionType(structType(m_context, int64, boolean), int64, int64)) \ macro(trap, "llvm.trap", functionType(voidType)) \ macro(x86SSE2CvtTSD2SI, "llvm.x86.sse2.cvttsd2si", functionType(int32, vectorType(doubleType, 2))) namespace jit { class IntrinsicRepository : public CommonValues { public: IntrinsicRepository(LContext, LModule); #define INTRINSIC_GETTER(ourName, llvmName, type) \ LLVMValueRef ourName##Intrinsic() { \ if (!m_##ourName) \ return ourName##IntrinsicSlow(); \ return m_##ourName; \ } FOR_EACH_FTL_INTRINSIC(INTRINSIC_GETTER) #undef INTRINSIC_GETTER private: #define INTRINSIC_GETTER_SLOW_DECLARATION(ourName, llvmName, type) \ LLVMValueRef ourName##IntrinsicSlow(); FOR_EACH_FTL_INTRINSIC(INTRINSIC_GETTER_SLOW_DECLARATION) #undef INTRINSIC_GETTER #define INTRINSIC_FIELD_DECLARATION(ourName, llvmName, type) LLVMValueRef m_##ourName; FOR_EACH_FTL_INTRINSIC(INTRINSIC_FIELD_DECLARATION) #undef INTRINSIC_FIELD_DECLARATION LContext m_context; }; } #endif /* INTRINSICREPOSITORY_H */ <file_sep>#ifndef COMMONVALUES_H #define COMMONVALUES_H #include "Abbreviations.h" namespace jit { class CommonValues { public: CommonValues(LContext context); CommonValues(const CommonValues&) = delete; const CommonValues& operator=(const CommonValues&) = delete; void initialize(LModule module) { m_module = module; } const LType voidType; const LType boolean; const LType int8; const LType int16; const LType int32; const LType int64; const LType intPtr; const LType floatType; const LType doubleType; const LType ref8; const LType ref16; const LType ref32; const LType ref64; const LType refPtr; const LType refFloat; const LType refDouble; const LValue booleanTrue; const LValue booleanFalse; const LValue int8Zero; const LValue int32Zero; const LValue int32One; const LValue int64Zero; const LValue intPtrZero; const LValue intPtrOne; const LValue intPtrTwo; const LValue intPtrThree; const LValue intPtrFour; const LValue intPtrEight; const LValue intPtrPtr; const LValue doubleZero; const unsigned rangeKind; const unsigned profKind; const LValue branchWeights; LContext const m_context; LModule m_module; }; } #endif /* COMMONVALUES_H */ <file_sep>#ifndef LOG_H #define LOG_H #ifdef LLVMLOG_LEVEL // always print LOGE #define LOGE(...) __my_log('E', __VA_ARGS__) #define EMASSERT(p) \ if (!(p)) { \ __my_assert_fail(#p, __FILE__, __LINE__); \ } #if LLVMLOG_LEVEL >= 10 #define LOGV(...) __my_log('V', __VA_ARGS__) #endif // DEFINING LOGV #if LLVMLOG_LEVEL >= 4 // debug log #define LOGD(...) __my_log('D', __VA_ARGS__) #endif #if LLVMLOG_LEVEL >= 5 // performance log #define LOGP(...) __my_log('P', __VA_ARGS__) #endif #ifdef __cplusplus extern "C" { #endif //__cplusplus void __my_log(char type, const char* fmt, ...) __attribute__((format(printf, 2, 3))); void __my_assert_fail(const char* msg, const char* file_name, int lineno) __attribute__((noreturn)); #ifdef __cplusplus } #endif //__cplusplus #endif // LLVMLOG_LEVEL #ifndef LOGE #define LOGE(...) #endif #ifndef LOGV #define LOGV(...) #endif #ifndef LOGD #define LOGD(...) #endif #ifndef LOGP #define LOGP(...) #endif #ifndef EMASSERT #define EMASSERT(p) #endif #endif /* LOG_H */ <file_sep>#include <assert.h> #include <string.h> #include "log.h" #include "CompilerState.h" #include "Compile.h" #define SECTION_NAME_PREFIX "." #define SECTION_NAME(NAME) (SECTION_NAME_PREFIX NAME) namespace jit { typedef CompilerState State; static inline size_t round_up(size_t s, unsigned alignment) { return (s + alignment - 1) & ~(alignment - 1); } static uint8_t* mmAllocateCodeSection( void* opaqueState, uintptr_t size, unsigned alignment, unsigned, const char* sectionName) { State& state = *static_cast<State*>(opaqueState); state.m_codeSectionList.push_back(jit::ByteBuffer()); state.m_codeSectionNames.push_back(sectionName); jit::ByteBuffer& bb(state.m_codeSectionList.back()); size_t additionSize = state.m_platformDesc.m_prologueSize; size += additionSize; bb.resize(size); assert((reinterpret_cast<uintptr_t>(bb.data()) & (alignment - 1)) == 0); return const_cast<uint8_t*>(bb.data() + additionSize); } static uint8_t* mmAllocateDataSection( void* opaqueState, uintptr_t size, unsigned alignment, unsigned, const char* sectionName, LLVMBool) { State& state = *static_cast<State*>(opaqueState); state.m_dataSectionList.push_back(jit::ByteBuffer()); state.m_dataSectionNames.push_back(sectionName); jit::ByteBuffer& bb(state.m_dataSectionList.back()); bb.resize(size); assert((reinterpret_cast<uintptr_t>(bb.data()) & (alignment - 1)) == 0); if (!strcmp(sectionName, SECTION_NAME("llvm_stackmaps"))) { state.m_stackMapsSection = &bb; } return const_cast<uint8_t*>(bb.data()); } static LLVMBool mmApplyPermissions(void*, char**) { return false; } static void mmDestroy(void*) { } void compile(State& state) { LLVMMCJITCompilerOptions options; LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); options.OptLevel = 2; LLVMExecutionEngineRef engine; char* error = 0; options.MCJMM = LLVMCreateSimpleMCJITMemoryManager( &state, mmAllocateCodeSection, mmAllocateDataSection, mmApplyPermissions, mmDestroy); if (LLVMCreateMCJITCompilerForModule(&engine, state.m_module, &options, sizeof(options), &error)) { LOGE("FATAL: Could not create LLVM execution engine: %s", error); assert(false); } LLVMModuleRef module = state.m_module; LLVMPassManagerRef functionPasses = 0; LLVMPassManagerRef modulePasses; LLVMTargetDataRef targetData = LLVMGetExecutionEngineTargetData(engine); char* stringRepOfTargetData = LLVMCopyStringRepOfTargetData(targetData); LLVMSetDataLayout(module, stringRepOfTargetData); free(stringRepOfTargetData); LLVMPassManagerBuilderRef passBuilder = LLVMPassManagerBuilderCreate(); LLVMPassManagerBuilderSetOptLevel(passBuilder, 2); LLVMPassManagerBuilderUseInlinerWithThreshold(passBuilder, 275); LLVMPassManagerBuilderSetSizeLevel(passBuilder, 0); functionPasses = LLVMCreateFunctionPassManagerForModule(module); modulePasses = LLVMCreatePassManager(); LLVMPassManagerBuilderPopulateFunctionPassManager(passBuilder, functionPasses); LLVMPassManagerBuilderPopulateModulePassManager(passBuilder, modulePasses); LLVMPassManagerBuilderDispose(passBuilder); LLVMInitializeFunctionPassManager(functionPasses); for (LLVMValueRef function = LLVMGetFirstFunction(module); function; function = LLVMGetNextFunction(function)) LLVMRunFunctionPassManager(functionPasses, function); LLVMFinalizeFunctionPassManager(functionPasses); LLVMRunPassManager(modulePasses, module); state.m_entryPoint = reinterpret_cast<void*>(LLVMGetPointerToGlobal(engine, state.m_function)); if (functionPasses) LLVMDisposePassManager(functionPasses); LLVMDisposePassManager(modulePasses); LLVMDisposeExecutionEngine(engine); } } <file_sep>#include "CompilerState.h" namespace jit { CompilerState::CompilerState(const char* moduleName, const PlatformDesc& desc) : m_stackMapsSection(nullptr) , m_module(nullptr) , m_function(nullptr) , m_context(nullptr) , m_entryPoint(nullptr) , m_platformDesc(desc) { m_context = LLVMContextCreate(); m_module = LLVMModuleCreateWithNameInContext("test", m_context); } CompilerState::~CompilerState() { LLVMContextDispose(m_context); } } <file_sep>#include <assert.h> #include "StackMaps.h" #include "CompilerState.h" #include "Abbreviations.h" #include "Link.h" namespace jit { void link(CompilerState& state) { StackMaps sm; DataView dv(state.m_stackMapsSection->data()); sm.parse(&dv); auto rm = sm.computeRecordMap(); assert(state.m_codeSectionList.size() == 1); uint8_t* prologue = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(state.m_codeSectionList.front().data())); uint8_t* body = static_cast<uint8_t*>(state.m_entryPoint); PlatformDesc& platformDesc = state.m_platformDesc; state.m_platformDesc.m_patchPrologue(platformDesc.m_opaque, prologue, body); for (auto& record : rm) { assert(record.second.size() == 1); auto found = state.m_patchMap.find(record.first); assert(found != state.m_patchMap.end()); PatchDesc& patchDesc = found->second; switch (patchDesc.m_type) { case PatchType::Direct: { platformDesc.m_patchDirect(platformDesc.m_opaque, body + record.second[0].instructionOffset); } break; case PatchType::Indirect: { platformDesc.m_patchIndirect(platformDesc.m_opaque, body + record.second[0].instructionOffset); } break; default: __builtin_unreachable(); } } } } <file_sep># llvm-toy <file_sep>#include "IntrinsicRepository.h" namespace jit { IntrinsicRepository::IntrinsicRepository(LContext context, LModule module) : CommonValues(context) #define INTRINSIC_INITIALIZATION(ourName, llvmName, type) , m_##ourName(0) FOR_EACH_FTL_INTRINSIC(INTRINSIC_INITIALIZATION) #undef INTRINSIC_INITIALIZATION { initialize(module); } #define INTRINSIC_GETTER_SLOW_DEFINITION(ourName, llvmName, type) \ LValue IntrinsicRepository::ourName##IntrinsicSlow() \ { \ m_##ourName = addExternFunction(m_module, llvmName, type); \ return m_##ourName; \ } FOR_EACH_FTL_INTRINSIC(INTRINSIC_GETTER_SLOW_DEFINITION) #undef INTRINSIC_GETTER } <file_sep>#ifndef COMPILERSTATE_H #define COMPILERSTATE_H #include <vector> #include <unordered_map> #include <list> #include <string> #include <stdint.h> #include "LLVMHeaders.h" #include "PlatformDesc.h" namespace jit { enum class PatchType { Direct, Indirect, Assist, }; struct PatchDesc { PatchType m_type; }; typedef std::vector<uint8_t> ByteBuffer; typedef std::list<ByteBuffer> BufferList; typedef std::list<std::string> StringList; typedef std::unordered_map<unsigned /* stackmaps id */, PatchDesc> PatchMap; struct CompilerState { BufferList m_codeSectionList; BufferList m_dataSectionList; StringList m_codeSectionNames; StringList m_dataSectionNames; ByteBuffer* m_stackMapsSection; PatchMap m_patchMap; LLVMModuleRef m_module; LLVMValueRef m_function; LLVMContextRef m_context; void* m_entryPoint; struct PlatformDesc m_platformDesc; CompilerState(const char* moduleName, const PlatformDesc& desc); ~CompilerState(); CompilerState(const CompilerState&) = delete; const CompilerState& operator=(const CompilerState&) = delete; }; } #endif /* COMPILERSTATE_H */ <file_sep>#ifndef ABBREVIATEDTYPES_H #define ABBREVIATEDTYPES_H #include "LLVMHeaders.h" namespace jit { typedef LLVMAtomicOrdering LAtomicOrdering; typedef LLVMBasicBlockRef LBasicBlock; typedef LLVMBuilderRef LBuilder; typedef LLVMCallConv LCallConv; typedef LLVMContextRef LContext; typedef LLVMIntPredicate LIntPredicate; typedef LLVMLinkage LLinkage; typedef LLVMModuleRef LModule; typedef LLVMRealPredicate LRealPredicate; typedef LLVMTypeRef LType; typedef LLVMValueRef LValue; typedef LLVMMemoryBufferRef LMemoryBuffer; } #endif /* ABBREVIATEDTYPES_H */ <file_sep>#ifndef INITIALIZELLVM_H #define INITIALIZELLVM_H extern "C" void initLLVM(void); #endif /* INITIALIZELLVM_H */ <file_sep>#ifndef LINK_H #define LINK_H namespace jit { void link(CompilerState& state); } #endif /* LINK_H */
c9f08a4e412101cf714585939e59013ad650c100
[ "Markdown", "Python", "C", "C++", "Shell" ]
30
Python
jjykh/llvm-toy
09b25365ade0910ced41f6981215d9df9d2c49c5
4a2c91defbcbe084970377a6a18eff1952255a00
refs/heads/master
<file_sep>package one.digitalinnovation.estoquedecerveja.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class CervejaExceededException extends Exception { public CervejaExceededException(Long id, int quantityToIncrement) { super(String.format("Cervejas com %s ID informado excede a capacidade máxima de estoque: %s", id, quantityToIncrement)); } } <file_sep>package one.digitalinnovation.estoquedecerveja.mapper; import one.digitalinnovation.estoquedecerveja.dto.CervejaDTO; import one.digitalinnovation.estoquedecerveja.entity.Cerveja; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface CervejaMapper{ CervejaMapper INSTANCE = Mappers.getMapper(CervejaMapper.class); Cerveja toModel(CervejaDTO beerDTO); CervejaDTO toDTO(Cerveja beer); }
59a0c2586c0550c9249fd5dae0ac9c909006b42a
[ "Java" ]
2
Java
daniellepatricio/estoquedecervejaREST
ff1d7e11a09575012a664a3b1b84606a2f506342
1f78bbce9f0e38072820b94deb62b05b3c2b2048
refs/heads/master
<repo_name>aheumaier/azure-nvidia-linux-desktop<file_sep>/scripts/test/setup_ubuntu_desktop.bats #!/usr/bin/env bats load 'libs/bats-support/load' load 'libs/bats-assert/load' load 'test_helper' profile_script="./scripts/setup_ubuntu_desktop.sh" setup() { DOCKER_SUT_ID=$(docker run -id ubuntu:18.04) } function teardown() { docker stop $DOCKER_SUT_ID && docker rm $DOCKER_SUT_ID } @test "test install_system_packages() should install provided packes" { # skip source ${profile_script} function sudo() { docker_mock "${*}"; } export -f sudo declare -ar PACKAGES=( wget curl gnupg2 x11vnc libusb-0.1-4 libxvidcore4 libaa1 libfaad2 libxss1 libopencore-amrnb0 libopencore-amrwb0 ) run install_system_packages assert_success } @test "test install_nvidia_repos() should install nvidia_repos" { # skip NVIDIA_PKG="nvidia-diag-driver-local-repo-ubuntu1804-415.25_1.0-1_amd64.deb" NVIDIA_REPO="http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64" TMP_DIR="/tmp" source ${profile_script} function sudo() { docker_mock "${*}"; } export -f sudo function wget() { docker_mock "wget" "${*}"; } export -f wget declare -ar PACKAGES=( wget curl gnupg2 ) run install_system_packages run install_nvidia_repos assert_success } @test "test install_cuda_repos() should install cuda_repos" { # skip CUDA_PKG="cuda-repo-ubuntu1804_10.0.130-1_amd64.deb" NVIDIA_REPO="http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64" TMP_DIR="/tmp" source ${profile_script} function sudo() { docker_mock "${*}"; } export -f sudo function wget() { docker_mock "wget" "${*}"; } export -f wget declare -ar PACKAGES=( wget curl gnupg2 ) run install_system_packages run install_cuda_repos assert_success } @test "test setup_x11vnc() should be properly configured" { skip VNC_PASS=$(openssl rand -base64 12) TMP_DIR="/tmp" source ${profile_script} function systemctl() { echo "This is running ${*}"; } export -f systemctl function sudo() { docker_mock "${*}"; } export -f sudo declare -ar PACKAGES=( wget curl gnupg2 x11vnc ) run install_system_packages run setup_x11vnc assert_success run cat /etc/x11vnc.passwd assert_output ${VNC_PASS} } @test "test run_main should fail on missin env var" { # skip NVIDIA_PKG="nvidia-diag-driver-local-repo-ubuntu1804-415.25_1.0-1_amd64.deb" NVIDIA_REPO="http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64" CUDA_PKG="cuda-repo-ubuntu1804_10.0.130-1_amd64.deb" USER_DEVSTACK=$(openssl rand -base64 12) unset PASS_DEVSTACK source ${profile_script} run run_main assert_failure assert_output "Empty required env var found: var var_name. ABORT" } @test "test run_main should be successfull" { # skip source ${profile_script} VNC_PASS=$(openssl rand -base64 12) NVIDIA_PKG="nvidia-diag-driver-local-repo-ubuntu1804-415.25_1.0-1_amd64.deb" NVIDIA_REPO="http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64" CUDA_PKG="cuda-repo-ubuntu1804_10.0.130-1_amd64.deb" LD_LIBRARY_PATH="/usr/local/lib" function install_nvidia_repos() { echo "This would install_nvidia_repos ${*}"; } export -f install_nvidia_repos function install_cuda_repos() { echo "This would install_cuda_repos ${*}"; } export -f install_cuda_repos function install_system_packages() { echo "This would install_system_packages ${*}"; } export -f install_system_packages function install_nvidia_drivers() { echo "This would install_nvidia_drivers ${*}"; } export -f install_nvidia_drivers function setup_x11vnc() { echo "This would setup_x11vnc ${*}"; } export -f setup_x11vnc run run_main assert_success } <file_sep>/README.md # Run Nvidia-enabled Linux desktops in Azure Engineering simulation software uses powerful display graphics and the GPU for a quick rendering of the display. Since virtual linux servers with non display attached secondary graphics as [Nvidia Tesla](https://en.wikipedia.org/wiki/Nvidia_Tesla) does not use GPU direkt rendering by default Xserver configurations. This issue can be easily corrected by modifying configurations on the host computer to allow the use of GPU rendering during a Remote Desktop session. ## Remote visualization However, running (and debugging) engineering software and other graphics-heavy software in a remote desktop environment can be challenging for the principal reason that Azure's Nvidia Tesla enabled Linux machines does not use GPU direkt rendering by default Xserver configurations. Starting up the graphics-heavy software can generate errors as the software attempts to initialize DirectX or OpenGL GPU display drivers on the host computer. Although they lack video outputs, when properly configured, [Azure NV Instances](https://docs.microsoft.com/en-us/azure/virtual-machines/nv-series) eqipped with Tesla GPUs are fully capable of supporting the same graphics APIs and visualization capabilities as their GeForce and Quadro siblings. Below is a collection of the basic requirements to enable graphics on Tesla GPUs, and steps for accomplishing this in the most common cases. My examples below assume a conventional Linux-based x86 compute node like Ubuntu, but they would likely be applicable to other node architectures. ### Enable the windowing system for full use of graphics APIs Once the GPU operation mode is properly set, the next requirement for full graphics operation is a running a windowing system. At present, the graphics software stack supporting OpenGL and related APIs depends on initialization and context creation facilities provided in cooperation with a running windowing system. A full windowing system is needed when supporting remote visualization software such as simulations software like VMD, VNC, or Virtual GL. Currently, a windowing system is also required for large scale parallel HPC visualization workloads, even though off-screen rendering (e.g. OpenGL FBOs or GLX Pbuffer rendering) is typically used exclusively. It is desirable to prevent the X Window System X11 server and related utilities from looking for attached displays when using Tesla GPUs. The `UseDisplayDevice` configuration option in `xorg.conf` can be set to `none`, thereby preventing any attempts to detect display, validate display modes, etc. The `nvidia-xconfig` utility can be told to set the display device to none by passing it the command line flag `--use-display-device=none` when you run it to update or generate an `xorg.conf` file. One of the side effects of enabling a windowing system to support full use of OpenGL and other graphics APIs is that it generally also enables a watchdog timer that will terminate CUDA kernels that run for more than a few seconds. This behavior differs from the compute-only scenario where a Tesla GPU is not graphics-enabled, and will allow arbitrarily long-running CUDA kernels. For HPC workloads, it is usually desirable to eliminate such kernel timeouts when the windowing system is running, and this is easily done by setting a special "Interactive" configuration flag to "false", in xorg.conf in the "Device" block for each GPU. The following is an example "Device" section from an HPC-oriented `xorg.conf` file. (see [ NVIDIA README X Config Options section for details][1]) ```bash Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BusID "PCI:132:0:0" ## ## disable display probing, display mode validation, etc. ## Option "UseDisplayDevice" "none" ## ## disable watchdog timeouts for long-running CUDA kernels ## Option "Interactive" "false" EndSection ``` The `xorg.conf` configuration example snippet shown above is what I use for the *NVIDIA Tesla K80* cards on a headless remote visualization server running the VTD simulation software, but is also very similar to what is used on nodes for autonomous driving or other industry simulations. ## Setup our rig You can find a repo with a fully automated full setup at this [Github Repo](https://github.com/aheumaier/azure-nvidia-linux-desktop) ### Bootstrap with Terraform Running `make deploy` will build a remote desktop enabled Ubuntu machine in a new resource group. This will deploy a Azure NV6 Instance with a Nvidia Tesla M60 for you - Setup KDE desktop environment - Setup Nvidia enabled Xserver - Setup X11VNC remote desktop server ```bash ~$ make deploy ``` You can connect now to the box with any VNC-Viewer using the hostname as session password Open a terminal e.g `konsole` and validate the results: ### Setup the node with Packer Running `make packer` will build a remote desktop enabled Ubuntu Image in you resource group to use for your own aplicances later: ``` ~$ make install ``` ## References - [HPC Visualization on NVIDIA Tesla GPUs](https://devblogs.nvidia.com/hpc-visualization-nvidia-tesla-gpus/) - [Using CUDA and X](https://nvidia.custhelp.com/app/answers/detail/a_id/3029/~/using-cuda-and-x) - [NVIDIA Container Toolkit](https://github.com/NVIDIA/nvidia-docker) <file_sep>/scripts/setup_ubuntu_desktop.sh #!/bin/bash # # Perparing the linux system for operating # simulation VTD components # # Usage: sudo ./setup_ubuntu_desktop.sh # # # === Break on the first Error === set -exo pipefail if [ "${DEBUG}" ]; then set -o xtrace # Similar to -v, but expands commands, same as "set -x" fi # === Cleanup actions === function finish() { sudo /usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync rm -rf "$TMP_DIR" } # === Enforce clean-up on any circumstances === # trap finish EXIT # === Installing Packages === install_system_packages() { sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "${PACKAGES[@]}" } # === Adding NVIDIA CUDA repositories === install_nvidia_repos() { sudo wget -O /etc/apt/preferences.d/cuda-repository-pin-600 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub sudo add-apt-repository "deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/ /" } # === Installing Cuda driver === install_nvidia_drivers() { sudo apt-get update sudo apt-get -y install cuda sudo nvidia-xconfig --use-display-device=none --virtual="3140x2160" # We will need it later for x11vnc } # === Configure x11vnc environment === setup_x11vnc() { sudo tee "/etc/systemd/system/x11vnc.service" >/dev/null <<'EOF' [Unit] Description=x11vnc VNC Server for X11 Requires=display-manager.service After=display-manager.service [Service] Type=forking ExecStartPre=/bin/bash -c "/bin/systemctl set-environment SDDMXAUTH=$(/usr/bin/find /var/run/sddm/ -type f)" ExecStart=/usr/bin/x11vnc -display :0 -auth ${SDDMXAUTH} -forever -shared -bg -o /var/log/x11vnc.log -rfbauth /etc/x11vnc.passwd -xkb -norc -noxrecord -noxdamage -nomodtweak ExecStop=/usr/bin/killall x11vnc Restart=on-failure RestartSec=2 [Install] WantedBy=graphical.target EOF sudo x11vnc -storepasswd $(hostname) /etc/x11vnc.passwd sudo systemctl enable x11vnc.service } # === MAIN PROCEDURE === run_main() { # declare -ra required_env_vars=( eequahThi1au # "${VNC_PASS}" # ) # for var in "${required_env_vars[@]}"; do # if [ -z "${var}" ]; then # var_name=("${!var@}") # echo "Empty required env var found: ${var_name[*]}. ABORT" # exit 1 # fi # done declare -ar PACKAGES=( wget curl x11vnc xterm freeglut3 kde-plasma-desktop openssh-server mesa-utils xfonts-75dpi libusb-0.1-4 libgsm1 libpulse0 libcrystalhd3 libmpg123-0 libdvdread4 libxvidcore4 libaa1 libfaad2 libxss1 libopencore-amrnb0 libopencore-amrwb0 libspeex1 libjack-jackd2-0 libdv4 libdca0 libtheora0 libxvmc1 libbs2b0 libmp3lame0 libmad0 liblircclient0 libsmbclient libsdl1.2debian libtwolame0 libenca0 ) declare TMP_DIR TMP_DIR=$(mktemp -d -t tmp.XXXXXXXXXX || exit 1) declare -r TMP_DIR install_nvidia_repos install_system_packages install_nvidia_drivers setup_x11vnc } # Be able to run this one either as standalone or import as lib if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then run_main fi <file_sep>/Makefile # Generates a nvidia enabled desktop machine in Azure # make test : runs all tests available # make bats : runs all bash tests available in scripts/test # # Directory containing scripts scripts := scripts # Directory containing bats source bats := $(wildcard $(scripts)/test/*.bats) all: test packer-build test: bats packer-validate bats: scripts/test/libs/bats/bin/bats $(bats) packer-validate: packer validate packer/linux-template.json install: packer build packer/linux-template.json terraform-init: cd tf && terraform init terraform-validate: cd tf && terraform validate terraform: terraform-validate cd tf && terraform apply deploy: terraform `
59081a98610a9377d66ec7c7216cfa9400ebba3e
[ "Markdown", "Makefile", "Shell" ]
4
Shell
aheumaier/azure-nvidia-linux-desktop
e5f3631ff12254569907cb2495c43634724de581
7f236002de95053927824ecd59aa60f74f0d2a43
refs/heads/master
<file_sep>package com.myself.spring.lifecycle.common; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * @author 【name】毛攀攀 * @author 【date】2019/04/25 * @author 【时间】22:47 * @author 【说明】 * @author 【工程】test-spring-lifecycle-demo * @author 【目录】com.myself.spring.lifecycle.common */ public class MyBeanPostProcessor implements BeanPostProcessor { public MyBeanPostProcessor() { super(); System.out.println("3、实例化BeanPostProcessor实现类"); } @Override public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out.println("16、执行BeanPostProcessor实现类postProcessAfterInitialization方法"); return arg0; } @Override public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out.println("11、执行BeanPostProcessor实现类postProcessBeforeInitialization方法"); return arg0; } } <file_sep>package com.myself.spring.lifecycle.common; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; /** * @author 【name】毛攀攀 * @author 【date】2019/04/25 * @author 【时间】22:52 * @author 【说明】 * @author 【工程】test-spring-lifecycle-demo * @author 【目录】com.myself.spring.lifecycle.common */ public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public MyBeanFactoryPostProcessor() { super(); System.out.println("1、实例化BeanFactoryPostProcessor实现类"); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException { System.out.println("2、调用BeanFactoryPostProcessor实现类postProcessBeanFactory方法"); BeanDefinition bd = arg0.getBeanDefinition("person"); bd.getPropertyValues().addPropertyValue("phone", "110"); } } <file_sep>package com.myself.spring.lifecycle; import com.myself.spring.lifecycle.vo.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * spring Bean生命周期 * 1、实例化BeanFactoryPostProcessor实现类; * 2、调用BeanFactoryPostProcessor实现类postProcessBeanFactory方法 * 3、实例化BeanPostProcessor实现类; * 4、实例化InstantiationAwareBeanPostProcessorAdapter实现类; * 5、调用InstantiationAwareBeanPostProcessorAdapter实现类postProcessBeforeInstantiation方法 * 6、实例化Bean; * 7、调用InstantiationAwareBeanPostProcessorAdapter实现类postProcessSetVlues方法 * 8、设置Bean属性 * 9、调用BeanNameWare实现类setBeanName方法 * 10、调用BeanFactoryWare实现类setBeanFactory方法 * 11、执行BeanPostProcessor实现类postProcessBeforeInitialization方法 * 12、调用InitializingBean实现类afterPropertiesSet方法 * 15、调用Bean init-method初始化方法 * 16、执行BeanPostProcessor实现类postProcessAfterInitialization方法 * 17、执行InstantiationAwareBeanPostProcessorAdapter实现类postProcessorAfterInitialization方法 * 18、容器初始化完成 * ------------销毁------------- * 19、调用Diposible实现类的destory方法 * 20、调用Bean destory-method方法 */ public class BeanLifeCycle { public static void main(String[] args) { ApplicationContext factory = new ClassPathXmlApplicationContext("beans.xml"); System.out.println("18、容器初始化完成"); //得到Preson,并使用 Person person = factory.getBean("person", Person.class); System.out.println(person); System.out.println("现在开始关闭容器!"); ((ClassPathXmlApplicationContext) factory).registerShutdownHook(); } }
6d843b312038b17fa571bf24983533fd7bd9e43e
[ "Java" ]
3
Java
maopanpan/test-spring-bean-lifecycle-demo
f46f5d07045a384bc68c2d1a49c517a021191fd5
235c24c52ba125ad0686da5ac8866206be25e809
refs/heads/master
<repo_name>object/Akka.Persistence.Reminders<file_sep>/Akka.Persistence.Reminders/ReminderSettings.cs #region copyright // ----------------------------------------------------------------------- // <copyright file="ReminderSettings.cs" creator="<NAME>"> // Copyright (C) 2017-2023 <NAME> and contributors // </copyright> // ----------------------------------------------------------------------- #endregion using System; using Akka.Configuration; namespace Akka.Persistence.Reminders { /// <summary> /// An immutable statically-typed settings class used by <see cref="Reminder"/> actor. /// </summary> public class ReminderSettings { /// <summary> /// An instance of a <see cref="ReminderSettings"/> with default configuration. /// </summary> public static ReminderSettings Default { get; } = new ReminderSettings( persistenceId: "reminder", journalPluginId: "", snapshotPluginId: "", tickInterval: TimeSpan.FromSeconds(10), snapshotInterval: 100, cleanupOldMessages: true, cleanupOldSnapshots: false ); public static ReminderSettings Create(Config config) { if (config == null) return Default; return new ReminderSettings( persistenceId: config.GetString("persistence-id", "reminder"), journalPluginId: config.GetString("journal-plugin-id", ""), snapshotPluginId: config.GetString("snapshot-plugin-id", ""), tickInterval: config.GetTimeSpan("tick-inverval", TimeSpan.FromSeconds(10)), snapshotInterval: config.GetInt("snapshot-interval", 100), cleanupOldMessages: config.GetBoolean("cleanup-old-messages", true), cleanupOldSnapshots: config.GetBoolean("cleanup-old-snapshots", false)); } /// <summary> /// Persistent identifier for event stream produced by correlated reminder. /// Default: "reminder". /// </summary> public string PersistenceId { get; } /// <summary> /// Identifier of a event journal used by correlated reminder. /// Default: akka.persistence default. /// </summary> public string JournalPluginId { get; } /// <summary> /// Identifer of a snapshot store used by correlated reminder. /// Default: akka.persistence default. /// </summary> public string SnapshotPluginId { get; } /// <summary> /// Unlike standard akka.net scheduler, reminders work in much lower frequency. /// Reason for this is that they are designed for a long running tasks (think of /// minutes, hours, days or weeks). Default: 10 seconds. /// </summary> public TimeSpan TickInterval { get; } /// <summary> /// Reminder uses standard akka.persistence eventsourcing for maintaining scheduler /// internal state. In order to make a stream of events shorter (and ultimately /// allowing for a faster recovery in case of failure), a reminder state snapshot is /// performed after a series of consecutive events have been stored. /// Default: every 100 consecutively persisted events. /// </summary> public int SnapshotInterval { get; } /// <summary> /// Reminder periodically saves its state in Snapshot store, so old EventJournal entries can be removed from the database. /// Default: true. (Default is set to true to match Reminder's behavior when this settings was not configurable) /// </summary> public bool CleanupOldMessages { get; } /// <summary> /// Current state of Reminder is stored in the most recent snapshot, so older SnapshotStore entries can be removed from the database. /// Before enabling snapshot cleanup make sure the SnapshotStore table doesn't contain large number of entries for the given PersistenceId. /// Deletion of large snapshots may take long time, so it may lead to timeout exception when deleting multiple snapshots. /// Default: false. (Default is set to false to match Reminder's behavior when this settings was not configurable) /// </summary> public bool CleanupOldSnapshots { get; } public ReminderSettings(string persistenceId, string journalPluginId, string snapshotPluginId, TimeSpan tickInterval, int snapshotInterval, bool cleanupOldMessages, bool cleanupOldSnapshots) { PersistenceId = persistenceId ?? throw new ArgumentNullException(nameof(persistenceId)); JournalPluginId = journalPluginId ?? throw new ArgumentNullException(nameof(journalPluginId)); SnapshotPluginId = snapshotPluginId ?? throw new ArgumentNullException(nameof(snapshotPluginId)); TickInterval = tickInterval; SnapshotInterval = snapshotInterval; CleanupOldMessages = cleanupOldMessages; CleanupOldSnapshots = cleanupOldSnapshots; } /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="PersistenceId"/>. /// </summary> public ReminderSettings WithPersistenceId(string persistenceId) => Copy(persistenceId: persistenceId); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="JournalPluginId"/>. /// In order to set it to default value, use empty string. /// </summary> public ReminderSettings WithJournalPluginId(string journalPluginId) => Copy(journalPluginId: journalPluginId); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="SnapshotPluginId"/>. /// In order to set it to default value, use empty string. /// </summary> public ReminderSettings WithSnapshotPluginId(string snapshotPluginId) => Copy(snapshotPluginId: snapshotPluginId); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="TickInterval"/>. /// </summary> public ReminderSettings WithTickInterval(TimeSpan tickInterval) => Copy(tickInterval: tickInterval); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="SnapshotInterval"/>. /// </summary> public ReminderSettings WithSnapshotInterval(int snapshotInterval) => Copy(snapshotInterval: snapshotInterval); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="CleanupOldMessages"/>. /// </summary> public ReminderSettings WithCleanupOldMessages(bool cleanupOldMessages) => Copy(cleanupOldMessages: cleanupOldMessages); /// <summary> /// Returns a new instance of <see cref="ReminderSettings"/> with overriden <see cref="CleanupOldSnapshots"/>. /// </summary> public ReminderSettings WithCleanupOldSnapshots(bool cleanupOldSnapshots) => Copy(cleanupOldSnapshots: cleanupOldSnapshots); private ReminderSettings Copy(string persistenceId = null, string journalPluginId = null, string snapshotPluginId = null, TimeSpan? tickInterval = null, int? snapshotInterval = null, bool? cleanupOldMessages = null, bool? cleanupOldSnapshots = null) => new ( persistenceId: persistenceId ?? PersistenceId, journalPluginId: journalPluginId ?? JournalPluginId, snapshotPluginId: snapshotPluginId ?? SnapshotPluginId, tickInterval: tickInterval ?? TickInterval, snapshotInterval: snapshotInterval ?? SnapshotInterval, cleanupOldMessages: cleanupOldMessages ?? CleanupOldMessages, cleanupOldSnapshots: cleanupOldSnapshots ?? CleanupOldSnapshots); } }<file_sep>/README.md # Akka.Persistence.Reminders An Akka.NET scheduler designed to work with long running tasks. When compared to standard `ActorSystem` scheduler, there are two major differences: - Standard scheduler state is stored in memory. That means, it's going to be lost after `ActorSystem` or machine restart. Reminder state is backed by an Akka.Persistence eventsourcing engine, which means that it's able to survive between restarts, making it good choice for tasks designed to be fired hours, days or many weeks in the future. - Unlike standard scheduler, reminder is not designed to work with sub-second latencies. If this is your case, don't use reminders. ### Basic example ```csharp var config = ConfigurationFactory.Load().WithFallback(Reminder.DefaultConfig); using (var system = ActorSystem.Create("system", config)) { // create a reminder var reminder = system.ActorOf(Reminder.Props(), "reminder"); var taskId = Guid.NewGuid().ToString(); // setup a message to be send to a recipient in the future var task = new Reminder.Schedule(taskId, recipient.Path, "message", DateTime.UtcNow.AddDays(1)); // setup a message to be send in hour intervals var task = new Reminder.ScheduleRepeatedly(taskId, recipient.Path, "message", DateTime.UtcNow.AddDays(1), TimeSpan.FromHours(1)); // setup a message to be send at 10:15am on the third Friday of every month var task = new Reminder.ScheduleCron(taskId, recipient.Path, "message", DateTime.UtcNow.AddDays(1), "15 10 ? * 6#3"); reminder.Tell(task); // get scheduled entries var state = await reminder.Ask<Reminder.State>(Reminder.GetState.Instance); // cancel previously scheduled entity - if ack was defined it will be returned to sender after completion reminder.Tell(new Reminder.Cancel(taskId)) } ``` You can also define a reply message, that will be send back once a scheduled task has been persisted. ```csharp var task = new Reminder.Schedule(Guid.NewGuid().ToString(), recipient.Path, "message", DateTime.UtcNow.AddDays(1), ack: "reply"); var ack = await reminder.Ask<string>(task); // ack should be "reply" ``` ### Cron Expressions You can setup schedule to repeat itself accordingly to following cron expressions format: ``` Allowed values Allowed special characters ┌───────────── minute 0-59 * , - / │ ┌───────────── hour 0-23 * , - / │ │ ┌───────────── day of month 1-31 * , - / L W ? │ │ │ ┌───────────── month 1-12 or JAN-DEC * , - / │ │ │ │ ┌───────────── day of week 0-6 or SUN-SAT * , - / # L ? │ │ │ │ │ * * * * * ``` Other characteristics (supported by a [Cronos](https://github.com/HangfireIO/Cronos) library used by this plugin): - Supports non-standard characters like L, W, # and their combinations. - Supports reversed ranges, like 23-01 (equivalent to 23,00,01) or DEC-FEB (equivalent to DEC,JAN,FEB). - Supports time zones, and performs all the date/time conversions for you. - Does not skip occurrences, when the clock jumps forward to Daylight saving time (known as Summer time). - Does not skip interval-based occurrences, when the clock jumps backward from Summer time. - Does not retry non-interval based occurrences, when the clock jumps backward from Summer time. ### Using reminder in cluster Since a reminder is a persistent actor, it's crucial, that only one instance of it may be active in the entire cluster at the same time. In order to avoid risk of having multiple instances or rellying on a single preconfigured machine, you may combine reminder together with Akka.NET [cluster singleton](http://getakka.net/articles/clustering/cluster-singleton.html) from [Akka.Cluster.Tools](https://www.nuget.org/packages/Akka.Cluster.Tools/) package. ```csharp system.ActorOf(ClusterSingletonManager.Props( singletonProps: Reminder.Props(), terminationMessage: PoisonPill.Instance, // use role to limit reminder actor placement only to some subset of nodes settings: ClusterSingletonManagerSettings.Create(system).WithRole("reminder")), name: "reminder"); ``` ### Using reminders together with Akka.Cluster.Sharding Since sharded actors don't have a single `ActorPath` as they can move between different nodes of the cluster, it's not reliable to set that actor's path as a reminder recipient. In this case a recipient should be the shard region living on a current cluster node, while the message itself should be a shard envelope having an information necessary to route the payload to target sharded actor. ```csharp var region = ClusterSharding.Get(system).Start( typeName: "my-actor", entityProps: Props.Create<MyActor>(), settings: ClusterShardingSettings.Create(system), messageExtractor: new MessageExtractor()); var envelope = new Envelope(shardId: 1, entityId: 1, message: "hello"); var task = new Reminder.Schedule(taskId, region.Path, envelope, DateTime.UtcNow.AddDays(1)); reminder.Tell(task); ``` ### Configuration ```hocon akka.persistence.reminder { # Persistent identifier for event stream produced by correlated reminder. persistence-id = "reminder" # Identifier of a event journal used by correlated reminder. journal-plugin-id = "" # Identifer of a snapshot store used by correlated reminder. snapshot-plugin-id = "" # Unlike standard akka.net scheduler, reminders work in much lower frequency. # Reason for this is that they are designed for a long running tasks (think of # seconds, minutes, hours, days or weeks). tick-inverval = 10s # Reminder uses standard akka.persistence eventsourcing for maintaining scheduler # internal state. In order to make a stream of events shorter (and ultimately # allowing for a faster recovery in case of failure), a reminder state snapshot is # performed after a series of consecutive events have been stored. snapshot-interval = 100 # Reminder periodically saves its state in Snapshot store, so old EventJournal entries can be removed from the database. # Default: true. (Default is set to true to match Reminder's behavior when this settings was not configurable) cleanup-old-messages = true # Current state of Reminder is stored in the most recent snapshot, so older SnapshotStore entries can be removed from the database. # Before enabling snapshot cleanup make sure the SnapshotStore table doesn't contain large number of entries for the given PersistenceId. # Deletion of large snapshots may take long time, so it may lead to timeout exception when deleting multiple snapshots. # Default: false. (Default is set to false to match Reminder's behavior when this settings was not configurable) cleanup-old-snapshots = false } ``` <file_sep>/RELEASE_NOTES.md #### 0.7 May 22 2023 * Extended settings with database cleanup configuration: * cleanupOldMessages * cleanupOldSnapshots #### 0.5 May 03 2020 * Removed FAKE (now uses standard dotnet command to build and package the library) * Added GetItemCount and GetItems messages #### 0.3 March 09 2023 * Updated Akka packages to 1.5 #### 0.3 March 09 2020 * Updated Akka.Persistence and Akka.TestKit.Xunit to 1.4.1-rc1 * Removed support for .NET 4.5 as no longer supported by Akka.Persistence * Bumped version to .NET Standard 2.0 to synchronized with Akka.Persistence * Bumped version of Tests to .NET Core 2.0 (minumum required by .NET Standard 2.0) #### 0.2 February 06 2019 * Added support for cron expressions. #### 0.1 November 28 2018 * Updated to Akka.Persistence v1.3.10 #### 0.0.1 November 21 2017 * Nuget package <file_sep>/build.sh dotnet build Akka.Persistence.Reminders.sln --configuration Release -p:VersionPrefix=$1
ea738f5bf687519e9b1c53940b08d2cc182d4720
[ "Markdown", "C#", "Shell" ]
4
C#
object/Akka.Persistence.Reminders
e09915c1f81c95aa89c37d2c28dc6fc1f1e81cbc
9edc41a20aaf2f4141d4e86bc2e577f630b09c1d
refs/heads/master
<file_sep>//concrete component class public class ComponentBeerDecaf extends ComponentBeer { public ComponentBeerDecaf(){ desc = &quot;Decaf&quot;;} public double cost(){ return 1.49 ;} } <file_sep>public class ObserverIns1 implements Observer, Display { private float temp; private float humi; private float pre; private Subject weatherData; public ObserverIns1(Subject weatherData){ this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float temp, float humi, float pre){ this.temp = temp; this.humi = humi; this.pre = pre; display(); } public void display(){ System.out.println(&quot;Current Conditions: &quot; + temp + &quot;F degrees and &quot; + humi + &quot;% humidity and &quot; + pre + &quot; pressue.&quot;); } } <file_sep>public class Waiter { Menu LunchMenu; Menu DinerMenu; public Waiter(Menu LunchM, Menu DinerM){ this.LunchMenu = LunchM; this.DinerMenu = DinerM; } public void printMenu(){ myIterator lunchMenuIterator = LunchMenu.createIterator(); myIterator dinerMenuIterator = DinerMenu.createIterator(); System.out.println(&quot;MENU\n-----\nLUNCH&quot;); printMenuItem(lunchMenuIterator); System.out.println(&quot;MENU\n-----\nDINER&quot;); printMenuItem(dinerMenuIterator); } private void printMenuItem(myIterator iter){ while( iter.hasNext() ){ MenuItem item = (MenuItem)iter.next(); System.out.println(item.getName() + &quot;,&quot;); System.out.println(item.getPrice() + &quot;,&quot;); System.out.println(item.getDescription() + &quot;,&quot;); } } } <file_sep>public class WeatherTestDrive { public static void main(String[] args){ System.out.println(&quot;my own observer pattern&quot;); //self-defined observer pattern WeatherData data = new WeatherData(); ObserverIns1 dis = new ObserverIns1(data); data.setMeasurements(72,50,80); data.setMeasurements(80,70,65); //Java built-in observer pattern System.out.println(&quot;Java built-in observer pattern&quot;); WeatherData2 data2 = new WeatherData2(); ObserverIns2 dis2 = new ObserverIns2(data2); data2.setMeasurements(72,50,80); data2.setMeasurements(80,70,65); } } <file_sep>public class PizzaStore1 extends PizzaStore { public Pizza createPizza(String item){ if( item.equals(&quot;cheese&quot;) ){ return new PizzaCheese(); }else{ return null; } } } <file_sep>public abstract class CoffeeAndTea { final void prepareRecipe(){ boilWater(); brew(); pourInCup(); if(customerWantCondiments()){addCondiments();} } abstract void brew(); abstract void addCondiments(); void boilWater(){ System.out.println(&quot;Boiling water&quot;); } void pourInCup(){ System.out.println(&quot;Pouring into cup&quot;); }; //hook function boolean customerWantCondiments(){ return true; } } <file_sep>//Author:xin //Date: 2018-06-06 //Strategy Pattern Demo public class FlyAsRocket implements FlyBehavior { public void fly(){ System.out.println(&quot;fly like a Rocket&quot;); } } <file_sep>### 问题: 现在有两个menu, 一个是lunchMenu class,使用的是arrayList 存储menu Item; 一个是dinnerMenu class,使用的是Array存储menu Items; 现在我们想将两个进行合并,具体就是可以使用waiter打印出所有的menu item; 设计printMenu()方法,因为两个类使用不同的数据结构存储menu Item,所以需要分别进行循环获取处理,如果再添加其他的menu,并使用不同的结构比如hashtable等存储,这时需要到printMenu()进行修改,而且printMenu()中会存在很多重复代码,如何优化? ### 解决方法: 根据“将变化的部分拿出来进行封装”的原则进行优化,可以看出,主要的变化部分是 循环获取 collection ele; 首先,就把这部分拿出来并封装成一个接口: Interface myIterator{ Boolean hasNext(); Object next(); } 然后,针对两种menu创建各自的iterator实现以上接口,在这两个具体的iterator类中具体实现 循环获取元素 的操作; lunchMenuIterator implements myIterator(){xxx} dinnerMenuIterator implements myIterator(){xxx} 最后,需要在两种menu中添加函数用来提供各自的iterator,添加createIterator()函数。 至此,已经解决问题,但是可以看到createIterator()在两个menu中是共有的部分,所以可以再次将此函数拿出来封装成一个接口, 这样做不仅减少了代码冗余,而且因为共同实现此接口使得两种menu利用多态可以互换。 Abstract Menu{ Void createIterator(); } 涉及到两组类,一组是实现了menu得各种具体的menu;一组是实现myIterator的针对各种menu的iteratorz,这两组对象组,通过printMenu()联系到一起并完成所需操作。 ### Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch09_IteratorAndComposite/src/Iterator) for demo code. ### Iterator Pattern: Provides a way to access the element of a collection of objects sequentially without exposing its underlying representation。 也即对于使用不同存储结构(arrayList, Array, hashtable等)的对象集合,只要能够提供提供iterator对象,都可以使用统一的接口进行循环获取单个元素的操作。 上面我们是自己定义的iterator接口,JAVA中已经提供了定义好的Iterator接口,而且除了hasNext(), next()方法外,还可以扩展其他方法。因此,使用iterator pattern时使用JAVA提供的iterator即可,如果JAVA提供的iterator interface不能满足 需求,也可以创建自己的iterator。 Iterator 模式的使用使得collection(menu)可以专注于存储menu item,而将 循环获取元素的操作 delegate给了iterator,这就体现了single responsibility的设计原则。 ### Single Responsibility: A class should have only one reason to change。 在设计的时候,每个类最多应该只关注一个单独的点,因为关注的点越多,引入的可变因素越多,后期出错的概率越大,也越难维护,所以前期设计时一定要注意这一个原则。 ### 新的问题: 如果在上面的dinner menu中添加一个dessert menu,那么以上的printMenu方法就不再适用了,需要考虑新的方法,这里就引入了composite pattern. ### Composite pattern: Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly。 **适用情景**为 :遍历树形数据。 这种模型允许我们对composite and individual objects进行相同的操作,在这里就表现为对menu item and menu都可以执行相同的操作。 **模型类架构图:** 首先需要定义一个虚父类component,将所有可以进行的操作放到里面; Public abstract class Component { Operation(); Add(component); Remove(component); getChild(int); } 然后,针对composite and individual node实现两种类: Class leaf { Operation(); } Class composite { Add(component); Remove(component); getChild(); operation(); } 我们可以看到,实现的这两个类对父类中的函数是有选择的进行Override的,因为有些操作对leaf而言是无意义的,而有的操作可能对composite是无意义的,所以选择性进行override。这也是父类component设计为虚类而非接口的原因,因为在父类中要对所有函数都进行default implementation。 **针对关于menu的具体问题,类设计如下:** 父类 MenuComponent Public abstract class MenuComponent { getName(){xx} getDescription(){xx} getPrice(){xx} isVegetarian(){xx} print(){xx} add(component){xx} remove(component){xx} getChild(int){xx} } 然后创建两个子类: Class MenuItem{ xxx } Class Menu { xxx } 最关键的地方在于以上三个类中所有method的具体实现。 将Iterator + composite两种模式结合起来: 需要在menuCompoent父类中添加createIterator()方法; menuItem是没有iterator概念的,所以menuItemIterator直接返回NullIterator(类似于NoCommand的思想); menu返回的iterator定义为compositeIterator,这个的实现有些复杂。 可以看出,两种模式结合起来使用的总体架构和iterator是相似的,只是其中的menu 换成了menuComponent,而且每种具体iterator的实现更复杂了些,但总体类的架构是和之前的iterator相同的。 Demo code url: https://github.com/bethrobson/Head-First-Design-Patterns/tree/master/src/headfirst/designpatterns/composite/menuiterator <file_sep>### 问题: 眼下有一款游戏机Gamball,有四种状态,四种行为,一种状态到另一种状态通过一种action进行转换,现在 已知其状态转移图,需要构建实现代码。 ### 解决方法: 最开始想到的是最原始的过程式编程,把每种action作为中心,判断可能的当前状态和转换到的状态, Void insert(){ If(state == xx){xxx} If(state == xx){xxx} } 当新增加一种状态时,需要做很大的代码改动,而且以上根本没有用到OO思想, **改进如下:** 我们以每种状态为中心,当前状态在四种行为下的反应为具体实现,让每种状态自己管理自己的状态转移。 首先,设计 state 接口 Interface state { insertQ(); ejectQ(); } 然后,每种具体的状态implement state interface,并具体实现四种行为下的状态转移; 最后,定义GameMachine类,在类中包含各种具体状态的reference,并一直指示current state, 因为最终client action都是对game machine操作的,所以这这个类中也要定义四种action method,但是具体的实现则是delegate to current state来实现。 比如GameMachine中, void intertQ(){ current.insertQ(); } 改进之后,不仅符合OO原则,而且容易扩展,如果增加一种状态,只需创建一个新的state class即可。 ### Demo 此模式的demo和下一节的proxy demo代码有重复,所以放到下一节统一实现。 ### State pattern: Allows an object to alter its behavior when its internal state changes, the object will appear to change its class. ### 模型类架构图: 一个抽象state class ,可以为抽象类(如果需要默认实现),也可以为接口; 多个具体的state class,用来具体实现状态转移action; 一个context,用来和外界直接接触并操作,即上面例子里的gameMachine。 ### Strategy and state: 两种实现的形式很相似,但是初衷和侧重点不同: Strategy 侧重an alternative to subclassing,动态选择,有操作者选择某种确定的具体行为; State 侧重an alternative to putting lots of conditionals in your context,动态选择,但是选择哪一个不是由外界决定的,而是由context的内在state决定的。 <file_sep>### 问题的提出及解决: 准备一杯咖啡的类定义为: Public class coffee { boilWater(){xx}; brewCoffee(){xx}; pourInCup(){xx}; addMilk(){xx}; } 准备一杯茶的类定义为: Public class tea { boilWater(){xx}; brewTea(){xx}; pourInCup(){xx}; addLemon(){xx}; } 从上面可以看出,两种类的活动模式都是一样的,只是其中某些具体步骤不相同,以上设计会有很多重复代码, 改进如下: Public abstract class CoffeeAndTea{ Public void prepare(){ boilWater(); brew(); pourInCup(); addCondiment(); } Void boilWater(){xx}; Void pourInCup(){xx}; Abstract void brew(); Abstract void addCondiment(); } 然后具体到coffee and tea的时候,只需扩展以上类并具体实现虚方法即可,既保证了行为的灵活性,又最大程度利用了code reuse。 ### Template Method Pattern Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template method let subclasses redefine certain steps of an algorithm without changing the algorithm’s structure。 ### Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch08_TemplateMethodPattern/src) to see the demo code. ### 模型类设计图: 只需要一个虚类即可: Abstract class AbstractClass { Final void templateMethod(){ primitiveOperation1(); primitiveOperation2(); concreteOperation(); } Abstract void primitiveOperation1(); Abstract void primitiveOperation2(); Void concreteOperation(){xx}; } 具体的类拓展该虚类时负责实现具体的某些子函数。 ### Hook 函数: A hook is a method that is declared in the abstract class, but only give an empty or default implementation。 Hook的本质就是一个虚类中的方法,注意为非虚方法,因为子类可以不用理会,在需要的时候可以进行覆盖,这就给了子类更改父类行为的入口和自由(可改可不改)。 因为这个函数是在父类中的,所以子类虽然可以通过override修改其具体行为,但是其调用则是由父类控制,这就引入了OO Hollywood principle。 ### OO原则: **Don’t call me, I will call you。** 此原则主要用来解决不同level元素间混乱问题,hook的设计就体现了这一原则。 Hook enable low-level component(concrete class like Coffee) to hook into high-level component(abstract class CoffeeAndTea), but the high-level component decide how and when to call it. Template method模式既可以保持统一的架构,又可以满足行为具体化,且重复利用code reuse,所以在应用中经常用到。 JAVA array中的sort()就是使用了这一模式。JFrame中的paint()函数则是hook应用的一个例子。 ### 对比 **Strategy pattern, template and factory**: Strategy 和template两者很相似,都是将具体的行为delegate给其余的对象,但是实际上还是有很多不同的地方的: 第一, Strategy将整个algorithm的实现都delegate给了其他对象,template只将整个algorithm中某些steps代理给其他对象; 第二, Strategy 使用的是composition;template使用的是Inherence; 第三, Strategy侧重的是运行期间动态改变行为的灵活性;template侧重的是在不改变整体框架的前提下灵活实现某些步骤,并最大化利用code reuse; 第四, Factory method可以认为是template method 的一种特殊情况。 <file_sep>## Aapter and Facade pattern ### Adapter pattern: 可以使用 电源转换器 来理解这种模式。 Converts the interface of a class into another interface that the client expect. Adapters let classes work together that couldn’t otherwise because of incompatiable interface。 主要目的是为了两种接口不兼容的class可以兼容; ### 简单示例: Public interface Duck { void quack(); void fly(); } Public interface Turkey { void gobble(); void fly(); } 现在client想使用duck,但是我们只有turkey,这时就需要一个adapter Public class TurkeyAdapter implements Duck { Turkey turkey; Public TurkeyAdatpter(Turkey tk){ this.turkey = tk; } Void quack(){ turkey.goggle(); } Void fly(){turkey.fly(); } } ### 模型类架构图: 涉及到两个:target(duck),即需要的类; adaptee(turkey),现有的类,需要被转换的类 设计adapter: 使其实现target,并包含adaptee,使用adaptee的方法实现target的方法。 **使用实例:** 以前的JAVA中,使用Enumerators来循环获取集合中的单个元素;现在则多是使用Iterator来实现这一个功能,这个时候就可以使用adapter来使得原来的expose Enumerator interface的代码可以使用Iterator功能。 ### Façade pattern: Provides a unified interface to a set of interfaces in a subsystem。 即对于涉及到多个对象调用多个方法的情况下,对这些对象和方法进行集合封装。 ### 简单示例: 一个家庭影院涉及到好多类,比如灯光,声响,荧幕等; 需要watch movie时,分别要调用light.on(), sound.on(), screen.on()等,会与很多个对象打交道,这时候就可以使用Façade, 定义public class façade {} 将涉及到的object都集合到façade里面,并将watch movie所需要的操作集合进一个函数watechMovie()里面。 ### Demo Headfirst给出的关于adapter 和 facade的demo都非常简单,这里就没有给出代码。 ### OO原则: least knowledge- talk only to your immediate friend,尽量减少类相互间的依赖和耦合。 其中一条: not to call methods on objects that were returned from calling other methods, but we can call methods of instance variable and function paremeters. ### 对比 以下三种模式都使用到class composition,但是侧重点各不相同: **Adapter** wrap class to change its interface; **Façade** wrap several objects to simplify the interface; **Decorator** wrap object to add new behaviors。 <file_sep>//author:xin //date:2018-6-6 //self-defined observer pattern public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObservers(); } <file_sep>//author:xin //date:2018-6-6 //self-defined observer pattern public interface Observer { public void update(float temp, float humi, float pre); } <file_sep>### 问题: 接着从pattern 10的问题看, Game ball游戏获得空前成功,多个地方都建有game machine,每个地方的game machine都在本地运行之前利用state pattern设计良好的程序,如今想在总部得到全部的game machine明细,包括地点,名字和状态,因为game machine是分布于各个地方的,所以程序位于不同的JVM上面。 ### 解决方法: 如果只是打印本地game machine的状态,只需要设计一个GameMonitor类,在里面传入game machine reference,然后调用其相关get函数或许所需的状态即可。 而如今各地的game machine是位于不同的JVM上面,因为我们需要能够访问不同JVM上面的game machine类的get函数,所以需要提供一种解决方法。 这里就是用到了remote proxy 模式, **A remote proxy acts as a local representative to a remote object** 它的本质是JAVA RMI机制, **RMI gives a way to find objects in a remote JVM and allows us to invoke their methods。** **RMI 的本质为**: 本地client需要访问异地service,使用RMI的实质过程为: 首先,client所在的server 应该有一个 client helper,也称为remote proxy,也即它就代表我们要访问的异地service; Service所在的server 也有一个service helper; 过程为: client访问本地的client helper(proxy),这种访问就是local invoke,是可以的; Client helper通过network底层机制来和remote server进行通讯,将invoke method信息发送给service helper; Service helper 收到invoke information后调用service,这个时候为local invoke。 这样就实现了client remote invoke service的过程。 JAVA内置支持RMI,其中client helper即stub, service helper即skeleton。 ### 实现简单的RMI: 这里,将jabdw3420作为server, jabdw3421作为client, 最终的目的是在3421上面可以调用3420上面的java类定义的sayHi()方法。 **实现步骤:** 首先,将3420上面的java类变成remote service, **1.Make a remote interface** 这个interface作用是 defines the remote methods you want client to call. Public interface myRemote extends Remote{ Public String sayHi() throws RemoteException; } 三点要注意, 第一,必须extends Remote;第二,必须throw RemoteException;第三,里面的method涉及到的参数或返回值必须为primitive or serializable。 **2.Make a remote implementation** 也即实现上面定义的remote interface Public class myRemoteImpl extends UnicastRemoteObject implements myRemote { Public String sayHi(){ return “server say, hi” ; } Public myRemoteImpl () throws RemoteException {} } 注意两点, 第一,一定要extend UnicastRemoteObject;第二,因为UnicastRemoteObject会抛出异常,所以这里也要定义一个空的构建函数,目的就是为了将父类抛出的异常继续throw。 **3.生成stub and skeleton** 使用RMI工具生成。 首先要对implementation进行compile生成class 然后要在implementation class所在的目录运行 rmic myRemoteImpl 就会在当前目录下生成stub, skeleton,默认命名为 xx_Stub, xx_Skeleton,实际上只会生成stub没有skeleton。 **4.注册service** 到这里为止生成service已经成功,还需要进行注册,这里需要两个操作 首先,另外打开一个terminal,运行rmiregistry; 然后,还需要进行rebind,rebind的代码可以自己选择放在哪里,这里将其放在implementation上面,因此最后的implementation就变成了以下: Public class myRemoteImpl extends UnicastRemoteObject implements myRemote { Public String sayHi(){ return “server say, hi” ; } Public myRemoteImpl () throws RemoteException {} public static void main(String[] args){ try{ MyRemote service = new MyRemoteImpl(); Naming.rebind(&quot;//localhost/RemoteHi&quot;, service); }catch(Exception ex){ ex.printStackTrace(); } } } 至此就准备成功了,可以使用了。 **在client端使用时,步骤如下:** 首先,将server端的myRemote.class, myRemoteImpl_Stub.class拷贝到client端正确目录下(client端代码所在处) 然后,书写调用myRemote的代码 try{ MyRemote service = (MyRemote)Naming.lookup(&quot;rmi://10.1.114.201/RemoteHi&quot;); String s = service.sayHi(); System.out.println(s); }catch(Exception ex){ ex.printStackTrace(); } 最关键的是Naming.lookup的使用,用来查找所需要的proxy,其中的参数为server service所在的位置,这里为3420 IP地址。 最后,运行, 首先在server 端开启terminal运行rmiregistry 然后在server 端运行rebind所在代码,这里就是myRemoteImpl(因为这个错误调试很长时间) 然后在client端正常编译运行即可。 ### Simple RMI demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch11_ProxyPattern/src/simpleRMI) for simple RMI code. ### game machine的具体实现: Server 端的service已有,即为gameMachine何一组具体的state class; 需要编写remote和remoteImpl,这里创建 GameMachineRemote;其中的GameMachineRemoteImpl就在 GameMachine class的基础上面修改而成; 然后编写GameMachineTest将Naming.rebind()放在这里执行; 在client端创建GameMonitor,使其包含GameMachineRemote reference,并调用其get函数获取所需状态; 最后使用GameMonitorTestDrive进行测试。 ### Game Machine monitor Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch11_ProxyPattern/src/GameMonitor) for Game machine monitor demo code. ### Proxy Pattern Provides a surrogate(代孕) or placeholder for another object to control access to it。 Proxy pattern 的变种非常多,除了remote proxy之外还有很多很多种的proxy,书中还给出了 virtual proxy和protection proxy的两个示例,除此外还提到Firewall proxy, Caching proxy等等多种。所以,Proxy模式的功能非常强大,概念也有些难以理解,变种特别特别多,需要花费很大时间和精力去真正全面了解和消化。 <file_sep>//Author:xin //Date: 2018-06-06 //Strategy Pattern Demo public class FlyWithWings implements FlyBehavior { public void fly(){ System.out.println(&quot;Fly with wings&quot;); } } <file_sep>public class Tea extends CoffeeAndTea { public void brew(){ System.out.println(&quot;Dripping Tea through filter&quot;); } public void addCondiments(){ System.out.println(&quot;Adding lemon&quot;); } } <file_sep>//Author:xin //Date: 2018-06-06 //Strategy Pattern Demo public class oneDuck extends Duck { public oneDuck(){ flyBehavior = new FlyWithWings(); } public void display(){ System.out.println(&quot;I am one duck that can fly&quot;); } } <file_sep># Observer Pattern Author: Xin Date: 2018-6-4 ### 问题 有一个已经实现了的气象观测站app,现在想实时显示天气数据,怎么做? ### 解决方法 Observer模式非常好理解,可以参照预订报纸来进行理解,之前GUI中很多action listener也是基于此。 **Observer pattern**: defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. 体现的OO原则: **Loose Coupling 松耦合** ### 具体实现: 先定义两个接口:发布者Subject 和 订购者(观察者)Observer Public interface Subject { registerObserver(Observer o); removeObserver(Observer o); notifyObservers(); } Public interface Observer { Update(Subject sub); } **如何使用:** Public class weatherData implements Subject { private ArrayList observers;//用来存储自己的observers public WeatherData(){observers = new ArrayList();} //implement interface method public void registerObserver(Observer o){ observers.add(o); } public void removeObserver(Observer o){ int i = observers.indexOf(o); if(i&gt;=0){observers.remove(i);} } public void notifyObservers(){ for(int i=0;i&lt;observers.size();i++){ Observer ob = (Observer)observers.get(i); ob.update(this); } } //custom methods dataChanged(){ notifyObservers(); } } Public class update implements Observer { Private Subject subject; Public void update(Subject sub){ subject = sub; //use data to do sth here } } ### Demo Check [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch02_ObserverPattern) for Weather station demo. ### 总结 这种模式特别常用,所以JAVA有内置实现, Observable class 对应Subject; Observer interface对应 Observer; Observable class常用方法:addOberver(), deleteObserver(), notifyObservers(), setChanged(); Observer interface方法:update(Observable ob, Object args); 其中,Observable一方发送更新有两种方式: notifyObservers(Object arg); 这种为push方式,即将数据发给observer; notifyObservers(); 这种为pull方式,即observer自己索取数据,这种方式需要在obserable中定义getter函数。 **在notifyObservers之前,一定要setChanged();** 因为observable为类而非接口,所以JAVA built-in observer的使用受到限制,如果我们自己的类已经是一个子类了,那就没办法使用了,这时就需要自己实现observer模式。除了java.util,其余如java bean, spring等也提供了observer的实现。 <file_sep>### 问题: 现在有一个遥控器,要用来控制家里的电器,比如灯,风扇等,眼下有的就是遥控器和厂家提供的灯,风扇的类;如何设计类来实现遥控灯和风扇? ### 解决方法: 先通过点餐来对比理解 Command模式: 首先,客人点餐,makeOrder(); 然后,服务员将order传递到后厨,并提醒后厨接单;orderUp(); 最后,后厨负责做饭;prepareOrder(); 从上面可以看到,服务员和后厨是互相解耦的,任何一个order 只要实现了orderUp()方法都可以被服务员调用(orderup, make a request),触发实际的操作(prepare order) **以开灯为例来简单实现提出的遥控器问题:** 首先定义统一接口(类似于orderUp())command: Public interface Command { public void execute(); } 然后实现具体命令: Public class lightOnCommand implements Command{ Light light; Public lightOnCommand(Light light){this.light = light; }//将具体的receiver 传给command Public void execute(){ light.on(); }// 执行具体的操作 } 最后使用此command: Public class control(){ Command slot; SetCommand(Command cmd){ this.slot = cmd;}//这里将具体的command传给control Public void runCmd(){ slot. Execute(); } } 运行: Control control; Light light = new Light(); lightOnCommand onCmd = new lightOnCommand(light); //传入具体的receiver and action,创建具体command control.setCommand(onCmd);//传入invoker control.runCmd(); ### Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch06_CommandPattern/src) for two demos. ### Command pattern: 核心思想为: separate object making a request from object that receive and execute the request ### 模式类构建模型: 首先,要有receiver 类,也即接受request的物体,这里要定义出具体的操作,比如light, light.on(); 其次,创建抽象command类和具体的command类;也即具体实现command–excute()方法,也即将receiver, action进行连接; 最后,将以上concrete command传给invoker(这里为control)就可以触发实现具体的command了。 ### 总结: 这种模式的本质思想和实现方式和第一种strategy模式基本是相同的,侧重点不同, strategy模式侧重的是将变化的行为拿出来进行单独封装,利用组合的形式动态绑定具体行为; command模式侧重的是请求和具体实现的分离,将具体的实现拿出去单独封装,也是利用组合的形式来实现。 <file_sep>//author xin //date 2018.6.8 //factory method pattern public class PizzaStoreTestDrive { public static void main(String[] args){ PizzaStore1 s1 = new PizzaStore1(); Pizza p1 = s1.orderPizza(&quot;cheese&quot;); System.out.println(&quot;Here is your pizza: &quot; + p1.getName()); PizzaStore2 s2 = new PizzaStore2(); Pizza p2 = s2.orderPizza(&quot;deggie&quot;); System.out.println(&quot;Here is your pizza: &quot; + p2.getName()); } } <file_sep>### 问题: 一个披萨店,最开始的时候,类设计为 Public class pizzastore { Pizza pizza; Public Pizza orderPizza(String type){ If(type == “type1”){ pizza = new Pizza1(); } Else if(type == “type2”){ pizza = new Pizza2(); } Return pizza; } } 可以看到当pizza type变化时 ,这个类代码需要改变,因此当pizza店扩张后,增加更多pizza type时,代码的改变将是一个很严重的问题,怎么解决? ### 解决方法 **改进一:** 根据 “将变化的部分拿出来进行封装”的原则,进行改进: 将创建部分代码拿出来封装成一个类: Public class pizzaFactory { Public createPizza(String type){ If(type == “type1”){ pizza = new Pizza1(); } Else if(type == “type2”){ pizza = new Pizza2(); } Return pizza; } } 原来的类设计改为: Public class pizzastore { pizzaFactory fac; //添加一个引用到pizza factory public PizzaStore(PizzaFactory pf){this.fac = pf;} Public Pizza orderPizza(String type){ Pizza pizza = fac.createPizza(type); Return pizza; } } 这时有两个类,pizzaStore, pizzaFactory,两者为组合关系,这样改进后,type改变时,只需改变pizzaFactory即可。 如果我们需要两种pizza,只需要创建两个pizzaFactory即可,new pizzaFactory1(), new pizzaFactory2(),但是还要在 pizzaStore类 里面进行改动,所以还需要进一步改进。 **改进二:** Public abstract pizzaStore { Public orderPizza(String type){ Pizza pizza = createPizza(type); Return pizza; } Public abstract Pizza createPizza(String type); } 将pizzaFactory类改为createPizza method,但是定义为abstract类型,需要子类去具体实现。 这样当需要不同类型的pizza时,对pizzaStore进行扩展即可,扩展时在子类中对具体的pizza type通过createPizza进行创建,这时就不需要去改动pizzaStore的类源码了。 这里涉及到两大类组:pizzaStore类组和pizza类组。两大类组之间为平行关系。它们通过createPizza method进行连接。 这里的关键就是abstract createPizza method和abstract pizzaStore类的设计。其中的createPizza abstract method就是今天要讲的工厂方法模型。 工厂方法模型的本质思想为,将对象创建的过程拿出来进行封装,并抽象,让子类来实现具体对象的创建。 可以看出来,其实每种模式都是更高程度抽象的结果,比如这里就是将之前具体的类pizzaStore抽象成一个抽象类。 ### Factory Method Pattern: Defines an interface(abstract method) for creating an object, but let subclasses decide which class to instantiate, Factory method lets a class defer instantiation to subclasses. ### Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch04_FactoryPattern/src) for Demo. **模型类设计图:** 两大类组: Product组,即上面的pizza组,要创建的东西; Creator 组,即上面的pizzastore组,使用这些东西的对象; 每一组最上层都为一个抽象类,两个类组通过factory method即abstract method in creator class连接起来。 涉及到的一个OO原则: **Dependency Inversion Principle**: Depend on abstractions, do not depend on concrete classes。 具体到我们这个例子,最开始pizzastore(high level)是要依赖于concrete pizza(low level)的,后来通过factory method并更改类设计,使得pizza store(high-level) and pizza(low-level)全部都依赖于abstraction(factory method)。 这个原则是一个很重要的原则,很大程度上也是一种思维模式。要训练这种从high level 到low level的思考设计模式。 ### Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes. 可以理解为: Factory method模式用于创建一个对象时; Abstract Factory模式用于创建一组相互关联的对象时。 抽象工厂模式理解也能够理解,但是因为举例子的时候和工厂方法模式放在了一起,所以对抽象工厂模式的使用还有些迷糊,希望有一个单纯只使用抽象工厂模式的例子。 <file_sep>public interface Menu{ public myIterator createIterator(); } <file_sep>public class Light { public void on(){ System.out.println(&quot;light is on&quot;); } public void off(){ System.out.println(&quot;light is off&quot;); } } <file_sep>//Author:xin //date:2018-6-6 //self-defined observer pattern import java.util.*; public class WeatherData implements Subject { private ArrayList observers; private float temp; private float humi; private float pre; public WeatherData(){ observers = new ArrayList(); } //implement interface method public void registerObserver(Observer o){ observers.add(o); } public void removeObserver(Observer o){ int i = observers.indexOf(o); if(i&gt;=0){ observers.remove(i); } } public void notifyObservers(){ for(int i=0;i&lt;observers.size();i++){ Observer ob = (Observer)observers.get(i); ob.update(temp,humi,pre); } } //other methods public void measurementsChanged(){ notifyObservers(); } public void setMeasurements(float temp, float hum, float pre){ this.temp = temp; this.humi = hum; this.pre = pre; measurementsChanged(); } } <file_sep>## Welcome to Design Pattern Garden You can use the [editor on GitHub](https://github.com/960761/AboutDesignPattern/blob/master/README.md) to maintain and preview the content for your website in Markdown files. ## Contents You can refer to [**books**](https://github.com/960761/AboutDesignPattern/tree/master/books) folder for books of design pattern; You can refer to [**code**](https://github.com/960761/AboutDesignPattern/tree/master/code) folder for example code for books; You can refer to the following for notes: <ul> {% for post in site.posts %} <li> <a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a> </li> {% endfor %} </ul> [Go back to my homepage->](https://960761.github.io/) <file_sep>### 单例模式: 顾名思义,单例模式就是只允许每个class有一个且只有一个对象生成,在有些使用中会需要这种应用。 实现方式为: Public class Singleton { Private static Singleton uniqueInstance; Private Singleton(){} Public static Singleton getInstance(){ If(uniqueInstance == null){ uniqueInstance = new Singleton();} Return uniqueInstance; } } 在多线程在中会出现问题,可以使用以下解决方法: 1. 将getInstance方法进行synchronized,这种方式会对性能造成一些影响; 2. 使用eager instantiation, Public class Singleton { Private static Singleton uniqueInstance = new Singleton(); Private Singleton(){} Public static Singleton getInstance(){ return uniqueInstance; } } 这种方式使得JVM 在load class的时候会生成一个实例,可以确保在任何thread访问之前创建。 当有多个classloader时也会产生多个instance,所以记得指定一种特定的classloader。 3. 在之前的基础上面,只将new 部分synchronized,这种方法不适用于java 1.4 and earlier。 Public class Singleton { Private volatile static Singleton uniqueInstance; Private Singleton(){} Public static Singleton getInstance(){ If(uniqueInstance == null){ Synchronized (Singleton.class){ If(uniqueInstance == null){ uniqueInstance = new Singleton(); } } } Return uniqueInstance; } } 目前没有合适的示例来帮助理解。 <file_sep>### 问题: 星巴克咖啡因为公司扩展,需要一个新的order system ,咖啡中可以加入各种配料,所以计算最终的花费就成了一个问题,如何设计才能够既满足新的要求又不去改动已有的代码? ### 解决方法: 方法1:为每种选择方案创建类,会造成大量的类,维护起来很困难; 方法2:将配料价格先提前加入进去,在base class中实现,每种咖啡只需在此基础上加入自己的价格即可, 这种方法的问题是,如果配料的种类或或价格改变,就需要改动base class code,而且如果加入新的咖啡种类不能加入这些配料又会是个问题,再比如要多份配料等都会成为问题,带来code change。 **OO原则**:OPEN-CLOSEprinciple: classes should be open for extension , but closed for modification。 满足open-close原则意味着更多层次的抽象,会使得代码更复杂,所以不需要也不能够所有的代码都满足这个原则,而是挑选日后最容易发生需求改变的部分使用这个原则进行设计。 ### Decorator pattern Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. 这种模式就是利用open-close原则,适用于在不改动原来class的基础上扩展class的功能。 想要扩展原有类的功能最常用的为inherance,但是继承只能在compile时静态扩展,如果要动态扩展,只能使用composition + delegate,Decorator模式就是基于composition思想的实现。 Decorator,顾名思义,就是加上一层层的装饰品,在原有class(每一种单纯咖啡)的基础上加入一层层的外包裹(decorator,这里指各种配料),当需要调用方法的时候,先一层层往里调用,返回结果时从最里面一层层的返回对应的值,然后每一层加入自己的值,最后就得到了最后的值。 ### Decorator模式类设计原型: 首先设计两个基本抽象类,被包装的类,这里指beer类,称为component; 包装类,这里称为Decorator类,也是一个抽象类, 要注意的是Decorator和Component的关系,两者既是inherence,又是composition,具体表现为Decorator类一方面继承自Component,另一方面还包含Component,这种关系理解起来有一些绕,之所以decorator要继承component是为了保证两者类型是相同的,这样才可以使用多态原理,decorator之所以要包含component很好理解,因为这种模式的目的就是为它添加一些新的功能。 然后,构建具体的component, decorator类; 最后根据具体需求创建具体的component类,“包装”上需要的decorator类,实现所需功能。 ### 具体使用: 以starbuzz coffee为例来实现一下: 首先设计抽象component, decorator类,这里为beverage(咖啡抽象类), condimentDecorator(配料抽象类), 然后创建具体类: Concrete component : Espresso extends beverage, Decaf extends beverage等具体的coffee, Concrete decorator: Milk extends condimentDecorator, Mocha extends condimentDecorator等具体的配料, 注意concrete decorator类的实现: Public class Milk extends condimentDecorator { Beverage beer; //包含对被包装对象的引用 Public Milk(Beverage br){this.beer = br;} Public String getDesc(){ return beer.getDesc +”, Milk” ; } Public double cost(){ return .20+beer.cost() ;} } ### 举例实现: 计算一种加有 milk, mocha的espresso的价格: 首先,创建espresso : Beverage beer = new Espresso(); 然后,添加Milk,创建添加有milk的beer: Beverage beer1 = new Milk(beer);//将被包装的espresson传进去 然后,再添加mocha,Beverage beer2 = new Mocha(beer1); // 此时被包装的为beer1 最后计算价格,调用beer2.cost();即可, 具体过程为,beer2.cost会调用被包装的beer1.cost(),beer1会去调用espresso的价格,最后得到espresso的价格后,返回到beer1,beer1附加上milk cost(20),返回给beer2,beer2会附加上mocha cost(15),最终得到返回值即为espresso + milk + mocha的总价格。 ### Demo Click [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch03_DecoratorPattern/src) for demo. ### 总结 在JAVA自身的API中也有很多地方用到这种模式,比如JAVA I/O中的inputstream, fileInputStream。 其中input stream 为component,有很多种具体的基本读入操作比如fileinputstream, stringbufferInputstream等;FilterInputStream为decorator,有BufferedInputStream, DataInputStream等各种decorator实现各种定制化的读入操作。 借用这种模式,可以很容易地扩展现有的input stream, 比如实现一种将输入中的大写字母转换为小写字母的读入inputstream,可以设计一个继承自FilterInputStream的类,也即decarator,在这个decarator中添加自己想要的功能,然后用这个decorator去包装需要的基本输入操作即可。 Decorator pattern的缺点是,会产生大量的类,增加代码数量。在使用这种模式时要注意这个特点,慎重选择。 <file_sep>public class Fan{ public static final int HIGH = 3; public static final int LOW = 1; public static final int OFF = 0; String location; int speed; public Fan(String loca){ this.location = loca; speed = OFF; } public void setHigh(){ speed = HIGH; System.out.println(&quot;Fan high speed&quot;); } public void setLow(){ speed = LOW; System.out.println(&quot;Fan low speed&quot;); } public void off(){ speed = OFF; System.out.println(&quot;Fan is off&quot;); } public int getSpeed(){ return speed; } } <file_sep># Strategy Pattern Author: Xin Date: 2018-6-4 ### 问题: 一款已经成熟实现的鸭子游戏,在原先的基础上面需要添加 fly的行为,怎么做? 方法: 方法1: 在父类中添加 fly方法,问题是,并不是所有的子类都有这个行为; 方法2:将Fly 设计为interface,有这种行为的子类实现接口,这会大量改动代码且duplicate code存在,而且若以后fly改变,还需要大量修改代码。 ### 解决方法: 首先,将 fly这种行为从duck类中拿出来进行封装,每种类型鸭子的飞行不一样,所以fly这种行为是不断变化的,不仅拿出来,还要封装和抽象化; 然后,将fly定义为一个类,这个类中只有fly方法,但并不实现它,然后再定义继承自它的子类,在子类中具体实现。 因为一个类不可以同时继承两个类,但却可以实现多个接口,所以将fly定义成接口。其实,接口的实质就是一个方法抽象类。 最终方案的类设计结构为: 将Fly单独拿出来定义为 interface FlyBehavior { public void fly(); } 具体的飞行种类定义为实现它的类: Class FlyType1 implements FlyBehavior{ Public void fly(){ concrete operation } } Class FlyType2 implements FlyBehavior{ Public void fly(){ concreate operation } } ### 如何使用: *父类的设计:* 将flyBehavior这种行为包含在duck类中,作为其一个成员,并定义一个调用fly的方法; Class Duck { FlyBehavior fb; Public void performFly(){ fb.fly(); } } *子类的设计:* 子类中需要初始化FlyBehavior这个变量,只有初始化后才可以调用具体的方法 Class oneDuck extends Duck { Public oneDuck() { fb = new FlyType1(); } //构造函数中进行初始化 } 使用时,直接 oneDuck.performFly();就可以了,这个时候就是调用的flyType1这种实现。 *父类的改进:* 以上还只能在子类的构造过程中选择具体的飞行实现方法,在父类中添加setFly方法: Class Duck { FlyBehavior fb; setFly(FlyBehavior fbb){fb = fbb; } Public void performFly(){ fb.fly(); } } 使用时: oneDuck.setFly(new FlyType2()); oneDuck.performFly(); 这就可以在runtime时动态改变fly行为了。 ### Demo Check [here](https://github.com/960761/AboutDesignPattern/tree/master/code/HeadFirst_DesignPattern/ch01_StrategyPattern/src) for Duck Demo. ### 设计模式总结: 以上解决问题的方法就被称为 **Strategy pattern** : defines a family of algorithms, encapsulates each one, and makes them interchangeable, Strategy lets the algorithms vary independently from clients that use it. 将变化的行为设计为抽象方法类(也即interface),以往都是在使用这种接口时进行实现,比如,若oneDuck有这种行为,则在oneduck中具体实现,而这种模式中,则是将实现也拿出来进行封装,也即设计不同的实现类实现这个接口,而不是在使用者中实现。 在使用这种模式时用到多态概念: flybehavior = new flyType1(); 等同于 animal = new Dog(); 这个模式涉及到**OO的三大原则**: **原则1**:将变化的部分拿出来进行封装(将fly拿出来进行封装); **原则2**:针对接口抽象化而不是具体的实现(对fly类进行抽象化而不是具体实现); **原则3**:更多使用composition而非Inherence(将fly作为DUCK的成员变量而不是继承)。 **Strategy pattern 关键词:** 方法抽象化 <file_sep>demo for singleton pattern <file_sep>### OO 基础: Abstraction 抽象 Encapsulation 封装 Polymorphism 多态 Inheritance 继承 ### OO原则: Encapsulate what varies; Favor composition over inheritance; Program to interfaces, not implementation; Strive for loosely coupled designs between objects that interact; Classes should be open for extension but closed for modification; Depend on abstractions, do not depend on concrete classes; Only talk to your immediate friends; Don’t call us, we will call you; A class should have only one reason to change. ### 常用设计模式概述: **Strategy:** 将算法实现进行封装,动态选择实现方式,使用composition + delegate 思想实现; **Observer:** 监听模式 **Decorator:** 在不改变原有类代码前提下,动态添加新功能,虽然可以使用 inheritance实现,但是继承只能静态添加,动态要使用composition + delegate思想实现; **Factory:** 将 类创建 过程抽象封装; **Singleton:** 用于只需要一个类实例情形; **Command:** 将 方法调用和触发 进行抽象封装,和strategy有些相似,但是两者的设计目的是不同的,比如,用户发出fly的请求,strategy侧重实现各种具体的fly行为;而command则是,根据用户发出fly or speak or else等各种不同种类的请求进行具体响应,侧重方法调用的实现,将make a quest 和 execute the action分离开来。在实现上面,也是使用了composition + delegate思想。 **Adapter:** 用来将一种类(接口)变换成另一种类(接口),基于inheritance + composition 思想实现这种模式; **Façade:** 用于简化接口;基于composition思想实现这种模式; **Template Method :** 适用于框架里的部分具体化,即将某个算法实现中的部分进行抽象封装,基于Inheritance思想实现,Factory method可以看成template method的一种特例; **Iterator:** 适用于对不同存储结构的一组数据进行统一的循环读取操作; **Composite:** 适用于处理tree-structured data 树形数据的情形; **State:** 状态的改变,composition + delegate思想; **Remote Proxy:** 基于RMI的原理,适用于不同JVM间有交流的情形。 ### 常用设计模式列表比较 |名字|定义|示例 |实现|备注| |-|-|-|-|-| |Strategy |将算法实现进行封装抽象,动态选择实现方式 |比如Duck的fly行为有多种具体方式 |Composition + delegate| |Decorator |不改变原类代码前提下动态添加新行为 |Coffee order system |Inheritance + composition| |Command |将 方法调用和触发 进行抽象封装 |Remote control |Composition + delegate |和strategy相似,但两者设计目的不同,比如,用户发出fly的请求,strategy侧重实现各种具体的fly行为;而command根据用户发出fly or speak or else等各种不同种类的请求进行响应,侧重方法调用的实现,将make a quest 和 execute the action分离开来 |Adapter |将一种类(接口)转换为另一种类(接口) |Goose &gt; duck |Inheritance + composition| |Facade |用于简化涉及到多个对象的接口 |Home theatre |composition| |Template |适用于框架里的部分具体化,即将某个算法实现中的部分进行抽象封装 |Make coffee and tea |inheritance |Factory method为它的一个特例,注意和Strategy的区别| |Factory |将 类创建过程 进行封装和抽象 |Make pizza inheritance ||衍生出Abstract Factory模式 |Observer |监听对象 |Weather report abstract | |Singleton |用于某种类只需要一个对象的情形| thread| Static + private| |Iterator |适用于对不同存储结构的一组数据进行统一的循环读取操作 |两种menu的组合 |delegate | |Composite |适用于处理tree-structured data 树形数据的情形 |Submenu |delegate| |State |涉及到不同状态之间转换的情形 |Game ball |Composition + delegate| |Remote Proxy| 不同的JVM间相互调用| Remote monitor| RMI| Proxy 功能很强大,也很负责,根据功能分为很多种类|
f1b6ba164b926ad1fa1f22c9c46369e5c4e7387e
[ "Markdown", "Java" ]
31
Java
960761/AboutDesignPattern
90e6e7b3f02067b808d9c5af6900dd7e65c489a0
825d49f55ec4446c35e0310522d241f3003858a0
refs/heads/master
<file_sep>import * as React from 'react'; import {View} from 'react-native'; import WelcomeScreen from './screens/SigningIn' import {createSwitchNavigator,createAppContainer} from 'react-navigation'; import appTab from './screens/appTab.js'; import navi from './screens/Navigation'; import Drawer from './screens/Drawer'; export default class App extends React.Component { render(){ return ( <AppContainer/> ); } } const switchNavigator=createSwitchNavigator({ Welcome:{screen:WelcomeScreen}, Options : {screen:navi}, bottom:{screen:appTab}, }) const AppContainer = createAppContainer(switchNavigator);<file_sep>import * as React from 'react'; import {View,Text,TextInput,TouchableOpacity,ScrollView,KeyboardAvoidingView,StyleSheet, Alert,Modal} from 'react-native'; import db from '../config'; import firebase from 'firebase' import HomeScreen from '../screens/HomeScreen'; import appTab from '../screens/appTab'; export default class WelcomeScreen extends React.Component{ constructor(){ super(); this.state={ email:'', password:'', name:'', name2:'', contact:'', cP:'', address:'', isModalVisible:'false' } } signUp=(email,password,cP)=>{ if (password !== cP){ return Alert.alert("Password Doesn't Match"); }else{ firebase.auth().createUserWithEmailAndPassword(email,password).then((response)=>{ db.collection("Users").add({ 'FirstName':this.state.name, 'LastName':this.state.name2, 'Contact':this.state.contact, 'Email':this.state.email, 'Address':this.state.address }) return Alert.alert("Successfully Signed Up", '', [ {text:'OK', onPress:()=>{ this.setState({'isModalVisible':false}) }} ] ); }).catch((error)=>{ var errorCode = error.code; var errorMessage = error.message; Alert.alert(errorMessage); }) } } signIn=(email,password)=>{ firebase.auth().signInWithEmailAndPassword(email,password).then((response)=>{ this.props.navigation.navigate('Home'); }).catch((error)=>{ var errorCode = error.code; var errorMessage = error.message; return Alert.alert(errorMessage) }) } showModal=()=>{ return( <Modal animationType='slide' transparent={false} visible={this.state.isModalVisible} > <View style={styles.modal}> <ScrollView style={{width:'100%'}}> <Text style={styles.signIng}>Signing Up</Text> <TextInput placeholder="<NAME>" maxLength={10} onChangeText={text=>{this.setState({name:text})}} style={styles.First} /> <TextInput placeholder="<NAME>" maxLength={15} onChangeText={text=>{this.setState({name2:text})}} style={styles.Last} /> <TextInput placeholder="address" multiline={true} onChangeText={text=>{this.setState({address:text})}} style={styles.add} /> <TextInput placeholder="Mobile No." maxLength={10} keyboardType="numeric" onChangeText={text=>{this.setState({contact:text})}} style={styles.cont} /> <TextInput placeholder="email Id" keyboardType="email-address" onChangeText={text=>{this.setState({email:text})}} style={styles.email} /> <TextInput placeholder="<PASSWORD>" secureTextEntry={true} onChangeText={text=>{this.setState({password:text})}} style={styles.pass} /> <TextInput placeholder="confirm password" secureTextEntry={true} onChangeText={text=>{this.setState({cP:text})}} style={styles.cP} /> <TouchableOpacity onPress={()=>this.signUp(this.state.email, this.state.password, this.state.cP)} style={styles.reg} > <Text style={styles.register2}>Register</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>this.setState({'isModalVisible':false})} style={styles.goBack} > <Text style={styles.goB}>Go Back</Text> </TouchableOpacity> </ScrollView> </View> </Modal> ) } render(){ return( <View> <View style={{justifyContent:'center'}}></View> <View> <Text style={styles.barter}> Barter System</Text> </View> { this.showModal() } <KeyboardAvoidingView behavior="padding" enabled> <TextInput style={styles.e} placeholder="email Id" keyboardType="email-address" onChangeText={(text)=>{this.setState({email:text})}} /> <TextInput style={styles.p} placeholder="<PASSWORD>" secureTextEntry={true} onChangeText={(text)=>{this.setState({password:text})}} /> <TouchableOpacity style={[styles.b,{width:100}]} onPress={()=>{this.signIn(this.state.email,this.state.password)}}> <Text style={[styles.in,{fontSize:25}]}>Sign In</Text> </TouchableOpacity> <TouchableOpacity style={[styles.a,{width:150,textAlign:'center',paddingLeft:30}]} onPress={()=>this.setState({'isModalVisible':true})}> <Text style={[styles.up,{fontSize:30}]}>Sign Up</Text> </TouchableOpacity> </KeyboardAvoidingView> </View> ) } } const styles = StyleSheet.create({ a:{ backgroundColor:'white', alignSelf:'center', width:90, borderColor:'#4466FF', borderWidth:3, borderRadius:15, marginBottom:20, marginTop:20, marginLeft:-15 }, b:{ backgroundColor:'white', width:90, borderColor:'#22CCFF', borderWidth:3, borderRadius:7, marginLeft:150 }, e:{ marginTop:120, //color:'grey', backgroundColor:'#EEEEBB', width:290, alignSelf:'center', fontSize:30, paddingLeft:5 }, p:{ marginTop:20, backgroundColor:"#EEEEBB", width:290, alignSelf:'center', marginBottom:20, fontSize:30, paddingLeft:5 }, back:{ backgroundColor:'#33BB00', marginBottom:0 }, in:{ justifyContent:'center', paddingLeft:0, fontWeight:'bold', alignSelf:'center', textAlign:'center', fontSize:30 }, up:{ fontWeight:'bold', //justifyContent:'center', alignSelf:'center', marginLeft:-35, }, modal:{ marginTop:150, flex:1, justifyContent:'center', alignSelf:'center', alignItems:'center', }, barter:{ fontWeight:'bold', marginTop:130, justifyContent:'center', alignSelf:'center', fontSize:50, backgroundColor:'#8888FF', padding:10, borderRadius:15 }, KeyboardAvoidingView:{ flex:1, justifyContent:'center', alignItems:'center' }, First:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, Last:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, add:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, cont:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, email:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, pass:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, cP:{ borderRadius:20, borderWidth:2, borderColor:'yellow', fontSize:17, width:290, paddingLeft:10, backgroundColor:'#A0FFAA', marginTop:7 }, register2:{ justifyContent:'center', alignSelf:'center', fontWeight:'bold', padding:3, }, reg:{ borderColor:'#56FC00', borderWidth:2, borderRadius:3, marginTop:15, width:90, marginLeft:90, padding:2 }, goBack:{ borderColor:'red', borderWidth:2, borderRadius:3, marginTop:15, width:90, marginLeft:90, padding:2 }, goB:{ justifyContent:'center', alignSelf:'center' }, signIng:{ justifyContent:'center', alignSelf:'center', borderColor:'black', borderWidth:1, fontSize:20, borderRadius:9, paddingLeft:5 } }) <file_sep>import * as React from 'react'; import {Icon,Badge,Header} from 'react-native-elements'; import {View,Text,TextInput,TouchableOpacity} from 'react-native'; import db from '../config'; export default class MyHeader extends React.Component{ constructor(props){ super(props); this.state={ value:'' } } numberOfNotifications=()=>{ db.collection('AllNotifications').where('NotificationStatus','==','Unread').onSnapshot((snapshot)=>{ var unreadNotifications = snapshot.docs.map((doc)=>doc.data()); this.setState({ value:unreadNotifications.length }) }) } componentDidMount(){ this.numberOfNotifications(); } BellWithBadge=()=>{ return( <View> <Icon name='bell' type='font-awesome' size={25} onPress={()=>{ this.props.navigation.navigate('Notification') }} /> <Badge value={this.state.value} containerStyle={{position:'dynamic', right:-3, left:-3}} /> </View> ) } MyHeader=()=>{ return( <Header leftComponent={<Icon name='bars' type='font-awesome' size={25} onPress={()=>{ this.props.navigation.toggleDrawer()}} />} centerComponent={{ text:this.props.title, style:{color:'black', backgroundColor:'white', width:300, alignSelf:'center', alignItems:'center', justifyContent:'center', borderRadius:20, paddingLeft:60, paddingTop:5, paddingBottom:5, fontSize:30 } }} rightComponent={<this.BellWithBadge {...this.props}/>} backgroundColor='#EAF8FE' /> ) } }<file_sep>import firebase from 'firebase'; require('@firebase/firestore'); const firebaseConfig = { apiKey: "<KEY>", authDomain: "bartersystemapp-b6d7b.firebaseapp.com", projectId: "bartersystemapp-b6d7b", storageBucket: "bartersystemapp-b6d7b.appspot.com", messagingSenderId: "452518883812", appId: "1:452518883812:web:ff1d916b95b2093b4257f1" }; firebase.initializeApp(firebaseConfig); export default firebase.firestore();<file_sep>import * as React from 'react'; import {createBottomTabNavigator} from 'react-navigation-tabs'; import Exchange from '../screens/ExchangeScreen'; import HomeScreen from '../screens/HomeScreen' import {Image} from 'react-native'; import firebase from 'firebase'; const appTab = createBottomTabNavigator({ Barter:{screen:HomeScreen, navigationOptions:{ tabBarIcon : <Image source={require('../assets/Home.png')} style={{width:30,height:30}}/>, tabBarLabel:'Requests' }, }, Exchange:{screen:Exchange, navigationOptions:{ tabBarIcon:<Image source={require('../assets/exchange.png')} style={{width:30,height:30}}/>, tabBarLabel:'Exchange' }, } }) export default appTab;<file_sep>import * as React from 'react'; import {createDrawerNavigator} from 'react-navigation-drawer'; import Drawer from '../screens/Drawer'; import appTab from '../screens/appTab'; import settings from '../screens/Settings'; import MyBarter from '../screens/MyBarters'; import Notifications from '../screens/Notification'; const navi = createDrawerNavigator({ Home:{ screen:appTab }, Settings:{ screen:settings }, MyBarters:{ screen:MyBarter }, Notification:{screen:Notifications} }, { contentComponent:Drawer }, { initialRouteName:'Home' }) export default navi;<file_sep>import * as React from 'react'; import {View,Text,FlatList,TouchableOpacity} from 'react-native'; import firebase from 'firebase'; import db from '../config'; import MyHeader from '../screens/AppHeader'; import {ListItem} from 'react-native-elements'; export default class Exchange extends React.Component{ constructor(){ super(); this.state={ userId:firebase.auth().currentUser.email, allBooks:[] } this.requestRef = null } getRequestedItemsList=()=>{ this.requestRef = db.collection("UsersRequest").onSnapshot(snapshot=>{ var allBooks = snapshot.docs.map((doc)=>doc.data()) this.setState({ allBooks:allBooks }) }) } componentDidMount(){ this.getRequestedItemsList(); } componentWillUnount(){ this.requestRef(); } keyExtractor=(item,index)=>index.toString(); renderItem=({item,i})=>{ return( <ListItem key={i} title={item.Item} subtitle={item.Reason} titleStyle={{color:'black', fontWeight:'bold'}} rightElement={ <TouchableOpacity onPress={()=>{ this.props.navigation.navigate('ReceiverDetails',{'details':item})}} > <Text>Exchange</Text> </TouchableOpacity > } bottomDivider /> ) } render(){ return( <View style={{justifyContent:'center',marginTop:30}}> <View> { this.state.allBooks.length === 0 ?( <View> <Text>List Empty</Text> </View> ): ( <FlatList keyExtractor={this.keyExtractor} data={this.state.allBooks} renderItem={this.renderItem} /> ) } </View> </View> ) } }<file_sep>import * as React from 'react'; import {View,Text,TextInput,TouchableOpacity,StyleSheet,KeyboardAvoidingView, ToastAndroid, Alert} from 'react-native'; import firebase from 'firebase'; import db from '../config'; import MyHeader from '../screens/AppHeader'; export default class HomeScreen extends React.Component{ constructor(){ super(); this.state={ name:'', reason:'', userId:firebase.auth().currentUser.email } } getUniqueId=()=>{ return Math.random().toString(36).substring(8); } submit=(Name,Reason)=>{ var userId = this.state.userId var randomRequestId = this.getUniqueId(); db.collection('UsersRequest').add({ 'Item' : Name, 'Reason' : Reason, 'UserId' : userId, 'requestId': randomRequestId }) this.setState({ name:'', reason:'' }) return Alert.alert("Submitted Successfully"); } render(){ return( <View> <MyHeader naviations={this.props.navigation} title="RequestItem"/> <TouchableOpacity style={styles.list}> <Text style={{paddingLeft:20,fontSize:50,fontWeight:'bold',width:300}}>Fill Details</Text> <Text style={{fontWeight:'italics'}}>*plz fill the details to exchange an item*</Text> </TouchableOpacity> <KeyboardAvoidingView behavior="padding"enabled> <View> <TextInput placeholder='Item Name' keyboardType='ascii-capable' onChangeText={(text)=>{ this.setState({ name:text }) }} style={styles.item} /> </View> <View> <TextInput placeholder='Reason' onChangeText={(text)=>{ this.setState({ reason:text }) }} multiline={true} style={styles.reason} /> </View> <TouchableOpacity onPress={()=> {this.submit(this.state.name,this.state.reason)}} style={styles.submit} > <Text style={{textAlign:'center'}}>Submit</Text> </TouchableOpacity> </KeyboardAvoidingView> </View> ) } } const styles = StyleSheet.create({ item:{ justifyContent:'center', alignSelf:'center', marginTop:100, borderColor:'black', borderRadius:3, borderWidth:2, backgroundColor:'#52FF99', width:240, height:40, fontSize:20, paddingLeft:4 }, reason:{ backgroundColor:'#52FF99', justifyContent:'center', alignSelf:'center', textAlign:'left', borderWidth:2, borderColor:'black', borderRadius:3, width:240, marginTop:20, fontSize:20, paddingLeft:4, height:51 }, submit:{ backgroundColor:'yellow', borderRadius:10, borderWidth:2, borderColor:'black', justifyContent:'center', alignSelf:'center', width:150, marginTop:50, height:30 }, back:{ backgroundColor:'#A55F66' }, list:{ backgroundColor:'#88FC33', marginTop:90, justifyContent:'center', alignSelf:'center', borderRadius:5, width:240, paddingLeft:10 } })
8fab0404dbfe27380eb3ec5ea4c7598559e6eb10
[ "JavaScript" ]
8
JavaScript
dhruv11-d/BarterSystemApp8
9e912c078ba988fd3b88f89451ec99aa14930306
bb6ed67ae1b57f121e38e47652eade65274c338d
refs/heads/master
<file_sep>// code here const getData = async (url) => { const resp = await fetch(url); const data = await resp.json(); data.forEach((usuario) => { const { nombre, correo} = usuario; // Object Destructuring =) document.querySelector("#nombreUsuario").innerHTML = nombre; document.querySelector("#correoUsuario").innerHTML = correo; }); }; window.addEventListener("DOMContentLoaded", () => { getData("http://localhost:4000/usuario") }); document.querySelector("a").addEventListener("click", ()=> localStorage.clear()); <file_sep>//Code here - HTML let preguntasHTML = [ [ { pregunta: "¿Qué etiqueta es semánticamente correcta para el contenido principal?", correcta: "main", opcion2: "section", opcion3: "header", }, { pregunta: "¿Qué etiqueta HTML nos sirve para incluir archivos de JavaScript?", correcta: "script", opcion2: "br", opcion3: "styles", }, ], [ { pregunta: "Organiza la estructura de un documento HTML5:", elemento1: "<!DOCTYPE html>", elemento2: "<html>", elemento3: "<head></head>", elemento4: "<body></body>", elemento5: "</html>", }, { pregunta: "Ordena Jerárquicamente las siguientes etiquetas:", elemento1: "<h1>", elemento2: "<h2>", elemento3: "<h3>", elemento4: "<h4>", elemento5: "<p>", }, ], [ { pregunta: "¿Qué tecnologías pertenece al MEVN Stack?", imagen1: "../images/Windows.png", imagen2: "../images/Kotlin.png", correcta: "../images/Vue.png", imagen4: "../images/Angular.png", }, { pregunta: "Sistema de base de datos NoSQL, orientado a documentos y de código abierto...", imagen1: "../images/Linux.png", correcta: "../images/Mongo.png", imagen2: "../images/Nodejs.png", imagen4: "../images/express.png", }, ], ]; let randomImage = Math.floor(Math.random() * 4); let animaciones = new Array(); animaciones[0] = "../images/boy1.svg"; animaciones[1] = "../images/boy2.svg"; animaciones[2] = "../images/girl1.svg"; animaciones[3] = "../images/girl2.svg"; let randomIndex = Math.floor(Math.random() * 3); let randomQuestion = Math.floor(Math.random() * 2); if (randomIndex === 0) { // 3 respuestas 1 correcta const { pregunta, correcta, opcion2, opcion3 } = preguntasHTML[randomIndex][randomQuestion]; let pintarDom = ` <div id="pregunta"> <img src="${animaciones[randomImage]}" alt="Imagen Aleatoria" /> <p>${pregunta}</p> </div> <div id="opciones"> <div class="seleccionOpcion" id="1"> <p>${correcta}</p> <input type="checkbox" name="" id=""> </div> <div class="seleccionOpcion" id="2"> <p>${opcion2}</p> <input type="checkbox" name="" id=""> </div> <div class="seleccionOpcion" id="3"> <p>${opcion3}</p> <input type="checkbox" name="" id=""> </div> </div> <button>COMPROBAR</button> `; document.body.innerHTML = pintarDom; let seleccion = document.getElementsByClassName("seleccionOpcion"); let comprobar = document.querySelector("button"); let respuesta = ""; seleccionRespuesta = (e) => { const valor1 = e.target.id; document.getElementById(valor1).classList.toggle("verde"); respuesta = valor1; }; for (var i = 0; i < seleccion.length; i++) { seleccion[i].addEventListener("click", seleccionRespuesta); } comprobar.addEventListener( "click", (comprobarRespuesta = () => { if (respuesta == 1) { Swal.fire({text:'¡Buen Trabajo!', icon:'success' }).then(() => {localStorage.setItem("opcionesHTML-Correcta", 1); window.location.reload()}) comprobar.classList.toggle("verdeCorrecto"); } else { Swal.fire({text:'Incorrecto', icon:'error' }).then(() => {localStorage.setItem("opcionesHTML-Incorrecta", 1); window.location.reload()}) comprobar.classList.toggle("rojo"); } }) ); } else if (randomIndex === 1) { // Organizar codigo const { pregunta, elemento5, elemento4, elemento3, elemento2, elemento1 } = preguntasHTML[randomIndex][randomQuestion]; let pintarDom = ` <header id="pregunta1">${pregunta}</header> <div class="organizarElementos"> <hr> </div> <div id="inicial"> <input class="desplazarCodigo" id="0" type="button" value="${elemento5}"> <input class="desplazarCodigo" id="1" type="button" value="${elemento4}"> <input class="desplazarCodigo" id="2" type="button" value="${elemento3}"> <input class="desplazarCodigo" id="3" type="button" value="${elemento2}"> <input class="desplazarCodigo" id="4" type="button" value="${elemento1}"> </div> <div id="contenedorBoton"> <button>COMPROBAR</button> </div> `; document.body.innerHTML = pintarDom; let comprobar = document.querySelector("button"); let seleccion = document.getElementsByClassName("desplazarCodigo"); let arregloRpta = new Array(); let acumArray = new Array(); let arreglo2 = new Array(); for (var i = 0; i < seleccion.length; i++) { seleccion[i].addEventListener("click", desplazar = (e) =>{ const valor = e.target; acumArray = arregloRpta.push(valor.id); arregloRpta[i] += acumArray; arreglo2 = arregloRpta.filter(element => element != null && !Number.isNaN(element)); //console.log(arreglo2); for (let i = 0; i < 4; i++) { document.querySelector(".organizarElementos").append(valor); } }); } comprobar.addEventListener("click", comprobarRespuesta = () =>{ const arregloPrueba = ["4", "3", "2", "1", "0"]; if (arreglo2.length==arregloPrueba.length && arreglo2.every((v,i) => v === arregloPrueba[i])) { Swal.fire({text:'¡Buen Trabajo!', icon:'success' }).then(() => {localStorage.setItem("organizarHTML-Correcta", 1); window.location.reload()}) comprobar.classList.toggle("verdeCorrecto"); } else { Swal.fire({text:'Incorrecto', icon:'error' }).then(() => {localStorage.setItem("organizarHTML-Incorrecta", 1); window.location.reload()}) comprobar.classList.toggle("rojo"); } }); } else if (randomIndex === 2) { // Seleccion imagen const { pregunta, imagen1, imagen2, correcta, imagen4 } = preguntasHTML[randomIndex][randomQuestion]; let pintarDom = ` <header>${pregunta}</header> <div id="padreImagen"> <div class="item"> <img class="seleccionImagen" id="1" src="${imagen4}" alt="imagen 4"> </div> <div class="item"> <img class="seleccionImagen" id="2" src="${correcta}" alt="imagen 3"> </div> <div class="item"> <img class="seleccionImagen" id="3" src="${imagen2}" alt="imagen 2"> </div> <div class="item"> <img class="seleccionImagen" id="4" src="${imagen1}" alt="imagen 1"> </div> </div> <button>COMPROBAR</button> `; document.body.innerHTML = pintarDom; let seleccion = document.getElementsByClassName("seleccionImagen"); let comprobar = document.querySelector("button"); let respuesta = ""; seleccionRespuesta = (e) => { const valor = e.target.id; document.getElementById(valor).classList.toggle("verde"); respuesta = valor; }; for (var i = 0; i < seleccion.length; i++) { seleccion[i].addEventListener("click", seleccionRespuesta); } comprobar.addEventListener( "click", (comprobarRespuesta = () => { if (respuesta == 2) { Swal.fire({text:'¡Buen Trabajo!', icon:'success' }).then(() => {localStorage.setItem("imagenHTML-Correcta", 1); window.location.reload()}) comprobar.classList.toggle("verdeCorrecto"); } else { Swal.fire({text:'Incorrecto', icon:'error' }).then(() => {localStorage.setItem("imagenHTML-Incorrecta", 1); window.location.reload()}); comprobar.classList.toggle("rojo"); } }) ); } //alert("Ha culminado el proceso. Debe empezar desde en cero en cualquiera de las categorías!."); <file_sep>import dataUsuario from './dataUsuario'; import './style.css'; console.log("Daily - Bits");
3960fa9e2f54f77a3da5631aaedc7f934dfa6c61
[ "JavaScript" ]
3
JavaScript
Biggiegun/sprint1WB
85afd5ab0b608b1a15fa1ae94b0dd59faf1e13a3
7c859605eaa3796142fe294840e273589487e4b8
refs/heads/main
<file_sep>def freq(str): max_count=1 count=1 n=len(str) for i in range(0,n-1): if(str[i]==str[i+1]): count+=1 max_count=max(max_count,count) else: count=1 print("It is a ",max_count," neighbour") str=input("Enter the string: ") freq(str)<file_sep>ls=[] n=int(input("Enter number of elements: ")) sum=0 for i in range(0,n): ele=int(input()) ls.append(ele) for i in range(0,n): sum+=ls[i] print(sum) <file_sep>s = input("Enter the string: ") variable = True while variable and s != "": variable = False for i in range(len(s) - 1): if s[i] == s[i+1]: variable = True s = s[:(i)] + s[(i+2):] break if s == "": print('Empty String') else: print(s)<file_sep>def is_prime(n): for i in range (2,n): if(n%i == 0): return False return True def twin_prime(lb,ub): for i in range(lb,ub-2): if(is_prime(i) and is_prime(i+2)): print(i," ", i+2) i+=2 lb=int(input("Enter the lower bound: ")) ub=int(input("Enter the upper bound: ")) twin_prime(lb,ub) <file_sep>ls=[] n=int(input("Enter number of elements: ")) prod=1 for i in range(0,n): ele=int(input()) ls.append(ele) for i in range(0,n): prod*=ls[i] print(prod)<file_sep>def factorial(n): prod=1 while(n>0): prod=prod*n n=n-1 return prod n=int(input("Enter the number: ")) print(factorial(n))<file_sep>n=int(input("Enter the number to be inserted: ")) lst=[] n_lst=[] m=int(input("Enter the number of elements: ")) for i in range(0,m): ele=int(input()) lst.append(ele) print(lst) def inerstion(): count =0 while(count<=m): lst.insert(count,n) print(lst) count+=1 lst.remove(n) inerstion() <file_sep>n=int(input("Enter the number of prices: ")) lst=[] for i in range(0,n): ele=int(input()) lst.append(ele) lst.sort() cp=lst[0] sp=lst[n-1] profit=sp-cp print("SP ",sp,"- CP",cp," = Profit ",profit) <file_sep>n1=input("Enter 1st num: ") n2=input("Enter 2nd num: ") n3=input("Enter 3rd num: ") n2=max(n1,n2) n3=max(n3,n2) print(n3)<file_sep>def is_prime(n): for i in range (2,n): if(n%i == 0): return False return True def is_Pallindrome(n): temp=n num=0 while (n!=0): d=n%10 num=num*10+d n=n//10 if(num==temp): return True else: return False lb=int(input("Enter the lower bound: ")) ub=int(input("Enter the upper bound: ")) for i in range (lb,ub): if(is_prime(i) and is_Pallindrome(i)): print(i," ") <file_sep>def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] str=input("Enter the string: ") n_str=str if(n_str== reverse(str)): print("Is Pallindrome") else: print("Not Pallindrome")<file_sep>def check(str): n=len(str) up,low=0,0 for i in range(0,n): if(str[i].isupper()): up+=1 elif(str[i].islower()): low+=1 print(up," ", low) str=input("Enter the string: ") check(str)
e2c2f34c743f20edbf7d044816ef2e53bc26d2cf
[ "Python" ]
12
Python
Soumojitshome2023/Python-Lab-PCC-CS393-
e0f15b469a06b93a44783e3ea4cf6d31dc3eb00c
f0c5ec922c2199a9a5f54410ef00ebf928bf80ee
refs/heads/master
<repo_name>dongdongzhaoUP/sgx_db<file_sep>/App/App.cpp #include <iostream> #include <sstream> #include <fstream> #include <string> #include "sgx_urts.h" #include "sgx_utils/sgx_utils.h" #include "Enclave_u.h" #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #define SERVER_PORT 7000 #define QUEUE 20 #define MAX_PATH FILENAME_MAX #define ENCLAVE_FILENAME "enclave.signed.so" using namespace std; const char* dbname = "test.db"; sgx_enclave_id_t eid = 0; char token_path[MAX_PATH] = {'\0'}; sgx_launch_token_t token = {0}; sgx_status_t ret = SGX_ERROR_UNEXPECTED; int updated = 0; void ocall_print_error(const char *str){cerr << str << endl;} void ocall_print_string(const char *str){cout << str;} void ocall_println_string(const char *str){cout << str << endl;} //tmp.txt��ŵ�ǰSQL�����ص�������� void ocall_write_file(const char* FILE_NAME, const char* szAppendStr, size_t buf_len) { FILE *fp ; fp = fopen(FILE_NAME, "a+"); if (fp != NULL) { int ret_val = fwrite(szAppendStr,sizeof(char),buf_len, fp); if (ret_val != buf_len) {printf ("Failed to write to file - returned value: %d\n", ret_val);} int out_fclose = fclose(fp); if (out_fclose != 0) {printf ("Failed to close the file - %s\n", FILE_NAME);exit(0);} } else {printf ("Failed to open the file - %s - for writing\n", FILE_NAME);exit(0);} } //����SQL������־�����ڴ����ݿ� void ocall_init(){ FILE *fp1; fp1 = fopen("test.txt","r"); char buf[1024]; int len; //printf("\n-----init-----\n"); while(fgets(buf,1024,fp1) !=NULL) { len = strlen(buf); if(buf[len-1]=='\n') {buf[len-1]='\0';len--;} if(len!=0) { ecall_initdb(eid,buf); //printf("%s\n",buf); } } //printf("\n-----init over-----\n"); fclose(fp1); } static int callback(void *data, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main() { fd_set rfds; struct timeval tv; int retval, maxfd; ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL); if (ret != SGX_SUCCESS) { cerr << "Error: creating enclave" << endl; return -1; } cout << "Info: SQLite SGX enclave successfully created." << endl; ret = ecall_opendb(eid); if (ret != SGX_SUCCESS) { cerr << "Error: Making an ecall_open()" << endl; return -1; } ocall_init(); //���������׽���sockaddr_in�ṹ��������ֱ��ʾ�ͻ��˺ͷ����� int serverSocket; struct sockaddr_in server_addr; struct sockaddr_in clientAddr; int addr_len = sizeof(clientAddr); int client; char buffer[200],buf[200],SQLError[]="SQLite error:"; int iDataNum; if((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return 1; } bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERVER_PORT); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("connect"); return 1; } //���÷������ϵ�socketΪ����״̬ if(listen(serverSocket, 5) < 0) { perror("listen"); return 1; } client = accept(serverSocket, (struct sockaddr*)&clientAddr, (socklen_t*)&addr_len); if(client < 0){ perror("accept"); //continue; } printf("\nwaiting...\n"); //��ʼ������Ϣ while(1){ char *zErrMsg = 0; const char* data = "Callback function called"; //receive printf("\nRECV:"); char buffer[1024]; memset(buffer, 0 ,sizeof(buffer)); int len = recv(client, buffer, sizeof(buffer), 0); //cin.getline(buffer,1024); if(strcmp(buffer, "quit") == 0) break; printf("%s\n", buffer); //clear tmp FILE *fp; fp = fopen("tmp.txt","w+"); fclose(fp); //send printf("\nSEND:"); int sqlok; ecall_execute_sql(eid,&sqlok, buffer); //��tmp���ݶ���buf ifstream in("tmp.txt", ios::in); istreambuf_iterator<char> beg(in), end; string tmpbuf(beg, end); in.close(); int i; for(i =0;i<tmpbuf.length();++i){ buf[i]= tmpbuf[i]; } buf[i]='\0'; //�����ɹ���д��SQL��־ if(sqlok == 0) { fp = fopen("test.txt","a+"); if (fp != NULL) { fwrite(buffer,sizeof(char),strlen(buffer), fp); fwrite("\n\r",2,1,fp); } fclose(fp); } else{ } // ��select�����ɹ���������ֵ��ΪDONE // fp = fopen("tmp.txt","r"); // char ch = fgetc(fp); // if (ch = EOF) {char* buf1="DONE";fwrite(buf1,sizeof(char),strlen(buf1), fp);} // fclose(fp); send(client, buf, strlen(buf), 0); } close(serverSocket); ret = ecall_closedb(eid); if (ret != SGX_SUCCESS) { cerr << "Error: Making an ecall_closedb()" << endl; return -1; } ret = sgx_destroy_enclave(eid); if (ret != SGX_SUCCESS) { cerr << "Error: destroying enclave" << endl; return -1; } return 0; } <file_sep>/Enclave/Enclave.cpp #include "Enclave_t.h" #include "sqlite3.h" #include <string> sqlite3* db; char * findstr(const char * str, char * sub){ if(NULL == str || NULL == sub){return NULL;} char * p = NULL, * q = NULL, * c = NULL; int found = 0; p = const_cast<char*>(str); while(*p != '\0'){ q = sub;c = p; while(*c == *q && *q != '\0'){ q++; c++; } if('\0' == *q){ found = 1; break; } p++; } if(1 == found){ return p;} else { return NULL;} } static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i = 0; i < argc; i++){ std::string azColName_str = azColName[i]; std::string argv_str = (argv[i] ? argv[i] : "NULL"); std::string tmp = (azColName_str + " = " + argv_str + "\n"); /*--------------------添加加密操作,加密tmp---------------------------*/ ocall_print_string(tmp.c_str()); ocall_write_file ("tmp.txt",tmp.c_str(),tmp.length()); } ocall_print_string("\n"); return 0; } void ecall_initdb(const char *sql){ /*--------------------添加解密操作,解密buf---------------------------*/ //ocall_print_string(sql); //ocall_print_string("\n"); int rc; char *zErrMsg = 0; rc = sqlite3_exec(db,sql,0,0,&zErrMsg); } void ecall_opendb(){ int rc; char buff[1024]; int len; rc = sqlite3_open(":memory:", &db); if (rc) { ocall_println_string("SQLite error - can't open database connection: "); ocall_println_string(sqlite3_errmsg(db)); return; } ocall_print_string("Enclave: Created database connection to :memory:"); } int ecall_execute_sql(const char *sql){ int rc; char *r=NULL; char * str2="select"; char *zErrMsg = 0; /*--------------------添加解密操作,解密sql---------------------------*/ r = findstr(sql,str2); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); //SQL语法错误 2 /*--------------------添加加密操作,加密tmp---------------------------*/ if (rc) { std::string tmp = "SQLite error: "; tmp += sqlite3_errmsg(db); ocall_println_string(tmp.c_str()); ocall_write_file ("tmp.txt",tmp.c_str(),tmp.length()); return 2; } //select操作成功 1 (操作在回调函数里面) if(NULL != r){return 1;} //非select操作成功 0 /*--------------------添加加密操作,加密tmp---------------------------*/ else { std::string tmp = "DONE\n"; ocall_println_string(tmp.c_str()); ocall_write_file ("tmp.txt",tmp.c_str(),tmp.length()); return 0; } } void ecall_closedb(){ sqlite3_close(db); ocall_println_string("Enclave: Closed database connection"); }
3d17d5be93651ec55fd08cfa64306cf1f202c91e
[ "C++" ]
2
C++
dongdongzhaoUP/sgx_db
9c1989f80c7a5bb097a23229bb8f25dfadc9ba78
5d5f61735593fedfe6ff759909fcb87660997950
refs/heads/master
<repo_name>nimaeskandary/Daemon-Dash-UMD<file_sep>/README.md # Daemon-Dash-UMD-2015 Daemon Dash: Small hackathon at the University of Maryland. My team of me and three other students found a database online of UFO sightings and decided to represent aspects of the data in charts and graphs, and made a widget that mines the data real time after the user selects a few options <file_sep>/main.js $(document).ready(function(){ //$('#banner').css("width",$(window).width()); $('.UIDiv').mouseenter(function(){ //makes the left block expand into the user selection boxes if($(this).css('height') !== '350px'){ $(this).animate({ height: '350px' }); $('#UIone').fadeOut('fast'); //Fades out what did you see bro $('.ui-field-contain').css('display','initial'); $('.btn').css('display','initial'); //shows the button $('.label').css('display','initial'); $('#barGraph').animate({ top: '550px', }); $('#barTitle').animate({ top: '520px', }); } }); $('.UIDiv').mouseleave(function(){ //makes the left block expand into the user selection boxes if($(this).css('height') === '350px'){ $(this).animate({ height: '50px' }); $('#UIone').fadeIn('fast'); //Fades out what did you see bro $('.ui-field-contain').css('display','none'); $('.btn').css('display','none'); //shows the button $('#barGraph').animate({ top: '280px', }); $('#comment').remove(); $('#answer').remove(); $('#barTitle').animate({ top: '250px', }); } }); $('.btn').click(function(){ //responds to button click, reads in user choices for state and shape var stateIndex = document.getElementById("select-choice-1"); var selectedState = stateIndex.options[stateIndex.selectedIndex].value; var shapeIndex = document.getElementById("select-choice-2"); var selectedShape = shapeIndex.options[shapeIndex.selectedIndex].value; parseStateShapeCounter(selectedState,selectedShape); }); var mostCommonState = $("#mostStatePie").get(0).getContext("2d");//creates pie chart for the most common states //pie chart data //sum of values = 360 var mostCommonStateData = [ { value: variables.mostCommonStates[0][1], color: "cornflowerblue", highlight: "lightskyblue", label: variables.mostCommonStates[0][0] }, { value: variables.mostCommonStates[1][1], color: "lightgreen", highlight: "yellowgreen", label: variables.mostCommonStates[1][0] }, { value: variables.mostCommonStates[2][1], color: "orange", highlight: "darkorange", label: variables.mostCommonStates[2][0] }, { value: variables.mostCommonStates[3][1], color: "red", highlight: "darkred", label: variables.mostCommonStates[3][0] }, { value: variables.mostCommonStates[4][1], color: "purple", highlight: "white", label: variables.mostCommonStates[4][0] } ]; //draw var mostCommonStatePieChart = new Chart(mostCommonState).Pie(mostCommonStateData); var leastCommonState = $("#leastStatePie").get(0).getContext("2d");//creates pie chart for the most common states //pie chart data //sum of values = 360 var leastCommonStateData = [ { value: variables.leastCommonStates[0][1], color: "purple", highlight: "white", label: variables.leastCommonStates[0][0] }, { value: variables.leastCommonStates[1][1], color: "orange", highlight: "darkorange", label: variables.leastCommonStates[1][0] }, { value: variables.leastCommonStates[2][1], color: "lightgreen", highlight: "yellowgreen", label: variables.leastCommonStates[2][0] }, { value: variables.leastCommonStates[3][1], color: "red", highlight: "darkred", label: variables.leastCommonStates[3][0] }, { value: variables.leastCommonStates[4][1], color: "cornflowerblue", highlight: "lightskyblue", label: variables.leastCommonStates[4][0] } ]; //draw var leastCommonStatePieChart = new Chart(leastCommonState).Pie(leastCommonStateData); var mostCommonShape = $("#mostShapePie").get(0).getContext("2d"); //pie chart data //sum of values = 360 var mostCommonShapeData = [ { value: variables.mostCommonShapes[0][1], color: "red", highlight: "darkred", label: variables.mostCommonShapes[0][0] }, { value: variables.mostCommonShapes[1][1], color: "purple", highlight: "white", label: variables.mostCommonShapes[1][0] }, { value: variables.mostCommonShapes[2][1], color: "orange", highlight: "darkorange", label: variables.mostCommonShapes[2][0] }, { value: variables.mostCommonShapes[3][1], color: "cornflowerblue", highlight: "lightskyblue", label: variables.mostCommonShapes[3][0] }, { value: variables.mostCommonShapes[4][1], color: "lightgreen", highlight: "yellowgreen", label: variables.mostCommonShapes[4][0] } ]; //draw var mostCommonShapePieChart = new Chart(mostCommonShape).Pie(mostCommonShapeData); var leastCommonShape = $("#leastShapePie").get(0).getContext("2d"); //pie chart data //sum of values = 360 var leastCommonShapeData = [ { value: variables.leastCommonShapes[0][1], color: "cornflowerblue", highlight: "lightskyblue", label: variables.leastCommonShapes[0][0] }, { value: variables.leastCommonShapes[1][1], color: "lightgreen", highlight: "yellowgreen", label: variables.leastCommonShapes[1][0] }, { value: variables.leastCommonShapes[2][1], color: "purple", highlight: "white", label: variables.leastCommonShapes[2][0] }, { value: variables.leastCommonShapes[3][1], color: "red", highlight: "darkred", label: variables.leastCommonShapes[3][0] }, { value: variables.leastCommonShapes[4][1], color: "orange", highlight: "darkorange", label: variables.leastCommonShapes[4][0] } ]; //draw var leastCommonShapePieChart = new Chart(leastCommonShape).Pie(leastCommonShapeData); var barData = { labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], datasets: [ { label: 'Number of Sightings', fillColor: 'orange', data: [11049, 15353, 18216, 13605, 14151, 18951, 8836] } ] }; var context = document.getElementById('barGraph').getContext('2d'); var clientsChart = new Chart(context).Bar(barData); }); var variables = { //data for the most common states data: [], mostCommonStates: [['CA',11474], ['FL',5346], ['WA',5145], ['TX',4451], ['NY',4026]], leastCommonStates: [['ND',171], ['DE',248], ['SD',254], ['WY',262], ['RH',380]], mostCommonShapes: [['Light',20300], ['Circle',9993], ['Triangle',9474], ['Fireball',7776], ['Other',6919]], leastCommonShapes: [['Cross',301], ['Cone',411], ['Teardrop',915], ['Egg',925], ['Chevron',1138]], }; var parseStateShapeCounter = function(state,shape){ //parses and interprets data, returns the answer to user input Papa.parse('Data/UFO_data.csv', { download: true, dynamicTyping: true, complete: function(results) { // variables.data = results.data; var tempData = stateShapeCounter(state,shape); var stateIndex = document.getElementById("select-choice-1"); var selectedState = stateIndex.options[stateIndex.selectedIndex].value; var shapeIndex = document.getElementById("select-choice-2"); var selectedShape = shapeIndex.options[shapeIndex.selectedIndex].value; $("#answer").remove(); $("#comment").remove(); if(shapeIndex !== "Unknown") { $(".UIDiv").append("<p id='answer'>A "+ selectedShape.toLowerCase() +" shaped UFO was seen " + tempData[0] +" </br>time(s) out of " + tempData[1] + " sightings.</p>"); $(".UIDiv").append("<p id='comment'>" + commentGenerator(tempData[0]/tempData[1]) + "</p>"); } else { } console.log("Amount of times shape seen: " + tempData[0] + "\nTotal amount of reports: " + tempData[1]); } }); } var stateShapeCounter = function(state,shape){//counts how many times a certain shape occurs per state var counter = 0; var stateColumn; for(var c = 0;c<variables.data[1].length;c++){ if(variables.data[1][c] === state) stateColumn = c+1; } for(var y = 0;y<variables.data.length;y++){ if(variables.data[y][stateColumn] === shape) counter++; } return [counter,getTotalSightingsByState(stateColumn)]; } var getTotalSightingsByState = function(stateColumn){//gets the total amount of ufo sightings var counter = 0; for(var y = 0;y<variables.data.length;y++){ if(variables.data[y][stateColumn] !== '') counter++; } return counter; } var commentGenerator = function(x){ //generates comments that return based on probability the user saw a UFO if(x<.04) return "What you saw was just the moon"; else if(x<.06) return "That shape in the sky, <br>might've just been a blimp"; else if(x<.08) return "You saw a UFO, get your tin foil hat!"; else if(x<.10) return "Call NBC, the world needs to know what you saw."; else if(x<.12) return "Hmm that's a tough call, I'm not sure what that was"; else return "Well, you didn't see a UFO but at <br>least you're not crazy"; }
1d4aaf04a8da0d5573c643117657dd6befe395ab
[ "Markdown", "JavaScript" ]
2
Markdown
nimaeskandary/Daemon-Dash-UMD
5acdcac29dff3de486de901f7157ea65ca5e2c69
737871138fad7696c7a9e313f82900c48a486ddc
refs/heads/master
<file_sep>// $(document).ready(function() { // $("#first-name").keypress(function(){ // var firstname = $('#first-name').val(); // var nameregex = /^[a-zA-Z]{2,30}$/; // if(!nameregex.test(firstname)){ // $('#fn-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#fn-error').addClass('hide'); // } // }); // $("#last-name").keypress(function(){ // var lastname = $('#last-name').val(); // var nameregex = /^[a-zA-Z]{2,30}$/; // if(!nameregex.test(lastname)){ // $('#ln-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#ln-error').addClass('hide'); // } // }); // $("#title-display").keypress(function(){ // var titlename = $('#title-display').val(); // var nameregex = /^[a-zA-Z]{2,30}$/; // if(!nameregex.test(titlename)){ // $('#title-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#title-error').addClass('hide'); // } // }); // $("#company-details").keypress(function(){ // var companyname = $('#company-details').val(); // var nameregex = /^[a-zA-Z]{2,30}$/; // if(!nameregex.test(companyname)){ // $('#company-error').removeClass('hide'); $('#fn').css('border-color','red'); // } // else{ // $('#company-error').addClass('hide'); // } // }); // $("#phone-number").keyup(function(){ // var number = $('#phone-number').val(); // var regex = /^[0-9]{3}[-][0-9]{3}[-][0-9]{4}/; // if(!regex.test(number)){ // $('#number-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#number-error').addClass('hide'); // } // }); // $('#email-check').on('input', function() { // var input=$('#email-check').val(); // var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; // if(!re.test(input)){ // $('#email-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#email-error').addClass('hide'); // } // }); // $("#industry-name").keypress(function(){ // var name = $('#industry-name').val(); // var nameregex = /^[a-zA-Z]{2,30}$/; // if(!nameregex.test(name)){ // $('#industry-error').removeClass('hide');/* $('#fn').css('border-color','red');*/ // } // else{ // $('#industry-error').addClass('hide'); // } // }); // $("#submit").click(function(){ // alert("please fill all the fields."); // }); // }); $(function() { $("form[name='registration']").validate({ rules: { firstname: "required", lastname: "required", title: "required", company: "required", city: "required", industry: "required", email: { required: true, email: true }, phone: { required: true, minlength: 10 } }, messages: { firstname: "Please enter your firstname", lastname: "Please enter your lastname", title: "please enter your work title", company: "please enter your company name", city: "please enter your city", industry: "please enter your working desgination", phone: { required: "Please provide a phone number", minlength: "Your phone number must be of 10 digit" }, email: "Please enter a valid email address" }, submitHandler: function(form) { form.submit(); } }); });
96d021325cbdca5472b61e6b58bec000c9b45aed
[ "JavaScript" ]
1
JavaScript
chytramn59/konnexe-res
9263047a991a7c49c2a70fc921a6f709655ac8fe
65110abfe33ac372144a29de5361365e95f53910
refs/heads/master
<file_sep>const express = require('express'), path = require('path'), mongoose = require('mongoose'); // Realiza la conexion a la base de datos mongoose.connect('mongodb://localhost/NombreDeLaBaseDeDatos', { useNewUrlParser: true }); const db = mongoose.connection; db.once('open', ()=>{ console.log('Conectado a MongoDB'); }); db.on('error', (err)=>{ console.log(err); }); // Inicializa Express const app = express(); // Configura el motor de las vistas app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); // Establece la carpeta public app.use(express.static(path.join(__dirname, 'public'))); // Home Route app.get('/', (req, res)=>{ res.render('index'); }); // Inicializa el servidor en el puerto 3000 app.listen(3000, ()=>{ console.log('Inicalizado el servidor en el puerto 3000') })
f1d6d88cd95eb4dc97f986bdb00bf302ca073332
[ "JavaScript" ]
1
JavaScript
kroyxlab/express-boilerplate
80af38465aa112c659c1ad0c6148545b2be29df9
e182352227127742803dfafcfe7c67ecddad4f88
refs/heads/master
<repo_name>ivnat97/test<file_sep>/src/lab/MethodOverride.java package lab; class Figure{ Figure(){} double area(){ System.out.print("Площадь фигуры не определена: "); return 0; } } class Circle extends Figure{ double radius; final double PI = 3.14; Circle(){ radius = 1; } Circle(double radius){ this.radius = radius; } @Override double area(){ System.out.print("Площадь круга: "); return PI*radius*radius; } } class Square extends Figure{ double a; Square(){ a = 1; } Square(double a){ this.a = a; } @Override double area(){ System.out.print("Площадь квадрата: "); return a*a; } } class Triangle extends Figure{ double h,c; Triangle(){ h = 2; c = 1; } Triangle(double h, double c){ this.h = h; this.c = c; } @Override double area(){ System.out.print("Площадь треугольника: "); return 0.5*h*c; } } public class MethodOverride { public static void main(String[] args) { Figure f = new Figure(); Circle c = new Circle(5); Square s = new Square(3); Triangle t = new Triangle(8,6); System.out.println(f.area()); System.out.println(c.area()); System.out.println(s.area()); System.out.println(t.area()); } }<file_sep>/src/lab/StaticMethods.java package lab; class Calc{ static int plus(int a, int b){ System.out.print(a + " + " + b + " = "); return a+b; } static int minus(int a, int b){ System.out.print(a + " - " + b + " = "); return a-b; } static int mult(int a, int b){ System.out.print(a + " * " + b + " = "); return a*b; } static double devide(int a, int b){ System.out.print(a + " / " + b + " = "); if (b!=0) return a/b; else return 0; } } public class StaticMethods { public static void main(String[] args){ System.out.println(Calc.plus(4, 8)); System.out.println(Calc.minus(30, 4)); System.out.println(Calc.mult(7, 10)); System.out.println(Calc.devide(24, 8)); } } <file_sep>/src/lab/FinalType.java package lab; class Box{ double width; double lehgth; final double height=5.13; final void meth(){ System.out.println("This is box"); } } class WeightBox extends Box{ } final class Base{ } public class FinalType { public static void main(String[] args) { final int mas[] = {1,2,3}; mas[2]=4; int mas1[]={2,3}; mas=mas1; } }
4fdc9eef6f80f28df37839029efd9bdc56cd66f5
[ "Java" ]
3
Java
ivnat97/test
95794db9faa35cd14aa4ddb002c951ccfe8ff19c
861ee4d1b401dea57f8223620bc7b0be569130ed
refs/heads/master
<file_sep> # coding: utf-8 # # Multichain-simpleUI # # import tkinter for python GUI # import os for system file location # In[49]: from tkinter import * import os # # Working # # 1. locate file in system(here the files are in the same directory as the python file) # 2. create a simple UI with three buttons # 3. button1 ==> creates a new chain named "chain1" through a .bat file(code : multichain-ulti) # 4. button2 ==> launches the newly created chain1 through a .bat file(code : multichaind chain1 -daemon) # 5. button3 ==> exits the chain through a .bat file(code : /cmd c exit) # In[65]: class application(Frame): def openFileCreate(self): # change file location as per reqirement os.system(r'""C:\\Users\\zero\\Desktop\\int\\create-chain.bat""') def openFileLaunch(self): os.system(r'""C:\\Users\\zero\\Desktop\\int\\launch-chain.bat""') def openFileExit(self): os.system(r'""C:\\Users\\zero\\Desktop\\int\\exit-chain.bat""') def __init__(self,master): Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): #create chain self.create_button = Button(self,command = self.openFileCreate,text="create chain") self.create_button.grid(row = 0,column = 1,columnspan = 1,sticky = W) #launch chain self.launch_button = Button(self,command = self.openFileLaunch,text="launch chain") self.launch_button.grid(row = 2,column = 2,columnspan = 2,sticky = W) #exit chain self.exit_button = Button(self,command = self.openFileExit,text="exit chain") self.exit_button.grid(row = 3,column = 2,columnspan = 2, sticky = W) root = Tk() root.title("Multichain-Launcher") root.geometry("200x100") app = application(root) root.mainloop() # In[ ]: <file_sep># multiChain Projects in multiChain
8338deaf9b59d4f0326a53b04f26c61fcf629712
[ "Markdown", "Python" ]
2
Python
sanket-k/multiChain
60d82f27876aed056326a060d6cc5cf0723cc834
dfdf3c64c1872bd1d1a00806a8ed85d78d8fe09d
refs/heads/master
<repo_name>NitinLondey/Spring-Boot-Challenge<file_sep>/src/main/java/com/mindex/challenge/service/CompensationService.java package com.mindex.challenge.service; import com.mindex.challenge.data.CompensationBean; import com.mindex.challenge.data.CreateCompensationResponseBean; public interface CompensationService { /** * Create a compensation for given Employee * @param compensation * @return CreateCompensationResponseBean */ CreateCompensationResponseBean createCompensation(CompensationBean compensation); /** * Retrieve Compensation details for given Employee(Id) * @param Id * @return CompensationBean */ CompensationBean retrieveCompensation(String Id); } <file_sep>/src/main/java/com/mindex/challenge/data/CreateCompensationResponseBean.java package com.mindex.challenge.data; public class CreateCompensationResponseBean { private CompensationBean compensation; private boolean compensationCreated; private String message; public CompensationBean getCompensation() { return compensation; } public void setCompensation(CompensationBean compensation) { this.compensation = compensation; } public boolean isCompensationCreated() { return compensationCreated; } public void setCompensationCreated(boolean compensationCreated) { this.compensationCreated = compensationCreated; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <file_sep>/src/main/java/com/mindex/challenge/controller/CompensationController.java package com.mindex.challenge.controller; import com.mindex.challenge.data.CompensationBean; import com.mindex.challenge.data.CreateCompensationResponseBean; import com.mindex.challenge.service.CompensationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class CompensationController { private static final Logger LOG = LoggerFactory.getLogger(CompensationController.class); @Autowired private CompensationService compensationService; @PostMapping("/compensation") public CreateCompensationResponseBean create(@RequestBody CompensationBean compensation) { LOG.debug("Create Compensation [{}]",compensation); return compensationService.createCompensation(compensation); } @GetMapping("/compensation/employee/{id}") public CompensationBean read(@PathVariable String id) { LOG.debug("Get Compensation for id [{}]",id); return compensationService.retrieveCompensation(id); } } <file_sep>/src/main/java/com/mindex/challenge/service/impl/CompensationServiceImpl.java package com.mindex.challenge.service.impl; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mindex.challenge.dao.CompensationRepository; import com.mindex.challenge.data.CompensationBean; import com.mindex.challenge.data.CreateCompensationResponseBean; import com.mindex.challenge.service.CompensationService; @Service public class CompensationServiceImpl implements CompensationService { @Autowired private CompensationRepository compensationRepository; @Override public CreateCompensationResponseBean createCompensation(CompensationBean compensation) { CreateCompensationResponseBean response = new CreateCompensationResponseBean(); // Setting Id to Compensation entity compensation.setCompensationId(UUID.randomUUID().toString()); if (null != compensation && null != compensation.getEmployee() && null != compensation.getEmployee().getEmployeeId()) { /* * Checking if Compensation to be inserted is present in database or not. If * yes, if won't be inserted; and update operation shall be handled by Update * API If no, it will be inserted */ CompensationBean employeeFromDB = compensationRepository .findByEmployeeEmployeeId(compensation.getEmployee().getEmployeeId()); if (null == employeeFromDB) { response.setCompensation(compensationRepository.insert(compensation)); response.setCompensationCreated(true); response.setMessage("Compensation saved successfully."); } else { response.setCompensationCreated(false); response.setMessage("Compensation already present in Database."); } } return response; } @Override public CompensationBean retrieveCompensation(String id) { CompensationBean findByEmployeeEmployeeId = compensationRepository.findByEmployeeEmployeeId(id); return findByEmployeeEmployeeId; } } <file_sep>/src/test/java/com/mindex/challenge/service/impl/EmployeeServiceImplTest.java package com.mindex.challenge.service.impl; import com.mindex.challenge.data.Employee; import com.mindex.challenge.data.ReportingStructureBean; import com.mindex.challenge.service.EmployeeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class EmployeeServiceImplTest { private String employeeUrl; private String employeeIdUrl; private String reportingUrl; @Autowired private EmployeeService employeeService; @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Before public void setup() { employeeUrl = "http://localhost:" + port + "/employee"; employeeIdUrl = "http://localhost:" + port + "/employee/{id}"; reportingUrl= "http://localhost:" + port + "/reportingStructure/{id}"; } @Test public void testCreateReadUpdate() { Employee testEmployee = new Employee(); testEmployee.setFirstName("John"); testEmployee.setLastName("Doe"); testEmployee.setDepartment("Engineering"); testEmployee.setPosition("Developer"); // Create checks Employee createdEmployee = restTemplate.postForEntity(employeeUrl, testEmployee, Employee.class).getBody(); assertNotNull(createdEmployee.getEmployeeId()); assertEmployeeEquivalence(testEmployee, createdEmployee); // Read checks Employee readEmployee = restTemplate.getForEntity(employeeIdUrl, Employee.class, createdEmployee.getEmployeeId()).getBody(); assertEquals(createdEmployee.getEmployeeId(), readEmployee.getEmployeeId()); assertEmployeeEquivalence(createdEmployee, readEmployee); // Update checks readEmployee.setPosition("Development Manager"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Employee updatedEmployee = restTemplate.exchange(employeeIdUrl, HttpMethod.PUT, new HttpEntity<Employee>(readEmployee, headers), Employee.class, readEmployee.getEmployeeId()).getBody(); assertEmployeeEquivalence(readEmployee, updatedEmployee); } private static void assertEmployeeEquivalence(Employee expected, Employee actual) { assertEquals(expected.getFirstName(), actual.getFirstName()); assertEquals(expected.getLastName(), actual.getLastName()); assertEquals(expected.getDepartment(), actual.getDepartment()); assertEquals(expected.getPosition(), actual.getPosition()); } @Test public void readReportingStructureSuccess() { ReportingStructureBean testReportingStrucutreBean = getReportingData(); ReportingStructureBean response = restTemplate.getForEntity(reportingUrl, ReportingStructureBean.class, "03aa1462-ffa9-4978-901b-7c001562cf6f").getBody(); assertEquals(testReportingStrucutreBean.getnumberOfReports(),response.getnumberOfReports()); assertNotNull(response); } @Test public void testReportingForEmployeeIdNotPresent() { ReportingStructureBean testReportingStrucutreBean = getReportingData(); testReportingStrucutreBean.getEmployee().setEmployeeId(null);; ReportingStructureBean response = restTemplate.getForEntity(reportingUrl, ReportingStructureBean.class, testReportingStrucutreBean.getEmployee().getEmployeeId()).getBody(); assertNull(response.getEmployee()); } private ReportingStructureBean getReportingData() { Employee testEmployee = new Employee(); testEmployee.setEmployeeId("62c1084e-6e34-4630-93fd-9153afb65309"); testEmployee.setFirstName("Pete"); testEmployee.setLastName( "Best"); testEmployee.setDepartment( "Developer II"); testEmployee.setPosition( "Engineering"); testEmployee.setDirectReports(new ArrayList<Employee>()); Employee testEmployee1 = new Employee(); testEmployee1.setEmployeeId("c0c2293d-16bd-4603-8e08-638a9d18b22c"); testEmployee1.setFirstName("George"); testEmployee1.setLastName("Harrison"); testEmployee1.setDepartment("Engineering"); testEmployee1.setPosition("Developer III"); testEmployee1.setDirectReports(new ArrayList<Employee>()); Employee testEmployee2 = new Employee(); testEmployee2.setEmployeeId("03aa1462-ffa9-4978-901b-7c001562cf6f"); testEmployee2.setFirstName("Ringo"); testEmployee2.setLastName("Starr"); testEmployee2.setDepartment("Developer V"); testEmployee2.setPosition( "Engineering"); List<Employee> list=new ArrayList<Employee>(); list.add(testEmployee); list.add(testEmployee1); testEmployee1.setDirectReports(list); ReportingStructureBean response = new ReportingStructureBean(); response.setEmployee(testEmployee2); response.setNumberOfReports(2);; return response; } }
1e532f48a85d3e90e2df8385aa9fd4d8a70bb565
[ "Java" ]
5
Java
NitinLondey/Spring-Boot-Challenge
afb7661bc7edfd3173238e4f735a6366954bea77
5a4d426d0fc0b5ec8ed429db7ed7c4b142f26e49
refs/heads/main
<file_sep>var nombre = "" + valDepart; for (let i=valDepart+1; i<=valFin; i++) { nombre = nombre + "-" + i; }
23391d1ed3297365a64d7f67e947a29b4e6bb89a
[ "JavaScript" ]
1
JavaScript
jordanbelanger/jordanbelanger.github.io
70d97895af236c18390f0edf9ec4b12fa8135497
7530e03f4f65572259bbbec614d185379f3f9014
refs/heads/master
<repo_name>zzork/playwright<file_sep>/test-runner/src/runner.ts /** * Copyright Microsoft Corporation. All rights reserved. * * 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. */ import child_process from 'child_process'; import crypto from 'crypto'; import path from 'path'; import { EventEmitter } from 'events'; import { lookupRegistrations, FixturePool } from './fixtures'; import { Suite, Test, TestResult } from './test'; import { TestRunnerEntry } from './testRunner'; import { RunnerConfig } from './runnerConfig'; import { Reporter } from './reporter'; export class Runner { private _workers = new Set<Worker>(); private _freeWorkers: Worker[] = []; private _workerClaimers: (() => void)[] = []; private _testById = new Map<string, { test: Test, result: TestResult }>(); private _queue: TestRunnerEntry[] = []; private _stopCallback: () => void; readonly _config: RunnerConfig; private _suite: Suite; private _reporter: Reporter; constructor(suite: Suite, config: RunnerConfig, reporter: Reporter) { this._config = config; this._reporter = reporter; this._suite = suite; for (const suite of this._suite.suites) { suite.findTest(test => { this._testById.set(test._id, { test, result: test._appendResult() }); }); } if (process.stdout.isTTY) { const total = suite.total(); console.log(); const jobs = Math.min(config.jobs, suite.suites.length); console.log(`Running ${total} test${total > 1 ? 's' : ''} using ${jobs} worker${jobs > 1 ? 's' : ''}`); } } _filesSortedByWorkerHash(): TestRunnerEntry[] { const result: TestRunnerEntry[] = []; for (const suite of this._suite.suites) { const ids: string[] = []; suite.findTest(test => ids.push(test._id) && false); if (!ids.length) continue; result.push({ ids, file: suite.file, configuration: suite.configuration, configurationString: suite._configurationString, hash: suite._configurationString + '@' + computeWorkerHash(suite.file) }); } result.sort((a, b) => a.hash < b.hash ? -1 : (a.hash === b.hash ? 0 : 1)); return result; } async run() { this._reporter.onBegin(this._config, this._suite); this._queue = this._filesSortedByWorkerHash(); // Loop in case job schedules more jobs while (this._queue.length) await this._dispatchQueue(); this._reporter.onEnd(); } async _dispatchQueue() { const jobs = []; while (this._queue.length) { const entry = this._queue.shift(); const requiredHash = entry.hash; let worker = await this._obtainWorker(); while (worker.hash && worker.hash !== requiredHash) { this._restartWorker(worker); worker = await this._obtainWorker(); } jobs.push(this._runJob(worker, entry)); } await Promise.all(jobs); } async _runJob(worker: Worker, entry: TestRunnerEntry) { worker.run(entry); let doneCallback; const result = new Promise(f => doneCallback = f); worker.once('done', params => { // We won't file remaining if: // - there are no remaining // - we are here not because something failed // - no unrecoverable worker error if (!params.remaining.length && !params.failedTestId && !params.fatalError) { this._workerAvailable(worker); doneCallback(); return; } // When worker encounters error, we will restart it. this._restartWorker(worker); // In case of fatal error, we are done with the entry. if (params.fatalError) { // Report all the tests are failing with this error. for (const id of entry.ids) { const { test, result } = this._testById.get(id); this._reporter.onTestBegin(test); result.status = 'failed'; result.error = params.fatalError; this._reporter.onTestEnd(test, result); } doneCallback(); return; } const remaining = params.remaining; // Only retry expected failures, not passes and only if the test failed. if (this._config.retries && params.failedTestId) { const pair = this._testById.get(params.failedTestId); if (pair.result.expectedStatus === 'passed' && pair.test.results.length < this._config.retries + 1) { pair.result = pair.test._appendResult(); remaining.unshift(pair.test._id); } } if (remaining.length) this._queue.unshift({ ...entry, ids: remaining }); // This job is over, we just scheduled another one. doneCallback(); }); return result; } async _obtainWorker() { // If there is worker, use it. if (this._freeWorkers.length) return this._freeWorkers.pop(); // If we can create worker, create it. if (this._workers.size < this._config.jobs) this._createWorker(); // Wait for the next available worker. await new Promise(f => this._workerClaimers.push(f)); return this._freeWorkers.pop(); } async _workerAvailable(worker) { this._freeWorkers.push(worker); if (this._workerClaimers.length) { const callback = this._workerClaimers.shift(); callback(); } } _createWorker() { const worker = this._config.debug ? new InProcessWorker(this) : new OopWorker(this); worker.on('testBegin', params => { const { test } = this._testById.get(params.id); test._skipped = params.skipped; test._flaky = params.flaky; test._expectedStatus = params.expectedStatus; this._reporter.onTestBegin(test); }); worker.on('testEnd', params => { const workerResult: TestResult = params.result; // We were accumulating these below. delete workerResult.stdout; delete workerResult.stderr; const { test, result } = this._testById.get(params.id); Object.assign(result, workerResult); this._reporter.onTestEnd(test, result); }); worker.on('testStdOut', params => { const chunk = chunkFromParams(params); const { test, result } = this._testById.get(params.id); result.stdout.push(chunk); this._reporter.onTestStdOut(test, chunk); }); worker.on('testStdErr', params => { const chunk = chunkFromParams(params); const { test, result } = this._testById.get(params.id); result.stderr.push(chunk); this._reporter.onTestStdErr(test, chunk); }); worker.on('exit', () => { this._workers.delete(worker); if (this._stopCallback && !this._workers.size) this._stopCallback(); }); this._workers.add(worker); worker.init().then(() => this._workerAvailable(worker)); } async _restartWorker(worker) { await worker.stop(); this._createWorker(); } async stop() { const result = new Promise(f => this._stopCallback = f); for (const worker of this._workers) worker.stop(); await result; } } let lastWorkerId = 0; class Worker extends EventEmitter { runner: Runner; hash: string; constructor(runner) { super(); this.runner = runner; } run(entry: TestRunnerEntry) { } stop() { } } class OopWorker extends Worker { process: child_process.ChildProcess; stdout: any[]; stderr: any[]; constructor(runner: Runner) { super(runner); this.process = child_process.fork(path.join(__dirname, 'worker.js'), { detached: false, env: { FORCE_COLOR: process.stdout.isTTY ? '1' : '0', DEBUG_COLORS: process.stdout.isTTY ? '1' : '0', ...process.env }, // Can't pipe since piping slows down termination for some reason. stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }); this.process.on('exit', () => this.emit('exit')); this.process.on('error', e => {}); // do not yell at a send to dead process. this.process.on('message', message => { const { method, params } = message; this.emit(method, params); }); } async init() { this.process.send({ method: 'init', params: { workerId: lastWorkerId++, ...this.runner._config } }); await new Promise(f => this.process.once('message', f)); // Ready ack } run(entry: TestRunnerEntry) { this.hash = entry.hash; this.process.send({ method: 'run', params: { entry, config: this.runner._config } }); } stop() { this.process.send({ method: 'stop' }); } } class InProcessWorker extends Worker { fixturePool: FixturePool; constructor(runner: Runner) { super(runner); this.fixturePool = require('./testRunner').fixturePool as FixturePool; } async init() { const { initializeImageMatcher } = require('./expect'); initializeImageMatcher(this.runner._config); } async run(entry: TestRunnerEntry) { delete require.cache[entry.file]; const { TestRunner } = require('./testRunner'); const testRunner = new TestRunner(entry, this.runner._config, 0); for (const event of ['testBegin', 'testStdOut', 'testStdErr', 'testEnd', 'done']) testRunner.on(event, this.emit.bind(this, event)); testRunner.run(); } async stop() { await this.fixturePool.teardownScope('worker'); this.emit('exit'); } } function chunkFromParams(params: { testId: string, buffer?: string, text?: string }): string | Buffer { if (typeof params.text === 'string') return params.text; return Buffer.from(params.buffer, 'base64'); } function computeWorkerHash(file: string) { // At this point, registrationsByFile contains all the files with worker fixture registrations. // For every test, build the require closure and map each file to fixtures declared in it. // This collection of fixtures is the fingerprint of the worker setup, a "worker hash". // Tests with the matching "worker hash" will reuse the same worker. const hash = crypto.createHash('sha1'); for (const registration of lookupRegistrations(file, 'worker').values()) hash.update(registration.location); return hash.digest('hex'); } <file_sep>/test-runner/src/builtin.fixtures.ts /** * Copyright Microsoft Corporation. All rights reserved. * * 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. */ import os from 'os'; import path from 'path'; import { promisify } from 'util'; import fs from 'fs'; import rimraf from 'rimraf'; import { registerFixture } from './fixtures'; declare global { type DescribeFunction = ((name: string, inner: () => void) => void) & { fail(condition: boolean): DescribeFunction; skip(condition: boolean): DescribeFunction; slow(): DescribeFunction; repeat(n: number): DescribeFunction; }; type ItFunction<STATE> = ((name: string, inner: (state: STATE) => Promise<void> | void) => void) & { fail(condition: boolean): ItFunction<STATE>; fixme(condition: boolean): ItFunction<STATE>; flaky(condition: boolean): ItFunction<STATE>; skip(condition: boolean): ItFunction<STATE>; slow(): ItFunction<STATE>; repeat(n: number): ItFunction<STATE>; }; const describe: DescribeFunction; const fdescribe: DescribeFunction; const xdescribe: DescribeFunction; const it: ItFunction<TestState & WorkerState & FixtureParameters>; const fit: ItFunction<TestState & WorkerState & FixtureParameters>; const dit: ItFunction<TestState & WorkerState & FixtureParameters>; const xit: ItFunction<TestState & WorkerState & FixtureParameters>; const beforeEach: (inner: (state: TestState & WorkerState & FixtureParameters) => Promise<void>) => void; const afterEach: (inner: (state: TestState & WorkerState & FixtureParameters) => Promise<void>) => void; const beforeAll: (inner: (state: WorkerState & FixtureParameters) => Promise<void>) => void; const afterAll: (inner: (state: WorkerState & FixtureParameters) => Promise<void>) => void; } const mkdtempAsync = promisify(fs.mkdtemp); const removeFolderAsync = promisify(rimraf); declare global { interface FixtureParameters { parallelIndex: number; } interface TestState { tmpDir: string; } } export {parameters, registerFixture, registerWorkerFixture, registerParameter} from './fixtures'; registerFixture('tmpDir', async ({}, test) => { const tmpDir = await mkdtempAsync(path.join(os.tmpdir(), 'playwright-test-')); await test(tmpDir); await removeFolderAsync(tmpDir).catch(e => {}); }); <file_sep>/test-runner/src/test.ts /** * Copyright Microsoft Corporation. All rights reserved. * * 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. */ export type Configuration = { name: string, value: string }[]; type TestStatus = 'passed' | 'failed' | 'timedOut' | 'skipped'; export class Test { suite: Suite; title: string; file: string; only = false; slow = false; timeout = 0; fn: Function; results: TestResult[] = []; _id: string; // Skipped & flaky are resolved based on options in worker only // We will compute them there and send to the runner (front-end) _skipped = false; _flaky = false; _overriddenFn: Function; _startTime: number; _expectedStatus: TestStatus = 'passed'; constructor(title: string, fn: Function) { this.title = title; this.fn = fn; } titlePath(): string[] { return [...this.suite.titlePath(), this.title]; } fullTitle(): string { return this.titlePath().join(' '); } _appendResult(): TestResult { const result: TestResult = { duration: 0, expectedStatus: 'passed', stdout: [], stderr: [], data: {} }; this.results.push(result); return result; } _ok(): boolean { if (this._skipped || this.suite._isSkipped()) return true; const hasFailedResults = !!this.results.find(r => r.status !== r.expectedStatus); if (!hasFailedResults) return true; if (!this._flaky) return false; const hasPassedResults = !!this.results.find(r => r.status === r.expectedStatus); return hasPassedResults; } _hasResultWithStatus(status: TestStatus): boolean { return !!this.results.find(r => r.status === status); } _clone(): Test { const test = new Test(this.title, this.fn); test.suite = this.suite; test.only = this.only; test.file = this.file; test.timeout = this.timeout; test._flaky = this._flaky; test._overriddenFn = this._overriddenFn; return test; } } export type TestResult = { duration: number; status?: TestStatus; expectedStatus: TestStatus; error?: any; stdout: (string | Buffer)[]; stderr: (string | Buffer)[]; data: any; } export class Suite { title: string; parent?: Suite; suites: Suite[] = []; tests: Test[] = []; only = false; file: string; configuration: Configuration; // Skipped & flaky are resolved based on options in worker only // We will compute them there and send to the runner (front-end) _skipped = false; _configurationString: string; _hooks: { type: string, fn: Function } [] = []; _entries: (Suite | Test)[] = []; constructor(title: string, parent?: Suite) { this.title = title; this.parent = parent; } titlePath(): string[] { if (!this.parent) return []; return [...this.parent.titlePath(), this.title]; } total(): number { let count = 0; this.findTest(fn => { ++count; }); return count; } _isSkipped(): boolean { return this._skipped || (this.parent && this.parent._isSkipped()); } _addTest(test: Test) { test.suite = this; this.tests.push(test); this._entries.push(test); } _addSuite(suite: Suite) { suite.parent = this; this.suites.push(suite); this._entries.push(suite); } eachSuite(fn: (suite: Suite) => boolean | void): boolean { for (const suite of this.suites) { if (suite.eachSuite(fn)) return true; } return false; } findTest(fn: (test: Test) => boolean | void): boolean { for (const suite of this.suites) { if (suite.findTest(fn)) return true; } for (const test of this.tests) { if (fn(test)) return true; } return false; } _clone(): Suite { const suite = new Suite(this.title); suite.only = this.only; suite.file = this.file; suite._skipped = this._skipped; return suite; } _renumber() { let ordinal = 0; this.findTest((test: Test) => { // All tests are identified with their ordinals. test._id = `${ordinal++}@${this.file}::[${this._configurationString}]`; }); } _addHook(type: string, fn: any) { this._hooks.push({ type, fn }); } _hasTestsToRun(): boolean { let found = false; this.findTest(test => { if (!test._skipped) { found = true; return true; } }); return found; } } export function serializeConfiguration(configuration: Configuration): string { const tokens = []; for (const { name, value } of configuration) tokens.push(`${name}=${value}`); return tokens.join(', '); } export function serializeError(error: Error | any): any { if (error instanceof Error) { return { message: error.message, stack: error.stack }; } return trimCycles(error); } function trimCycles(obj: any): any { const cache = new Set(); return JSON.parse( JSON.stringify(obj, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.has(value)) return '' + value; cache.add(value); } return value; }) ); } <file_sep>/test-runner/src/testCollector.ts /** * Copyright Microsoft Corporation. All rights reserved. * * 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. */ import path from 'path'; import { fixturesForCallback } from './fixtures'; import { Test, Suite, serializeConfiguration } from './test'; import { spec } from './spec'; import { RunnerConfig } from './runnerConfig'; export type Matrix = { [key: string]: string[] }; export class TestCollector { suite: Suite; private _matrix: Matrix; private _config: RunnerConfig; private _grep: RegExp; private _hasOnly: boolean; constructor(files: string[], matrix: Matrix, config: RunnerConfig) { this._matrix = matrix; this._config = config; this.suite = new Suite(''); if (config.grep) { const match = config.grep.match(/^\/(.*)\/(g|i|)$|.*/); this._grep = new RegExp(match[1] || match[0], match[2]); } for (const file of files) this._addFile(file); this._hasOnly = this._filterOnly(this.suite); } hasOnly() { return this._hasOnly; } private _addFile(file: string) { const suite = new Suite(''); const revertBabelRequire = spec(suite, file, this._config.timeout); require(file); revertBabelRequire(); const workerGeneratorConfigurations = new Map(); suite.findTest((test: Test) => { // Get all the fixtures that the test needs. const fixtures = fixturesForCallback(test.fn); // For generator fixtures, collect all variants of the fixture values // to build different workers for them. const generatorConfigurations = []; for (const name of fixtures) { const values = this._matrix[name]; if (!values) continue; const state = generatorConfigurations.length ? generatorConfigurations.slice() : [[]]; generatorConfigurations.length = 0; for (const gen of state) { for (const value of values) generatorConfigurations.push([...gen, { name, value }]); } } // No generator fixtures for test, include empty set. if (!generatorConfigurations.length) generatorConfigurations.push([]); for (const configuration of generatorConfigurations) { // Serialize configuration as readable string, we will use it as a hash. const configurationString = serializeConfiguration(configuration); // Allocate worker for this configuration, add test into it. if (!workerGeneratorConfigurations.has(configurationString)) workerGeneratorConfigurations.set(configurationString, { configuration, configurationString, tests: new Set() }); workerGeneratorConfigurations.get(configurationString).tests.add(test); } }); // Clone the suite as many times as we have repeat each. for (let i = 0; i < this._config.repeatEach; ++i) { // Clone the suite as many times as there are worker hashes. // Only include the tests that requested these generations. for (const [hash, {configuration, configurationString, tests}] of workerGeneratorConfigurations.entries()) { const clone = this._cloneSuite(suite, tests); this.suite._addSuite(clone); clone.title = path.basename(file) + (hash.length ? `::[${hash}]` : '') + ' ' + (i ? ` #repeat-${i}#` : ''); clone.configuration = configuration; clone._configurationString = configurationString + `#repeat-${i}#`; clone._renumber(); } } } private _cloneSuite(suite: Suite, tests: Set<Test>) { const copy = suite._clone(); copy.only = suite.only; for (const entry of suite._entries) { if (entry instanceof Suite) { copy._addSuite(this._cloneSuite(entry, tests)); } else { const test = entry; if (!tests.has(test)) continue; if (this._grep && !this._grep.test(test.fullTitle())) continue; const testCopy = test._clone(); testCopy.only = test.only; copy._addTest(testCopy); } } return copy; } private _filterOnly(suite) { const onlySuites = suite.suites.filter(child => this._filterOnly(child) || child.only); const onlyTests = suite.tests.filter(test => test.only); if (onlySuites.length || onlyTests.length) { suite.suites = onlySuites; suite.tests = onlyTests; return true; } return false; } } <file_sep>/test-runner/test/exit-code.spec.ts /** * Copyright (c) Microsoft Corporation. * * 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. */ import colors from 'colors/safe'; import { spawnSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import rimraf from 'rimraf'; import { promisify } from 'util'; import '../lib'; const removeFolderAsync = promisify(rimraf); it('should fail', async () => { const result = await runTest('one-failure.js'); expect(result.exitCode).toBe(1); expect(result.passed).toBe(0); expect(result.failed).toBe(1); }); it('should timeout', async () => { const { exitCode, passed, failed, timedOut } = await runTest('one-timeout.js', { timeout: 100 }); expect(exitCode).toBe(1); expect(passed).toBe(0); expect(failed).toBe(0); expect(timedOut).toBe(1); }); it('should succeed', async () => { const result = await runTest('one-success.js'); expect(result.exitCode).toBe(0); expect(result.passed).toBe(1); expect(result.failed).toBe(0); }); it('should access error in fixture', async () => { const result = await runTest('test-error-visible-in-fixture.js'); expect(result.exitCode).toBe(1); const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'test-results', 'test-error-visible-in-fixture.txt')).toString()); expect(data.message).toContain('Object.is equality'); }); it('should access data in fixture', async () => { const { exitCode, report } = await runTest('test-data-visible-in-fixture.js'); expect(exitCode).toBe(1); const testResult = report.suites[0].tests[0].results[0]; expect(testResult.data).toEqual({ 'myname': 'myvalue' }); expect(testResult.stdout).toEqual([{ text: 'console.log\n' }]); expect(testResult.stderr).toEqual([{ text: 'console.error\n' }]); }); it('should handle worker fixture timeout', async () => { const result = await runTest('worker-fixture-timeout.js', { timeout: 1000 }); expect(result.exitCode).toBe(1); expect(result.output).toContain('Timeout of 1000ms'); }); it('should handle worker fixture error', async () => { const result = await runTest('worker-fixture-error.js'); expect(result.exitCode).toBe(1); expect(result.output).toContain('Worker failed'); }); it('should collect stdio', async () => { const { exitCode, report } = await runTest('stdio.js'); expect(exitCode).toBe(0); const testResult = report.suites[0].tests[0].results[0]; const { stdout, stderr } = testResult; expect(stdout).toEqual([{ text: 'stdout text' }, { buffer: Buffer.from('stdout buffer').toString('base64') }]); expect(stderr).toEqual([{ text: 'stderr text' }, { buffer: Buffer.from('stderr buffer').toString('base64') }]); }); it('should work with typescript', async () => { const result = await runTest('typescript.ts'); expect(result.exitCode).toBe(0); }); it('should retry failures', async () => { const result = await runTest('retry-failures.js', { retries: 1 }); expect(result.exitCode).toBe(1); expect(result.flaky).toBe(1); }); it('should retry timeout', async () => { const { exitCode, passed, failed, timedOut, output } = await runTest('one-timeout.js', { timeout: 100, retries: 2 }); expect(exitCode).toBe(1); expect(passed).toBe(0); expect(failed).toBe(0); expect(timedOut).toBe(1); expect(output.split('\n')[0]).toBe(colors.red('T').repeat(3)); }); it('should repeat each', async () => { const { exitCode, report } = await runTest('one-success.js', { 'repeat-each': 3 }); expect(exitCode).toBe(0); expect(report.suites.length).toBe(3); for (const suite of report.suites) expect(suite.tests.length).toBe(1); }); it('should report suite errors', async () => { const { exitCode, failed, output } = await runTest('suite-error.js'); expect(exitCode).toBe(1); expect(failed).toBe(1); expect(output).toContain('Suite error'); }); it('should allow flaky', async () => { const result = await runTest('allow-flaky.js', { retries: 1 }); expect(result.exitCode).toBe(0); expect(result.flaky).toBe(1); }); it('should fail on unexpected pass', async () => { const { exitCode, failed, output } = await runTest('unexpected-pass.js'); expect(exitCode).toBe(1); expect(failed).toBe(1); expect(output).toContain('passed unexpectedly'); }); it('should fail on unexpected pass with retries', async () => { const { exitCode, failed, output } = await runTest('unexpected-pass.js', { retries: 1 }); expect(exitCode).toBe(1); expect(failed).toBe(1); expect(output).toContain('passed unexpectedly'); }); it('should not retry unexpected pass', async () => { const { exitCode, passed, failed, output } = await runTest('unexpected-pass.js', { retries: 2 }); expect(exitCode).toBe(1); expect(passed).toBe(0); expect(failed).toBe(1); expect(output.split('\n')[0]).toBe(colors.red('P')); }); it('should not retry expected failure', async () => { const { exitCode, passed, failed, output } = await runTest('expected-failure.js', { retries: 2 }); expect(exitCode).toBe(0); expect(passed).toBe(2); expect(failed).toBe(0); expect(output.split('\n')[0]).toBe(colors.green('f') + colors.green('·')); }); it('should respect nested skip', async () => { const { exitCode, passed, failed, skipped } = await runTest('nested-skip.js'); expect(exitCode).toBe(0); expect(passed).toBe(0); expect(failed).toBe(0); expect(skipped).toBe(1); }); async function runTest(filePath: string, params: any = {}) { const outputDir = path.join(__dirname, 'test-results'); const reportFile = path.join(outputDir, 'results.json'); await removeFolderAsync(outputDir).catch(e => {}); const { output, status } = spawnSync('node', [ path.join(__dirname, '..', 'cli.js'), path.join(__dirname, 'assets', filePath), '--output=' + outputDir, '--reporter=dot,json', ...Object.keys(params).map(key => `--${key}=${params[key]}`) ], { env: { ...process.env, PWRUNNER_JSON_REPORT: reportFile, } }); const passed = (/(\d+) passed/.exec(output.toString()) || [])[1]; const failed = (/(\d+) failed/.exec(output.toString()) || [])[1]; const timedOut = (/(\d+) timed out/.exec(output.toString()) || [])[1]; const flaky = (/(\d+) flaky/.exec(output.toString()) || [])[1]; const skipped = (/(\d+) skipped/.exec(output.toString()) || [])[1]; const report = JSON.parse(fs.readFileSync(reportFile).toString()); let outputStr = output.toString(); outputStr = outputStr.substring(1, outputStr.length - 1); return { exitCode: status, output: outputStr, passed: parseInt(passed, 10), failed: parseInt(failed || '0', 10), timedOut: parseInt(timedOut || '0', 10), flaky: parseInt(flaky || '0', 10), skipped: parseInt(skipped || '0', 10), report }; } <file_sep>/test-runner/src/index.ts /** * Copyright 2019 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * 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. */ import * as fs from 'fs'; import * as path from 'path'; import rimraf from 'rimraf'; import { promisify } from 'util'; import './builtin.fixtures'; import './expect'; import { registerFixture as registerFixtureT, registerWorkerFixture as registerWorkerFixtureT, TestInfo } from './fixtures'; import { Reporter } from './reporter'; import { Runner } from './runner'; import { RunnerConfig } from './runnerConfig'; import { Matrix, TestCollector } from './testCollector'; import { installTransform } from './transform'; export { parameters, registerParameter } from './fixtures'; export { Reporter } from './reporter'; export { RunnerConfig } from './runnerConfig'; export { Suite, Test } from './test'; const removeFolderAsync = promisify(rimraf); declare global { interface WorkerState { } interface TestState { } interface FixtureParameters { } } const beforeFunctions: Function[] = []; const afterFunctions: Function[] = []; let matrix: Matrix = {}; global['before'] = (fn: Function) => beforeFunctions.push(fn); global['after'] = (fn: Function) => afterFunctions.push(fn); global['matrix'] = (m: Matrix) => matrix = m; export function registerFixture<T extends keyof TestState>(name: T, fn: (params: FixtureParameters & WorkerState & TestState, runTest: (arg: TestState[T]) => Promise<void>, info: TestInfo) => Promise<void>) { registerFixtureT(name, fn); } export function registerWorkerFixture<T extends keyof(WorkerState & FixtureParameters)>(name: T, fn: (params: FixtureParameters & WorkerState, runTest: (arg: (WorkerState & FixtureParameters)[T]) => Promise<void>, config: RunnerConfig) => Promise<void>) { registerWorkerFixtureT(name, fn); } type RunResult = 'passed' | 'failed' | 'forbid-only' | 'no-tests'; export async function run(config: RunnerConfig, files: string[], reporter: Reporter): Promise<RunResult> { if (!config.trialRun) { await removeFolderAsync(config.outputDir).catch(e => {}); fs.mkdirSync(config.outputDir, { recursive: true }); } const revertBabelRequire = installTransform(); let hasSetup = false; try { hasSetup = fs.statSync(path.join(config.testDir, 'setup.js')).isFile(); } catch (e) { } try { hasSetup = hasSetup || fs.statSync(path.join(config.testDir, 'setup.ts')).isFile(); } catch (e) { } if (hasSetup) require(path.join(config.testDir, 'setup')); revertBabelRequire(); const testCollector = new TestCollector(files, matrix, config); const suite = testCollector.suite; if (config.forbidOnly) { const hasOnly = suite.findTest(t => t.only) || suite.eachSuite(s => s.only); if (hasOnly) return 'forbid-only'; } const total = suite.total(); if (!total) return 'no-tests'; // Trial run does not need many workers, use one. const jobs = (config.trialRun || config.debug) ? 1 : config.jobs; const runner = new Runner(suite, { ...config, jobs }, reporter); try { for (const f of beforeFunctions) await f(); await runner.run(); await runner.stop(); } finally { for (const f of afterFunctions) await f(); } return suite.findTest(test => !test._ok()) ? 'failed' : 'passed'; } <file_sep>/test-runner/src/testRunner.ts /** * Copyright Microsoft Corporation. All rights reserved. * * 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. */ import { FixturePool, rerunRegistrations, setParameters, TestInfo } from './fixtures'; import { EventEmitter } from 'events'; import { setCurrentTestFile } from './expect'; import { Test, Suite, Configuration, serializeError, TestResult } from './test'; import { spec } from './spec'; import { RunnerConfig } from './runnerConfig'; import * as util from 'util'; export const fixturePool = new FixturePool(); export type TestRunnerEntry = { file: string; ids: string[]; configurationString: string; configuration: Configuration; hash: string; }; function chunkToParams(chunk: Buffer | string): { text?: string, buffer?: string } { if (chunk instanceof Buffer) return { buffer: chunk.toString('base64') }; if (typeof chunk !== 'string') return { text: util.inspect(chunk) }; return { text: chunk }; } export class TestRunner extends EventEmitter { private _failedTestId: string | undefined; private _fatalError: any | undefined; private _ids: Set<string>; private _remaining: Set<string>; private _trialRun: any; private _parsedGeneratorConfiguration: any = {}; private _config: RunnerConfig; private _timeout: number; private _testId: string | null; private _stdOutBuffer: (string | Buffer)[] = []; private _stdErrBuffer: (string | Buffer)[] = []; private _testResult: TestResult | null = null; private _suite: Suite; private _loaded = false; constructor(entry: TestRunnerEntry, config: RunnerConfig, workerId: number) { super(); this._suite = new Suite(''); this._suite.file = entry.file; this._suite._configurationString = entry.configurationString; this._ids = new Set(entry.ids); this._remaining = new Set(entry.ids); this._trialRun = config.trialRun; this._timeout = config.timeout; this._config = config; for (const {name, value} of entry.configuration) this._parsedGeneratorConfiguration[name] = value; this._parsedGeneratorConfiguration['parallelIndex'] = workerId; setCurrentTestFile(this._suite.file); } stop() { this._trialRun = true; } unhandledError(error: Error | any) { if (this._testResult) { this._testResult.error = serializeError(error); this.emit('testEnd', { id: this._testId, result: this._testResult }); } else if (!this._loaded) { // No current test - fatal error. this._fatalError = serializeError(error); } this._reportDone(); } stdout(chunk: string | Buffer) { this._stdOutBuffer.push(chunk); if (!this._testId) return; for (const c of this._stdOutBuffer) this.emit('testStdOut', { id: this._testId, ...chunkToParams(c) }); this._stdOutBuffer = []; } stderr(chunk: string | Buffer) { this._stdErrBuffer.push(chunk); if (!this._testId) return; for (const c of this._stdErrBuffer) this.emit('testStdErr', { id: this._testId, ...chunkToParams(c) }); this._stdErrBuffer = []; } async run() { setParameters(this._parsedGeneratorConfiguration); const revertBabelRequire = spec(this._suite, this._suite.file, this._timeout); require(this._suite.file); revertBabelRequire(); this._suite._renumber(); this._loaded = true; rerunRegistrations(this._suite.file, 'test'); await this._runSuite(this._suite); this._reportDone(); } private async _runSuite(suite: Suite) { try { await this._runHooks(suite, 'beforeAll', 'before'); } catch (e) { this._fatalError = serializeError(e); this._reportDone(); } for (const entry of suite._entries) { if (entry instanceof Suite) await this._runSuite(entry); else await this._runTest(entry); } try { await this._runHooks(suite, 'afterAll', 'after'); } catch (e) { this._fatalError = serializeError(e); this._reportDone(); } } private async _runTest(test: Test) { if (this._failedTestId) return false; if (this._ids.size && !this._ids.has(test._id)) return; this._remaining.delete(test._id); const id = test._id; this._testId = id; // We only know resolved skipped/flaky value in the worker, // send it to the runner. test._skipped = test._skipped || test.suite._isSkipped(); this.emit('testBegin', { id, skipped: test._skipped, flaky: test._flaky, }); const result: TestResult = { duration: 0, status: 'passed', expectedStatus: test._expectedStatus, stdout: [], stderr: [], data: {} }; this._testResult = result; if (test._skipped) { result.status = 'skipped'; this.emit('testEnd', { id, result }); return; } const startTime = Date.now(); try { const testInfo = { config: this._config, test, result }; if (!this._trialRun) { await this._runHooks(test.suite, 'beforeEach', 'before', testInfo); const timeout = test.slow ? this._timeout * 3 : this._timeout; await fixturePool.runTestWithFixtures(test.fn, timeout, testInfo); await this._runHooks(test.suite, 'afterEach', 'after', testInfo); } else { result.status = result.expectedStatus; } } catch (error) { // Error in the test fixture teardown. result.status = 'failed'; result.error = serializeError(error); } result.duration = Date.now() - startTime; this.emit('testEnd', { id, result }); if (result.status !== 'passed') this._failedTestId = this._testId; this._testResult = null; this._testId = null; } private async _runHooks(suite: Suite, type: string, dir: 'before' | 'after', testInfo?: TestInfo) { if (!suite._hasTestsToRun()) return; const all = []; for (let s = suite; s; s = s.parent) { const funcs = s._hooks.filter(e => e.type === type).map(e => e.fn); all.push(...funcs.reverse()); } if (dir === 'before') all.reverse(); for (const hook of all) await fixturePool.resolveParametersAndRun(hook, this._config, testInfo); } private _reportDone() { this.emit('done', { failedTestId: this._failedTestId, fatalError: this._fatalError, remaining: [...this._remaining], }); } } <file_sep>/test-runner/src/reporters/base.ts /** * Copyright (c) Microsoft Corporation. * * 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. */ import { codeFrameColumns } from '@babel/code-frame'; import colors from 'colors/safe'; import fs from 'fs'; import milliseconds from 'ms'; import os from 'os'; import path from 'path'; import StackUtils from 'stack-utils'; import terminalLink from 'terminal-link'; import { Reporter } from '../reporter'; import { RunnerConfig } from '../runnerConfig'; import { Suite, Test, TestResult } from '../test'; const stackUtils = new StackUtils(); export class BaseReporter implements Reporter { skipped: Test[] = []; asExpected: Test[] = []; unexpected = new Set<Test>(); flaky: Test[] = []; duration = 0; startTime: number; config: RunnerConfig; suite: Suite; constructor() { process.on('SIGINT', async () => { this.epilogue(); process.exit(130); }); } onBegin(config: RunnerConfig, suite: Suite) { this.startTime = Date.now(); this.config = config; this.suite = suite; } onTestBegin(test: Test) { } onTestStdOut(test: Test, chunk: string | Buffer) { if (!this.config.quiet) process.stdout.write(chunk); } onTestStdErr(test: Test, chunk: string | Buffer) { if (!this.config.quiet) process.stderr.write(chunk); } onTestEnd(test: Test, result: TestResult) { if (result.status === 'skipped') { this.skipped.push(test); return; } if (result.status === result.expectedStatus) { if (test.results.length === 1) { // as expected from the first attempt this.asExpected.push(test); } else { // as expected after unexpected -> flaky. this.flaky.push(test); } return; } if (result.status === 'passed' || result.status === 'timedOut' || test.results.length === this.config.retries + 1) { // We made as many retries as we could, still failing. this.unexpected.add(test); } } onEnd() { this.duration = Date.now() - this.startTime; } epilogue() { console.log(''); console.log(colors.green(` ${this.asExpected.length} passed`) + colors.dim(` (${milliseconds(this.duration)})`)); if (this.skipped.length) console.log(colors.yellow(` ${this.skipped.length} skipped`)); const filteredUnexpected = [...this.unexpected].filter(t => !t._hasResultWithStatus('timedOut')); if (filteredUnexpected.length) { console.log(colors.red(` ${filteredUnexpected.length} failed`)); console.log(''); this._printFailures(filteredUnexpected); } if (this.flaky.length) { console.log(colors.red(` ${this.flaky.length} flaky`)); console.log(''); this._printFailures(this.flaky); } const timedOut = [...this.unexpected].filter(t => t._hasResultWithStatus('timedOut')); if (timedOut.length) { console.log(colors.red(` ${timedOut.length} timed out`)); console.log(''); this._printFailures(timedOut); } console.log(''); } private _printFailures(failures: Test[]) { failures.forEach((test, index) => { console.log(this.formatFailure(test, index + 1)); }); } formatFailure(test: Test, index?: number): string { const tokens: string[] = []; const relativePath = path.relative(process.cwd(), test.file); const passedUnexpectedlySuffix = test.results[0].status === 'passed' ? ' -- passed unexpectedly' : ''; const header = ` ${index ? index + ')' : ''} ${terminalLink(relativePath, `file://${os.hostname()}${test.file}`)} › ${test.title}${passedUnexpectedlySuffix}`; tokens.push(colors.bold(colors.red(header))); for (const result of test.results) { if (result.status === 'passed') continue; if (result.status === 'timedOut') { tokens.push(''); tokens.push(indent(colors.red(`Timeout of ${test.timeout}ms exceeded.`), ' ')); } else { const stack = result.error.stack; if (stack) { tokens.push(''); const messageLocation = result.error.stack.indexOf(result.error.message); const preamble = result.error.stack.substring(0, messageLocation + result.error.message.length); tokens.push(indent(preamble, ' ')); const position = positionInFile(stack, test.file); if (position) { const source = fs.readFileSync(test.file, 'utf8'); tokens.push(''); tokens.push(indent(codeFrameColumns(source, { start: position, }, { highlightCode: true} ), ' ')); } tokens.push(''); tokens.push(indent(colors.dim(stack.substring(preamble.length + 1)), ' ')); } else { tokens.push(''); tokens.push(indent(String(result.error), ' ')); } } break; } tokens.push(''); return tokens.join('\n'); } } function indent(lines: string, tab: string) { return lines.replace(/^/gm, tab); } function positionInFile(stack: string, file: string): { column: number; line: number; } { for (const line of stack.split('\n')) { const parsed = stackUtils.parseLine(line); if (!parsed) continue; if (path.resolve(process.cwd(), parsed.file) === file) return {column: parsed.column, line: parsed.line}; } return null; } <file_sep>/test-runner/src/reporters/json.ts /** * Copyright (c) Microsoft Corporation. * * 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. */ import { BaseReporter } from './base'; import { Suite, Test, TestResult } from '../test'; import * as fs from 'fs'; class JSONReporter extends BaseReporter { onEnd() { super.onEnd(); const result = { config: this.config, suites: this.suite.suites.map(suite => this._serializeSuite(suite)).filter(s => s) }; const report = JSON.stringify(result, undefined, 2); if (process.env.PWRUNNER_JSON_REPORT) fs.writeFileSync(process.env.PWRUNNER_JSON_REPORT, report); else console.log(report); } private _serializeSuite(suite: Suite): any { if (!suite.findTest(test => true)) return null; const suites = suite.suites.map(suite => this._serializeSuite(suite)).filter(s => s); return { title: suite.title, file: suite.file, configuration: suite.configuration, tests: suite.tests.map(test => this._serializeTest(test)), suites: suites.length ? suites : undefined }; } private _serializeTest(test: Test): any { return { title: test.title, file: test.file, only: test.only, slow: test.slow, timeout: test.timeout, results: test.results.map(r => this._serializeTestResult(r)) }; } private _serializeTestResult(result: TestResult): any { return { status: result.status, duration: result.duration, error: result.error, stdout: result.stdout.map(s => stdioEntry(s)), stderr: result.stderr.map(s => stdioEntry(s)), data: result.data }; } } function stdioEntry(s: string | Buffer): any { if (typeof s === 'string') return { text: s }; return { buffer: s.toString('base64') }; } export default JSONReporter; <file_sep>/test-runner/src/spec.ts /** * Copyright (c) Microsoft Corporation. * * 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. */ import { Test, Suite } from './test'; import { installTransform } from './transform'; Error.stackTraceLimit = 15; function specBuilder(modifiers, specCallback) { function builder(specs, last) { const callable = (...args) => { if (!last || (typeof args[0] === 'string' && typeof args[1] === 'function')) { // Looks like a body (either it or describe). Assume that last modifier is true. const newSpecs = { ...specs }; if (last) newSpecs[last] = [true]; return specCallback(newSpecs, ...args); } const newSpecs = { ...specs }; newSpecs[last] = args; return builder(newSpecs, null); }; return new Proxy(callable, { get: (obj, prop) => { if (typeof prop === 'string' && modifiers.includes(prop)) { const newSpecs = { ...specs }; // Modifier was not called, assume true. if (last) newSpecs[last] = [true]; return builder(newSpecs, prop); } return obj[prop]; }, }); } return builder({}, null); } export function spec(suite: Suite, file: string, timeout: number): () => void { const suites = [suite]; suite.file = file; const it = specBuilder(['skip', 'fixme', 'fail', 'slow', 'only', 'flaky'], (specs, title, fn) => { const suite = suites[0]; const test = new Test(title, fn); test.file = file; test.slow = specs.slow && specs.slow[0]; test.timeout = timeout; const only = specs.only && specs.only[0]; if (only) test.only = true; if (!only && specs.skip && specs.skip[0]) test._skipped = true; if (!only && specs.fixme && specs.fixme[0]) test._skipped = true; if (specs.fail && specs.fail[0]) test._expectedStatus = 'failed'; if (specs.flaky && specs.flaky[0]) test._flaky = true; suite._addTest(test); return test; }); const describe = specBuilder(['skip', 'fixme', 'only'], (specs, title, fn) => { const child = new Suite(title, suites[0]); suites[0]._addSuite(child); child.file = file; const only = specs.only && specs.only[0]; if (only) child.only = true; if (!only && specs.skip && specs.skip[0]) child._skipped = true; if (!only && specs.fixme && specs.fixme[0]) child._skipped = true; suites.unshift(child); fn(); suites.shift(); }); (global as any).beforeEach = fn => suite._addHook('beforeEach', fn); (global as any).afterEach = fn => suite._addHook('afterEach', fn); (global as any).beforeAll = fn => suite._addHook('beforeAll', fn); (global as any).afterAll = fn => suite._addHook('afterAll', fn); (global as any).describe = describe; (global as any).fdescribe = describe.only(true); (global as any).xdescribe = describe.skip(true); (global as any).it = it; (global as any).fit = it.only(true); (global as any).xit = it.skip(true); return installTransform(); } <file_sep>/test-runner/src/reporters/pytest.ts /** * Copyright (c) Microsoft Corporation. * * 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. */ import colors from 'colors/safe'; import milliseconds from 'ms'; import * as path from 'path'; import { Test, Suite, Configuration, TestResult } from '../test'; import { BaseReporter } from './base'; import { RunnerConfig } from '../runnerConfig'; const cursorPrevLine = '\u001B[F'; const eraseLine = '\u001B[2K'; type Row = { id: string; relativeFile: string; configuration: string; ordinal: number; track: string[]; total: number; failed: boolean; startTime: number; finishTime: number; }; const statusRows = 2; class PytestReporter extends BaseReporter { private _rows = new Map<string, Row>(); private _suiteIds = new Map<Suite, string>(); private _lastOrdinal = 0; private _visibleRows: number; private _total: number; private _progress: string[] = []; private _throttler = new Throttler(250, () => this._repaint()); onBegin(config: RunnerConfig, rootSuite: Suite) { super.onBegin(config, rootSuite); this._total = rootSuite.total(); const jobs = Math.min(config.jobs, rootSuite.suites.length); this._visibleRows = jobs + Math.min(jobs, 3); // 3 buffer rows for completed (green) workers. for (let i = 0; i < this._visibleRows + statusRows; ++i) // 4 rows for status process.stdout.write('\n'); for (const s of rootSuite.suites) { const relativeFile = path.relative(this.config.testDir, s.file); const configurationString = serializeConfiguration(s.configuration); const id = relativeFile + `::[${configurationString}]`; this._suiteIds.set(s, id); const row = { id, relativeFile, configuration: configurationString, ordinal: this._lastOrdinal++, track: [], total: s.total(), failed: false, startTime: 0, finishTime: 0, }; this._rows.set(id, row); } } onTestBegin(test: Test) { super.onTestBegin(test); const row = this._rows.get(this._id(test)); if (!row.startTime) row.startTime = Date.now(); } onTestStdOut(test: Test, chunk: string | Buffer) { this._repaint(chunk); } onTestStdErr(test: Test, chunk: string | Buffer) { this._repaint(chunk); } onTestEnd(test: Test, result: TestResult) { super.onTestEnd(test, result); switch (result.status) { case 'skipped': { this._append(test, colors.yellow('∘')); this._progress.push('S'); this._throttler.schedule(); break; } case 'passed': { this._append(test, colors.green('✓')); this._progress.push('P'); this._throttler.schedule(); break; } case 'failed': // fall through case 'timedOut': { const title = result.status === 'timedOut' ? colors.red('T') : colors.red('F'); const row = this._append(test, title); row.failed = true; this._progress.push('F'); this._repaint(this.formatFailure(test) + '\n'); break; } } } private _append(test: Test, s: string): Row { const testId = this._id(test); const row = this._rows.get(testId); row.track.push(s); if (row.track.length === row.total) row.finishTime = Date.now(); return row; } private _repaint(prependChunk?: string | Buffer) { const rowList = [...this._rows.values()]; const running = rowList.filter(r => r.startTime && !r.finishTime); const finished = rowList.filter(r => r.finishTime).sort((a, b) => b.finishTime - a.finishTime); const finishedToPrint = finished.slice(0, this._visibleRows - running.length); const lines = []; for (const row of finishedToPrint.concat(running)) { const remaining = row.total - row.track.length; const remainder = '·'.repeat(remaining); let title = row.relativeFile; if (row.finishTime) { if (row.failed) title = colors.red(row.relativeFile); else title = colors.green(row.relativeFile); } const configuration = ` [${colors.gray(row.configuration)}]`; lines.push(' ' + title + configuration + ' ' + row.track.join('') + colors.gray(remainder)); } const status = []; if (this.asExpected.length) status.push(colors.green(`${this.asExpected.length} as expected`)); if (this.skipped.length) status.push(colors.yellow(`${this.skipped.length} skipped`)); const timedOut = [...this.unexpected].filter(t => t._hasResultWithStatus('timedOut')); if (this.unexpected.size - timedOut.length) status.push(colors.red(`${this.unexpected.size - timedOut.length} unexpected failures`)); if (timedOut.length) status.push(colors.red(`${timedOut.length} timed out`)); status.push(colors.dim(`(${milliseconds(Date.now() - this.startTime)})`)); for (let i = lines.length; i < this._visibleRows; ++i) lines.push(''); lines.push(this._paintProgress(this._progress.length, this._total)); lines.push(status.join(' ')); lines.push(''); process.stdout.write((cursorPrevLine + eraseLine).repeat(this._visibleRows + statusRows)); if (prependChunk) process.stdout.write(prependChunk); process.stdout.write(lines.join('\n')); } private _id(test: Test): string { for (let suite = test.suite; suite; suite = suite.parent) { if (this._suiteIds.has(suite)) return this._suiteIds.get(suite); } return ''; } private _paintProgress(worked: number, total: number) { const length = Math.min(total, 80); const cellSize = Math.ceil(total / length); const cellNum = (total / cellSize) | 0; const bars: string[] = []; for (let i = 0; i < cellNum; ++i) { let bar = blankBar; if (worked < cellSize * i) { bars.push(bar); continue; } bar = greenBar; for (let j = i * cellSize; j < worked && j < (i + 1) * cellSize; ++j) { if (worked < j) continue; if (this._progress[j] === 'F') { bar = redBar; break; } if (this._progress[j] === 'S') { bar = yellowBar; break; } } bars.push(bar); } return '[' + bars.join('') + '] ' + worked + '/' + total; } } const blankBar = '-'; const redBar = colors.red('▇'); const greenBar = colors.green('▇'); const yellowBar = colors.yellow('▇'); function serializeConfiguration(configuration: Configuration): string { const tokens = []; for (const { name, value } of configuration) tokens.push(`${name}=${value}`); return tokens.join(', '); } class Throttler { private _timeout: number; private _callback: () => void; private _lastFire = 0; private _timer: NodeJS.Timeout | null = null; constructor(timeout: number, callback: () => void) { this._timeout = timeout; this._callback = callback; } schedule() { const time = Date.now(); const timeRemaining = this._lastFire + this._timeout - time; if (timeRemaining <= 0) { this._fire(); return; } if (!this._timer) this._timer = setTimeout(() => this._fire(), timeRemaining); } private _fire() { this._timer = null; this._lastFire = Date.now(); this._callback(); } } export default PytestReporter;
b8f5c7c6f3a2a228b0f4a40d3ecaf030fd5de222
[ "TypeScript" ]
11
TypeScript
zzork/playwright
6ffdd4dfa1b8daf7bc43abd910b738ffee3ace44
b07dff1075866610c97cdcd62340dabb78131df9
refs/heads/master
<repo_name>mtellect/FlutterImagePickCrop<file_sep>/README.md # flutter_image_pick_crop A new Flutter plugin for cropping images picked from camera or gallery. ## Screenshots <img src="ss1.png" height="300em" /> <img src="ss2.png" height="300em" /> <img src="ss3.png" height="300em" /> <img src="ss4.png" height="300em" /> <img src="ss5.png" height="300em" /> <img src="ss6.png" height="300em" /> ### Show some :heart: and star the repo to support the project ## Usage [Example](https://github.com/mtellect/FlutterImagePickCrop/blob/master/example/lib/main.dart) ```yaml dependencies: flutter: sdk: flutter flutter_image_pick_crop: ``` ```dart class _MyAppState extends State<MyApp> { String _platformMessage = 'Unknown'; String _camera = 'fromCameraCropImage'; String _gallery = 'fromGalleryCropImage'; File imageFile; @override initState() { super.initState(); } initGalleryPickUp() async { /*setState(() { imageFile = null; _platformVersion = 'Unknown'; });*/ File file; String result; try { result = await FlutterImagePickCrop.pickAndCropImage(_gallery); } on PlatformException catch (e) { result = e.message; print(e.message); } if (!mounted) return; setState(() { imageFile = new File(result); _platformMessage = result; }); } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( appBar: new AppBar( title: new Text('Plugin Image Crop'), ), body: new Container( padding: const EdgeInsets.all(8.0), child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ imageFile != null ? new Image.file( imageFile, height: 400.0, ) : new Icon( Icons.image, size: 200.0, color: Theme.of(context).primaryColor, ), new Center( child: new Text('Running on: $_platformMessage\n'), ), new RaisedButton.icon( onPressed: initGalleryPickUp, icon: new Icon(Icons.image), label: new Text("Open Camera/Gallery")), new Padding(padding: new EdgeInsets.only(left: 5.0, right: 5.0)) ], ), ), ), ); } } ``` # Pull Requests I welcome and encourage all pull requests. It usually will take me within 24-48 hours to respond to any issue or request. Here are some basic rules to follow to ensure timely addition of your request: 1. Match coding style (braces, spacing, etc.) This is best achieved using `Reformat Code` feature of Android Studio `CMD`+`Option`+`L` on Mac and `CTRL` + `ALT` + `L` on Linux + Windows . 2. If its a feature, bugfix, or anything please only change code to what you specify. 3. Please keep PR titles easy to read and descriptive of changes, this will make them easier to merge :) 4. Pull requests _must_ be made against `develop` branch. Any other branch (unless specified by the maintainers) will get rejected. 5. Check for existing [issues](https://github.com/mtellect/FlutterImagePickCrop/issues) first, before filing an issue. 6. Make sure you follow the set standard as all other projects in this repo do 7. Have fun! ### Created & Maintained By [Maugost_Mtellect](https://github.com/mtellect/) > If you found this project helpful or you learned something from the source code and want to thank me, consider buying me a cup of :coffee: > > *Bitcoin: 1K2wivc2xy7tTjsmHhNzq7wwEHoyHfS64n # License Copyright 2018 <NAME> 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. ## Getting Started For help getting started with Flutter, view our online [documentation](https://flutter.io/). For help on editing package code, view the [documentation](https://flutter.io/developing-packages/).<file_sep>/android/src/main/java/maugost/flutterimagepickcrop/PickAndCrop.java package maugost.flutterimagepickcrop; import android.content.Intent; import io.flutter.plugin.common.PluginRegistry; /** * Created by <NAME> , CEO MTR Limited on 6/5/2018. */ public class PickAndCrop implements PluginRegistry.ActivityResultListener, PluginRegistry.RequestPermissionsResultListener { @Override public boolean onActivityResult(int i, int i1, Intent intent) { return false; } @Override public boolean onRequestPermissionsResult(int i, String[] strings, int[] ints) { return false; } } <file_sep>/CHANGELOG.md ## [0.0.1] - 6/62018. * Now you can pick images from either camera or gallery and crop the images before being displayed. (This version currently supports android for now.) <file_sep>/example/README.md # flutter_image_pick_crop_example Demonstrates how to use the flutter_image_pick_crop plugin. ## Getting Started For help getting started with Flutter, view our online [documentation](https://flutter.io/). <file_sep>/android/settings.gradle rootProject.name = 'flutter_image_pick_crop'
86125d8493a4abc1aba6e56c1bbff75e6d7be64b
[ "Markdown", "Java", "Gradle" ]
5
Markdown
mtellect/FlutterImagePickCrop
c66aeb272d668847c74e05d92ba1e146bf00b57e
3055c90e9b9b42d097dd871a9f15b2513c6d0181
refs/heads/master
<repo_name>aesimpson/umoja-design-system-archive<file_sep>/.storybook/preview.js import {html} from 'lit-html'; import samaTheme from './sama-theme.js'; const canvasStyles = ` html{ font-size: 100%; position: relative; box-sizing: border-box; --color-charcoal0: #0e0e11; --color-charcoal1: #1E1E24; --color-charcoal2: #2E2E38; --color-charcoal3: #40404f; --color-charcoal4: #606076; --color-charcoal5: #9D9DB5; --color-charcoal6: #cdcde1; --color-charcoal7: #e2e2ee; --color-purple: #7761b0; --font-manrope: "Manrope", sans-serif; } body{ background-color: var(--color-charcoal2); font-size: 1rem; font-weight: 400; font-family: var(--font-manrope); line-height: 1.5; } .main-content{ display: flex; flex-direction: column; align-items: center; padding: 3rem; }`; export const parameters = { backgrounds: { values: [ {name: 'charcoal0', value: '#0e0e11'}, {name: 'charcoal1', value: '#1E1E24'}, {name: 'charcoal2', value: '#2E2E38'}, {name: 'charcoal3', value: '#40404f'}, {name: 'charcoal4', value: '#606076'}, {name: 'charcoal5', value: '#9D9DB5'}, {name: 'charcoal6', value: '#cdcde1'}, {name: 'charcoal7', value: '#e2e2ee'}, {name: 'white', value: '#FFFFFF'}, ], }, docs: { theme: samaTheme, } }; export const decorators = [ (story) => html`<style>${canvasStyles}</style><div class="main-content">${story()}</div>`, ]; <file_sep>/src/styles/global-styles.js import {css} from 'lit'; import layoutCSS from './layout-styles.js'; export default css` :host { position: relative; box-sizing: border-box; --color-charcoal0: #0e0e11; --color-charcoal1: #1E1E24; --color-charcoal2: #2E2E38; --color-charcoal3: #40404f; --color-charcoal4: #606076; --color-charcoal5: #9D9DB5; --color-charcoal6: #cdcde1; --color-charcoal7: #e2e2ee; --color-purple0: #370c7c; --color-purple1: #5f2eae; --color-purple2: #885ad3; --color-purple3: #a378e9; --color-purple4: #c9aef5; --color-purple5: #e9dcfd; } :host *, :host *::before, :host *::after { box-sizing: inherit; } html { line-height: 1.15; -webkit-text-size-adjust: 100%; } body { margin: 0; } a { background-color: transparent; } button { font-family: inherit; font-size: 100%; margin: 0; } /** * Show the overflow in IE. * 1. Show the overflow in Edge. */ button, input { overflow: visible; } /** * Remove the inheritance of text transform in Edge, Firefox, and IE. * 1. Remove the inheritance of text transform in Firefox. */ button, select { /* 1 */ text-transform: none; } /** * Correct the inability to style clickable types in iOS and Safari. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; } /** * Remove the inner border and padding in Firefox. */ button::-moz-focus-inner, [type='button']::-moz-focus-inner, [type='reset']::-moz-focus-inner, [type='submit']::-moz-focus-inner { border-style: none; padding: 0; } /** * Restore the focus styles unset by the previous rule. */ button:-moz-focusring, [type='button']:-moz-focusring, [type='reset']:-moz-focusring, [type='submit']:-moz-focusring { outline: 1px dotted ButtonText; } /** * Add the correct display in IE 10. */ [hidden] { display: none; } .umoja-b-label{ font-size: 0.875rem; font-family: inherit; font-weight: 400; line-height: 1.43; color: var(--color-charcoal6); } .umoja-u-hidden{ display: none; } ${layoutCSS} `; <file_sep>/src/components/radio-button/radio-button.styles.js import {css} from 'lit'; import globalCSS from '../../styles/global-styles.js'; export default css` ${globalCSS} :host-context(umoja-radio-btn-group){ margin-right: 1rem; } .umoja-c-radio-btn__container{ display: inline-block; position: relative; } .umoja-c-radio-btn{ width: 100%; height: 100%; margin: 0; position: absolute; top: 0; left: 0; opacity: 0; cursor: pointer; z-index: 1; } .umoja-c-radio-btn__label{ display: inline-grid; grid-template-columns: 1rem auto; align-items: center; grid-column-gap: 0.5rem; position: relative; transition: all 0.15s linear; } .umoja-c-radio-btn__appearance{ display: inline-block; width: 1rem; height: 1rem; border: 1px solid var(--color-charcoal3); border-radius: 50%; background-color: var(--color-charcoal1); position: relative; } .umoja-c-radio-btn__appearance:before{ content: ""; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; border-radius: 50%; background-color: var(--color-charcoal5); position: absolute; position: absolute; top: 0; left: 0; transform: scale(0); } /* states */ .umoja-c-radio-btn:hover:enabled ~ .umoja-c-radio-btn__label, .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label{ color: #FFF } .umoja-c-radio-btn:active:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance, .umoja-c-radio-btn:focus:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ box-shadow: 0px 0px 0px 3px rgba(73, 55, 120, 0.4); /*purple glow*/ } .umoja-c-radio-btn:disabled{ cursor: not-allowed; } .umoja-c-radio-btn:disabled ~ *{ opacity: 0.5; } /* checked */ .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ border-color: var(--color-purple2); } .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance:before{ transform: scale(0.66); } /* image layout */ .umoja-c-radio-btn--img .umoja-c-radio-btn__label{ grid-template-columns: 1fr; grid-template-rows: 88px auto; min-width: 175px; border: 2px solid var(--color-charcoal0); border-radius: 10px; overflow: hidden; } .umoja-c-radio-btn--img .umoja-c-radio-btn__label > *{ padding: 0.5rem 1rem; } .umoja-c-radio-btn--img__top{ width: 100%; height: 100%; background: var(--backgroundImg) no-repeat center / cover; } .umoja-c-radio-btn--img .umoja-c-radio-btn__label-txt{ text-align: center; background-color: var(--color-charcoal3); } .umoja-c-radio-btn--img .umoja-c-radio-btn:focus:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ box-shadow: none; } .umoja-c-radio-btn--img .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label{ border-color: var(--color-purple2); } /* themes */ .umoja-c-radio-btn--light .umoja-c-radio-btn__appearance{ background-color: #FFF; border: 2px solid var(--color-charcoal0); } .umoja-c-radio-btn--light .umoja-c-radio-btn__appearance:before{ background-color: var(--color-purple1); } .umoja-c-radio-btn--light .umoja-c-radio-btn__label-txt{ color: var(--color-charcoal0); font-weight: 600; } .umoja-c-radio-btn--light .umoja-c-radio-btn:hover:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance, .umoja-c-radio-btn--light .umoja-c-radio-btn:active:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance, .umoja-c-radio-btn--light .umoja-c-radio-btn:focus:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ background-color: rgb(0 0 0 / 10%); } .umoja-c-radio-btn--light .umoja-c-radio-btn:hover:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ box-shadow: -3px 3px 0px rgba(0, 0, 0, 0.1); } .umoja-c-radio-btn--light .umoja-c-radio-btn:active:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance, .umoja-c-radio-btn--light .umoja-c-radio-btn:focus:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ box-shadow: none; } .umoja-c-radio-btn--light .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ border-color: var(--color-purple1); } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn__label-txt{ background-color: #FFF; } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:hover:enabled ~ .umoja-c-radio-btn__label{ box-shadow: -3px 3px 0px rgba(0, 0, 0, 0.1); } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:hover:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ background-color: #EAEAEA; box-shadow: none; } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:active:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance, .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:focus:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ background-color: #EAEAEA; } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label{ border-color: var(--color-purple1); } .umoja-c-radio-btn--light.umoja-c-radio-btn--img .umoja-c-radio-btn:checked ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__label-txt{ color: var(--color-purple1); } .umoja-c-radio-btn--light .umoja-c-radio-btn:checked:hover:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance{ border-color: var(--color-purple0); } .umoja-c-radio-btn--light .umoja-c-radio-btn:checked:hover:enabled ~ .umoja-c-radio-btn__label .umoja-c-radio-btn__appearance:before{ background-color: var(--color-purple0); } `; <file_sep>/stories/radio-button-story.js import {html} from 'lit-html'; import '../src/components/radio-button/radio-button.js'; export default { title: 'Components/Radio Button', component: 'umoja-radio-btn', parameters: { docs: { description: { component: '**<umoja-radio-btn>**', }, source: { type: 'code', } } }, argTypes: { label: { control: { type: 'text', }, }, name: { control: { type: 'text', }, }, value: { control: { type: 'text', }, }, disabled: { description: 'Specifices if a button is disabled. When attribute is set, the button will be unusable and un-clickable.', table: { type: { summary: 'boolean', detail: '<umoja-radio-btn disabled></umoja-radio-btn>', }, }, control: { type: 'boolean', }, }, checked: { control: { type: 'boolean', }, table: { type: { summary: 'boolean', detail: '<umoja-radio-btn checked></umoja-radio-btn>', }, }, }, img: { description: "If the img attribute is set to a valid image url, the radio button will render with the image as its background.", control: { type: 'text', }, }, theme: { description: "The theme color of the button. Default theme is dark mode.", table: { defaultValue: { summary: 'dark', }, }, options: ['dark','light'], control: { type: 'select', }, }, }, }; const Template = ({ img, label, disabled, checked, name, value, theme }) => html` <umoja-radio-btn label=${label} name=${name} value=${value} .img=${img} .theme=${theme} .checked=${checked} .disabled=${disabled} > </umoja-radio-btn> `; export const Default = Template.bind({}); Default.args = { label: 'Radio Button', name: 'radio_button', value: 'value', checked: false, disabled: false, }; Default.parameters = { docs: { source: { code: '<umoja-radio-btn label="Radio Button" name="radio_button" value="value"></umoja-radio-btn>', }, }, }; export const Image = Template.bind({}); Image.args = { label: 'Radio Button', name: 'radio_button', value: 'value', checked: false, disabled: false, img: 'https://www.sama.com/hubfs/edgecases_rain1.png', theme: 'light' }; Default.parameters = { docs: { source: { code: '<umoja-radio-btn label="Radio Button" name="radio_button" value="value" theme="light" style="--backgroundImg:url(edgecases_rain1.png);"></umoja-radio-btn>', }, }, }; <file_sep>/src/README.md ## Use an Umoja component This is a general guide to using umoja components. Refer to a component’s README or other documentation for specific details. To use a umoja component in your code: 1. From your project folder, install the component from npm. ```bash npm install umoja-web-components # requires node 10 & npm 6 or higher ``` 2. Import the component. All components: ```bash import 'umoja-web-components'; ``` You can import a single component with it's file path: Example: ```bash import 'umoja-web-components/components/button/button].js'; ``` 3. Add the component to your application or component: ```bash <umoja-component></umoja-component> ``` <file_sep>/.storybook/sama-theme.js import { create } from '@web/storybook-prebuilt/theming'; export default create({ base: 'dark', brandTitle: 'Sama', brandUrl: 'https://www.sama.com/', brandImage: './images/logo-white.png', });<file_sep>/src/components/radio-button/radio-button.js import {LitElement, html} from 'lit'; import {classMap} from 'lit/directives/class-map.js'; import { ifDefined } from 'lit/directives/if-defined.js'; import styles from './radio-button.styles.js'; /** * Radio Button. * @element umoja-radio-btn */ export default class UmojaRadioButton extends LitElement { static get styles() { return [styles]; } static get properties() { return { img: {type: String, reflect: true}, label: {type: String, reflect: true}, name: {type: String, reflect: true}, value: {type: String, reflect: true}, disabled: {type: Boolean, reflect: true}, checked: {type: Boolean, reflect: true}, theme: {type: String, reflect: true} }; } constructor() { super(); this.disabled = false; this.checked = false; this.addEventListener('click', this.handleClick); } connectedCallback() { super.connectedCallback(); } handleClick(e) { const { target } = e; if (target.disabled) { e.preventDefault(); e.stopPropagation(); } target.tabIndex = this.checked ? 0 : -1; if(!this.checked){ let event = new CustomEvent('umoja-radio-btn-checked', { bubbles: true, composed: true, detail: { radio: this }, }) this.dispatchEvent(event); } } handleKeyEvent(e) { e.preventDefault(); let event = new CustomEvent('umoja-radio-btn-keyevent', { bubbles: true, composed: true, detail: { radio: this, key: e.keyCode }, }) this.dispatchEvent(event); } set img(value) { if(value){ this.style.setProperty("--backgroundImg", `url(${value})`); } } get img() { return this.style.getPropertyValue("--backgroundImg"); } updated() { let input = this.shadowRoot.querySelector('.umoja-c-radio-btn'); input.focus(); } render() { const {img, label, disabled, checked, name, value, theme, handleClick, handleKeyEvent} = this; return html` <div class= ${classMap({ [`umoja-c-radio-btn__container`]: true, [`umoja-c-radio-btn--${theme}`]: theme, ['umoja-c-radio-btn--img']: img })} > <input type="radio" class= "umoja-c-radio-btn" .checked="${checked}" name=${ifDefined(name)} value=${ifDefined(value)} ?disabled="${disabled}" @click="${handleClick}" @keyup="${handleKeyEvent}" tabIndex="${checked ? 0 : -1}" /> <label for="" class= "umoja-b-label umoja-c-radio-btn__label"> ${img ? html` <div class="umoja-c-radio-btn--img__top"> <span class="umoja-c-radio-btn__appearance"></span> </div>` : html` <span class="umoja-c-radio-btn__appearance"></span> ` } <span class="umoja-c-radio-btn__label-txt">${label}</span> </label> </div> `; } } window.customElements.define('umoja-radio-btn', UmojaRadioButton);<file_sep>/src/components/radio-button-group/radio-button-group.styles.js import {css} from 'lit'; import globalCSS from '../../styles/global-styles.js'; export default css` ${globalCSS} `;<file_sep>/src/components/radio-button-group/radio-button-group.js import {LitElement, html} from 'lit'; import styles from './radio-button-group.styles.js'; /** * Radio Button Group. * @element umoja-radio-btn-group */ export default class UmojaRadioButtonGroup extends LitElement { static get styles() { return [styles]; } static get properties() { return { name: {type: String, reflect: true}, orientation: {type: String, reflect: true}, labelPosition: {type: String, reflect: true}, value: {type: String}, radios: {type: Array}, theme: {type: String, reflect: true} }; } constructor() { super(); this.name = this.getAttribute('name'); this.theme = this.getAttribute('theme'); this.value = this.getAttribute('value'); this.addEventListener('umoja-radio-btn-checked', this.handleRadioButtonChange.bind(this)); this.addEventListener('umoja-radio-btn-keyevent', this.handleRadioButtonKeyEvent.bind(this)); } connectedCallback() { super.connectedCallback(); //TODO: future switch over to HTMLELement.attachInternals() method. Method only compatibile in Chrome as of 8/21 this.insertAdjacentHTML('beforeend', `<input class="umoja-u-form-association" type="hidden" name="${this.name}">`); } firstUpdated(){ const formAssociation = this.querySelector('.umoja-u-form-association'); this.radios = Array.from(this.getElementsByTagName('umoja-radio-btn')); if( !this.value && formAssociation.value ){ this.value = formAssociation.value; } } updated(changedProperties){ this.radios.map((radio) => { if( changedProperties.has('value') ){ const radioValue = radio.value; if(radioValue == this.value){ radio.setAttribute('checked', 'checked'); this.querySelector('.umoja-u-form-association').setAttribute('value', radioValue); }else if((radioValue != this.value) && radio.hasAttribute('checked')){ radio.removeAttribute('checked') } } if(changedProperties.has('name')){ radio.setAttribute('name', this.name); this.querySelector('.umoja-u-form-association').setAttribute('name', this.name); } if(changedProperties.has('theme')){ if(this.theme){ radio.setAttribute('theme', this.theme); }else if(!this.theme && radio.hasAttribute('theme')){ radio.removeAttribute('theme'); } } }); return changedProperties; } handleRadioButtonChange(e){ const newRadio = e.detail.radio; const oldRadio = this.radios.find(radio => radio.checked); this.manageRadios(oldRadio, newRadio); } handleRadioButtonKeyEvent(e){ let direction; const oldRadio = this.radios.find(radio => radio.checked); const oldRadioIndex = this.radios.findIndex(radio => radio.checked); switch (e.detail.key) { case 37 || 38: //up or left direction = -1; break; case 39 || 40: //down or right direction = 1; break; } const newRadio = this.radios[oldRadioIndex + direction]; this.manageRadios(oldRadio, newRadio); } manageRadios(oldRadio, newRadio) { if(!newRadio) return; const newValue = newRadio.value; const oldValue = this.value; if (oldValue !== newValue) { if( oldRadio ) oldRadio.checked = false; newRadio.checked = true; this.value = newValue; this.dispatchEvent( new CustomEvent('umoja-radio-btn-group-change', { bubbles: true, composed: true, detail: { value: newValue, }, }) ); } } render() { return html ` <slot></slot> `; } } window.customElements.define('umoja-radio-btn-group', UmojaRadioButtonGroup);<file_sep>/src/components/button/button.js import {LitElement, html} from 'lit'; import {classMap} from 'lit/directives/class-map.js'; import { ifDefined } from 'lit/directives/if-defined.js'; import styles from './button.styles.js'; /** * Button. * @element umoja-btn */ export default class UmojaButton extends LitElement { static get styles() { return [styles]; } static get properties() { return { kind: {type: String, reflect: true}, title: {type: String, reflect: true}, disabled: {type: Boolean, reflect: true}, href: {type: String, reflect: true}, target: {type: String, reflect: true}, submit: {type: Boolean, reflect: true}, download: {type: String}, icon: {type: String, reflect: true} }; } constructor() { super(); this.kind = 'primary'; this.disabled = false; this.submit = this.getAttribute('submit'); if(this.submit){ //TODO: future switch over to HTMLELement.attachInternals() method. Method only compatibile in Chrome as of 8/21 const formAssociation = `<button class="umoja-u-form-association" type="submit"></button>`; this.insertAdjacentHTML('afterbegin', formAssociation); } } connectedCallback() { super.connectedCallback(); } handleClick(e) { if (this.disabled) { e.preventDefault(); e.stopPropagation(); } if(this.submit){ this.querySelector('.umoja-u-form-association').click(); this.querySelector('.umoja-u-form-association').remove(); } } render() { const {title, kind, disabled, href, target, submit, download, icon, handleClick} = this; let iconLayout = icon; iconLayout = (title ? false : true); return href ? html` <a class=${classMap({ [`umoja-c-btn`]: true, [`umoja-c-btn--${kind}`]: kind, [`umoja-c-btn--disabled`]: disabled, [`umoja-c-btn--icon`]: iconLayout })} href=${ifDefined(href)} target=${ifDefined(target)} ?download=${ifDefined(download)} rel=${ifDefined(target ? 'noreferrer noopener' : undefined)} role="button" aria-disabled=${disabled ? 'true' : 'false'} tabindex=${disabled ? '-1' : '0'} @click=${handleClick} > ${icon ? html `<span class="material-icons">${icon}</span>`: ''} ${ifDefined(title)} </a> ` : html` <button type=${submit ? 'submit' : 'button'} class=${classMap({ [`umoja-c-btn`]: true, [`umoja-c-btn--${kind}`]: kind, [`umoja-c-btn--disabled`]: disabled, [`umoja-c-btn--icon`]: iconLayout })} ?disabled="${disabled}" @click=${handleClick} > ${icon ? html `<span class="material-icons">${icon}</span>`: ''} ${ifDefined(title)} </button> `; } } customElements.define('umoja-btn', UmojaButton); <file_sep>/stories/radio-button-group-story.js import {html} from 'lit-html'; import ifExists from '../src/utils/if-exists'; import {Default, Image} from './radio-button-story.js' import '../src/components/radio-button/radio-button.js'; import '../src/components/radio-button-group/radio-button-group.js'; export default { title: 'Components/Radio Button Group', component: 'umoja-radio-btn-group', parameters: { docs: { description: { component: '**<umoja-radio-btn-group>**', }, source: { type: 'code', } } }, argTypes: { name: { description: "Name of the radio button group. The set value will be applied to all child buttons within the button group.", control: { type: 'text', }, }, theme: { description: "The theme color of the child buttons. Default theme is dark mode.", table: { defaultValue: { summary: 'dark', }, }, options: ['dark','light'], control: { type: 'select', }, }, } }; export const DefaultGroup = (args) => { const{name, theme} = args; return html` <umoja-radio-btn-group name="${ifExists(name)}" theme="${ifExists(theme)}" > ${Default({...Default.args })} ${Default({...Default.args })} ${Default({...Default.args })} </umoja-radio-btn-group> `; } DefaultGroup.args ={ name: 'group_1' } DefaultGroup.parameters = { docs: { source: { code: ` <umoja-radio-btn-group name="group_1"> <umoja-radio-btn label="Radio Button" value="value1"></umoja-radio-btn> <umoja-radio-btn label="Radio Button" value="value2"></umoja-radio-btn> <umoja-radio-btn label="Radio Button" value="value3"></umoja-radio-btn> </umoja-radio-btn-group>` }, }, }; export const ImageGroup = (args) => { const{name, theme} = args; return html` <umoja-radio-btn-group name="${ifExists(name)}" theme="${ifExists(theme)}" > ${Image({...Image.args })} ${Image({...Image.args })} ${Image({...Image.args })} </umoja-radio-btn-group> `; } ImageGroup.args ={ name: 'group_1', theme: 'light' } ImageGroup.parameters = { docs: { source: { code: ` <umoja-radio-btn-group name="group_1" theme="light"> <umoja-radio-btn label="Radio Button" value="value1" style="--backgroundImg:url(edgecases_rain1.png);"></umoja-radio-btn> <umoja-radio-btn label="Radio Button" value="value2" style="--backgroundImg:url(edgecases_rain1.png);"></umoja-radio-btn> <umoja-radio-btn label="Radio Button" value="value3" style="--backgroundImg:url(edgecases_rain1.png);"></umoja-radio-btn> </umoja-radio-btn-group>` }, }, };<file_sep>/stories/button-story.js import {html} from 'lit-html'; import ifExists from '../src/utils/if-exists'; import '../src/components/button/button.js'; export default { title: 'Components/Button', component: 'umoja-btn', parameters: { docs: { description: { component: '**<umoja-btn>**', }, source: { type: 'code', } } }, argTypes: { title: { control: { type: 'text', }, }, kind: { options: ['primary', 'secondary'], table: { defaultValue: { summary: 'primary', }, }, control: { type: 'select', }, }, disabled: { description: 'Specifices if a button is disabled. When attribute is set, the button will be unusable and un-clickable.', table: { type: { summary: 'boolean', detail: '<umoja-btn disabled></umoja-btn>', }, }, control: { type: 'boolean', }, }, href: { description: 'If the href attribute is set the button will render as a link element.', control: { type: 'text', }, }, target: { description: 'Changes where the link should open. Requires href attribute to be set.', options: ['_blank', '_parent', '_self', '_top'], control: { type: 'select', }, }, download: { description: 'Specifies that the link target will be downloaded when the link is clicked. Requires href attribute to be set.', control: { type: 'text', }, }, submit: { description: 'Changes the button type attribute to type="submit".', table: { type: { summary: 'boolean', detail: '<umoja-btn submit></umoja-btn>', }, }, control: { type: 'boolean', }, }, icon: { description: 'Render a Material UI Icon in the button. Attribute value should be a valid Material Icon name.', control:{ type: 'text' } } }, }; const Template = ({ kind, title, disabled, href, target, download, submit, icon }) => html` <umoja-btn title=${ifExists(title)} kind=${ifExists(kind)} ?disabled=${disabled} href=${ifExists(href)} target=${ifExists(target)} download=${ifExists(download)} submit=${ifExists(submit)} icon=${ifExists(icon)} > </umoja-btn> `; export const Default = Template.bind({}); Default.args = { title: 'Button' }; Default.parameters = { docs: { source: { code: '<umoja-btn title="Button"></umoja-btn>', }, }, controls: { exclude: ['icon'] } }; export const Icon = Template.bind({}); Icon.args = { icon: 'home' }; Icon.parameters = { docs: { source: { code: '<umoja-btn icon="home"></umoja-btn>', }, }, } <file_sep>/README.md ## Building an Umoja component # CSS Architecture and class names The Umoja Design System uses a strict class naming convention. Keeping to this convention creates a modular system with better clarity, improved legibility, and avoids conflicts. This is all accomplished by combining 4 techniques: 1. a global namespace 2. class prefixes 3. pascal casing 4. BEM syntax The prefixes available are: b- (Base) for classes that add additional styling to base HTML elements c- (Component) for UI components, such as .umoja-c-btn l- (Layout) for layout-related styles, such as .umoja-l-grid__item or .umoja-l-input-group__item Based off of: [CSS Architecture for Design Systems](https://bradfrost.com/blog/post/css-architecture-for-design-systems/) ## Use an Umoja component This is a general guide to using umoja components. Refer to a component’s README or other documentation for specific details. To use a umoja component in your code: 1. From your project folder, install the component from npm. ```bash npm install umoja-web-components # requires node 10 & npm 6 or higher ``` 2. Import the component. In a JavaScript module: ```bash import {SomeComponent} from 'umoja-web-components'; ``` 3. Add the component to your application or component: ```bash <umoja-component></umoja-component> ``` ## Testing This sample modern-web.dev's [@web/test-runner](https://www.npmjs.com/package/@web/test-runner) along with Mocha, Chai, and some related helpers for testing. See the [modern-web.dev testing documentation](https://modern-web.dev/docs/test-runner/overview) for more information. Tests can be run with the `test` script: ```bash npm test ``` ## Linting Linting of JavaScript files is provided by [ESLint](eslint.org). In addition, [lit-analyzer](https://www.npmjs.com/package/lit-analyzer) is used to type-check and lint lit-html templates with the same engine and rules as lit-plugin. The rules are mostly the recommended rules from each project, but some have been turned off to make LitElement usage easier. The recommended rules are pretty strict, so you may want to relax them by editing `.eslintrc.json`. To lint the project run: ```bash npm run lint ``` ## Formatting [Prettier](https://prettier.io/) is used for code formatting. It has been pre-configured according to the Polymer Project's style. You can change this in `.prettierrc.json`. Prettier has not been configured to run when commiting files, but this can be added with Husky and and `pretty-quick`. See the [prettier.io](https://prettier.io/) site for instructions. ## Editing If you use VS Code, we highly reccomend the [lit-plugin extension](https://marketplace.visualstudio.com/items?itemName=runem.lit-plugin), which enables some extremely useful features for lit-html templates: - Syntax highlighting - Type-checking - Code completion - Hover-over docs - Jump to definition - Linting - Quick Fixes The project is setup to reccomend lit-plugin to VS Code users if they don't already have it installed. <file_sep>/test/button_test.js /** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ import { UmojaButton } from '../src/index.js'; import {fixture, html} from '@open-wc/testing'; const assert = chai.assert; suite('umoja-btn', () => { test('is defined', () => { const el = document.createElement('umoja-btn'); assert.instanceOf(el, UmojaButton); }); test('renders with default values', async () => { const el = await fixture(html`<umoja-btn title="Button"></umoja-btn>`); assert.shadowDom.equal( el, ` <button type="button" class="umoja-c-btn umoja-c-btn--primary">Button</button> ` ); }); test('renders with a set name', async () => { const el = await fixture(html`<umoja-btn title="Umoja"></umoja-btn>`); assert.shadowDom.equal( el, `<button type="button" class="umoja-c-btn umoja-c-btn--primary">Umoja</button>` ); }); test('handles a click', async () => { const el = await fixture(html`<umoja-btn title="Button"></umoja-btn>`); const button = el.shadowRoot.querySelector('button'); button.click(); await el.updateComplete; assert.shadowDom.equal( el, `<button type="button" class="umoja-c-btn umoja-c-btn--primary">Button</button>` ); }); test('styling applied', async () => { const el = await fixture(html`<umoja-btn title="Button"></umoja-btn>`); await el.updateComplete; assert.equal(getComputedStyle(el).height, 'auto'); }); }); <file_sep>/src/utils/if-exists.js import { ifDefined } from 'lit-html/directives/if-defined.js'; /** * Extention of `lit-html/directives/if-defined` which checks if given value is `null` or `undefined`. */ export default value => ifDefined(value ?? undefined);<file_sep>/src/components/button/button.styles.js import {css} from 'lit'; import globalCSS from '../../styles/global-styles.js'; export default css` ${globalCSS} .umoja-c-btn { display: inline-flex; align-items: center; justify-content: center; min-width: 75px; height: 30px; margin: 0; border: none; border-radius: 2px; padding: 0 16px; outline: none; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-size: 0.875rem; font-family: inherit; font-weight: 600; line-height: 1; text-decoration: none; vertical-align: bottom; position: relative; cursor: pointer; transition: all 0.15s linear; } .umoja-c-btn:active:enabled, .umoja-c-btn:focus:enabled { border: 1px solid var(--color-purple); box-shadow: 0px 0px 0px 3px rgba(73, 55, 120, 0.4); } .umoja-c-btn--primary { background-color: var(--color-charcoal3); color: var(--color-charcoal6); } .umoja-c-btn--primary:hover:enabled, .umoja-c-btn--primary:active:enabled, .umoja-c-btn--primary:focus:enabled { background-color: var(--color-charcoal4); color: #fff; } .umoja-c-btn--secondary { background-color: #fff; color: var(--color-charcoal2); } .umoja-c-btn--secondary:hover:enabled, .umoja-c-btn--secondary:active:enabled, .umoja-c-btn--secondary:focus:enabled { background-color: var(--color-charcoal7); } .umoja-c-btn--disabled, .umoja-c-btn:disabled { opacity: 0.6; cursor: not-allowed; } .umoja-c-btn--icon{ height: 36px; width: 36px; min-width: 0; } .umoja-c-btn .material-icons{ display: inline-block; margin-right: 4px; font-family: 'Material Icons'; font-weight: normal; font-style: normal; font-size: 1.25rem; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; -moz-osx-font-smoothing: grayscale; font-feature-settings: 'liga'; } .umoja-c-btn--icon .material-icons{ margin-right: 0; } `; <file_sep>/styles/README.md ## Umoja style foundations Umoja Foundations package containing: - Color scheme - Standard grid layout - Sass variables - Utility classes
30af19ddd5b53841230fb0747390bdece2d14ac1
[ "JavaScript", "Markdown" ]
17
JavaScript
aesimpson/umoja-design-system-archive
fab1e406ed6d7a3da324ae95bf048f1d085288ab
3abf961ccc1b5e2dd2e3b43217e8ebed1bb74888
refs/heads/master
<repo_name>einet/intranet-mannager<file_sep>/CMcast.h /* * CMcast.h * * Created on: Apr 8, 2014 * Author: zlx */ #ifndef CMCAST_H_ #define CMCAST_H_ #include <iostream> #include <sstream> #include <string> #include <boost/asio.hpp> #include "boost/bind.hpp" #include "boost/date_time/posix_time/posix_time_types.hpp" #include "boost/threadpool.hpp" #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <iomanip> #include "GzipProcess.h" #include <sys/types.h> #include <sys/wait.h> #include "JsonMsg.h" //const short multicast_port = 32001; const int max_message_count = 10; using namespace boost::threadpool; typedef boost::shared_ptr<pool> pool_ptr; typedef std::map<std::string, std::string> ssmap; extern pool_ptr workthread_pool_ptr; class CTimeout: public boost::enable_shared_from_this<CTimeout>, private boost::noncopyable { public: CTimeout(bool b) { flag = b; } ~CTimeout() { } bool get() { return flag; } void set(bool b) { flag = b; } private: bool flag; }; class CPidTimeout: public boost::enable_shared_from_this<CPidTimeout>, private boost::noncopyable { public: CPidTimeout(pid_t p) { flag = false; pid = p; } ~CPidTimeout() { } int killpid() { int status, retval = 0; //如果进程还在运行,则强制中断 if (0 == (waitpid(pid, &status, WNOHANG))) { printf("kill子进程:%d\n", pid); retval = kill(pid, SIGKILL); if (retval==0) { printf("等待子进程(%d)退出\n", pid); retval = waitpid(pid, &status, 0); if (WIFEXITED(status)) { printf("exited, status=%d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("killed by signal %d\n", WTERMSIG(status)); } else if (WIFSTOPPED(status)) { printf("stopped by signal %d\n", WSTOPSIG(status)); } else if (WIFCONTINUED(status)) { printf("continued\n"); } printf("子进程退出(%d):%d\n", pid,status); } else { printf("进程退出(%d)status:%d\n", pid, status); } } //通知调用进程结束 printf("子进程:%dend\n", pid); flag = true; return retval; } bool get() { return flag; } private: bool flag; pid_t pid; }; typedef boost::shared_ptr<CTimeout> tmout_ptr; typedef boost::shared_ptr<CPidTimeout> tpidmout_ptr; class CMcast: public boost::enable_shared_from_this<CMcast>, private boost::noncopyable { public: CMcast(boost::asio::io_service& io_service, const boost::asio::ip::address& listen_address, const boost::asio::ip::address& multicast_address, const short multicast_port = 32001); std::string get_remote_addr(); int get_remote_port(); void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd); void handle_send_to(const boost::system::error_code& error); void handle_timeout(const boost::system::error_code& error); void handle_sendheartbeat(const boost::system::error_code& error); void handle_send(const boost::system::error_code& error); void send_to(std::string msg, int flag = 0); void send_to(const string & sid, const string & cmd, std::string msg, int flag = 0); void start(); private: boost::asio::ip::udp::socket socket_; boost::asio::ip::udp::endpoint sender_endpoint_; enum { max_length = 8 * 1024 * 1024 }; boost::asio::ip::udp::endpoint endpoint_; boost::asio::ip::udp::endpoint listen_endpoint; boost::asio::deadline_timer timer_; boost::asio::deadline_timer heartbeattimer_; std::size_t inbound_data_size = 0; enum { header_length = 8 }; void process_data(JsonMsg_ptr j_ptr, const std::string& addr, const int& port, int flag); std::string outbound_header_; std::vector<char> inbound_data_; CGzipProcess_ptr m_zipptr; }; typedef boost::shared_ptr<boost::asio::deadline_timer> timer_ptr; typedef boost::shared_ptr<CMcast> CMcast_ptr; void print_data(JsonMsg_ptr j_ptr, const std::string& addr, const int& port, CMcast_ptr m_ptr, int flag); #endif /* CMCAST_H_ */ <file_sep>/readme.txt 主要用于集群服务的管理,维护,对话系统和其它应用系统日志信息的查看。系统通过web服务接受用户请求,根据请求的情况,通过组播发送操作命令,被请求的主机响应该请求,执行相关的指令,并把执行的结果返回给操作者。 系统支持常规的服务状况查询,内存使用,磁盘使用,进程服务状态;支持日志文件的检索和查看,通过日志文件知道应用服务的状况;系统支持文件的上传和下载服务,可以分享文件,或者升级远程的系统。 系统节点安装并启动本系统后,系统可以自动发现该节点,并可以把该节点加入到服务集群管理。 系统以图形的形式提供集群拓扑服务图,可以通过编辑人工分组,这样可以通过界面对指定的组进行管理和查询的服务。 安装本系统需要满足条件: 1、linux64位环境。 2、网络环境支持组播。 系统工作原理: 通过Web界面接受指令,指令通过组播发送到特定的端口,集群内的机器接受消息,根据指令消息的,对应的主机执行该命令,并把结果发送组播端口,服务器接收后推送到用户。 可以执行的消息通过正则表达式进行控制,满足则执行;否则作为聊天的消息发送。 Web页面对接受的消息进行处理,进行相关的展示。 1、文件列表; 2、文件查看; 3、日志文件查看等。 2014-10-22修改日志 系统完成了单IO条件下的服务集群监控管理程序 修改了异步传输时文件句柄复用的问题, 修改了异步传输文件的方式,采用先传文件头,然后再传递数据,解决了浏览器下载多媒体文件播放的问题,支持分段异步多线程的文件传递 支持多线程文件上传 完善了管道调用shell的系统。 系统完成了单IO条件下的服务集群监控管理程序 修改了异步传输时文件句柄复用的问题, 修改了异步传输文件的方式,采用先传文件头,然后再传递数据,解决了浏览器下载多媒体文件播放的问题,支持分段异步多线程的文件传递 支持多线程文件上传 完善了管道调用shell的系统. 2015-11-23 修改用户session的锁管理,从全局锁修改为每session id锁; 增加消息队列读写锁,全局。 增加对shell调用的终止管理,分为每seesion id,和全局,用户可以选择停止一些操作(tail cat find tar)等 修改页面增加对第三方系统的查询调用,可以显示第三方的用户使用情况等 <file_sep>/Release/subdir.mk ################################################################################ # Automatically-generated file. Do not edit! ################################################################################ # Add inputs and outputs from these tool invocations to the build variables CPP_SRCS += \ ../CFrame.cpp \ ../CMain.cpp \ ../CMcast.cpp \ ../GzipProcess.cpp \ ../JsonMsg.cpp \ ../reciver.cpp \ ../sender.cpp OBJS += \ ./CFrame.o \ ./CMain.o \ ./CMcast.o \ ./GzipProcess.o \ ./JsonMsg.o \ ./reciver.o \ ./sender.o CPP_DEPS += \ ./CFrame.d \ ./CMain.d \ ./CMcast.d \ ./GzipProcess.d \ ./JsonMsg.d \ ./reciver.d \ ./sender.d # Each subdirectory must supply rules for building sources it contributes %.o: ../%.cpp @echo 'Building file: $<' @echo 'Invoking: GCC C++ Compiler' g++ -I/home/zlx/boost_1_55_0 -O3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" @echo 'Finished building: $<' @echo ' ' <file_sep>/Debug/objects.mk ################################################################################ # Automatically-generated file. Do not edit! ################################################################################ USER_OBJS := LIBS := -lpthread -lrt -lz -lboost_system -lboost_thread -lboost_serialization -lboost_filesystem -lboost_iostreams -lboost_regex <file_sep>/web/main.cpp // // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2013 <NAME> (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <string> #include <boost/asio.hpp> #include "server.hpp" CWebSVR_ptr m_webSrv_Ptr; int webmain(const std::string& ip,const std::string& port,const std::string& doc) { try { m_webSrv_Ptr.reset(new http::server::server(ip, port, doc,4)); m_webSrv_Ptr->run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; } void stopwebsvr() { m_webSrv_Ptr->stop(); } <file_sep>/page/lib/commands.js function copy(one) { var two = {} for (var name in one) { two[name] = one[name] } return two } var commands = { collapse: { args: ['id', 'doCollapse'], apply: function (view, model) { model.setCollapsed(this.id, this.doCollapse) view.setCollapsed(this.id, this.doCollapse) view.goTo(this.id) }, undo: function (view, model) { model.setCollapsed(this.id, !this.doCollapse) view.setCollapsed(this.id, !this.doCollapse) view.goTo(this.id) }, }, newNode: { args: ['pid', 'index', 'text'], apply: function (view, model) { var cr = model.create(this.pid, this.index, this.text) this.id = cr.node.id view.add(cr.node, cr.before) view.startEditing(cr.node.id) }, undo: function (view, model) { var ed = view.editing view.remove(this.id) this.saved = model.remove(this.id) var nid = model.ids[this.pid].children[this.index-1] if (nid === undefined) nid = this.pid if (ed) { view.startEditing(nid) } else { view.setSelection([nid]) } }, redo: function (view, model) { var before = model.readd(this.saved) view.add(this.saved.node, before) } }, appendText: { args: ['id', 'text'], apply: function (view, model) { this.oldtext = model.ids[this.id].data.name model.appendText(this.id, this.text) view.appendText(this.id, this.text) }, undo: function (view, model) { model.setData(this.id, {name: this.oldtext}) view.setData(this.id, {name: this.oldtext}) } }, changeNode: { args: ['id', 'newdata'], apply: function (view, model) { this.olddata = copy(model.ids[this.id].data) model.setData(this.id, this.newdata) view.setData(this.id, this.newdata) view.goTo(this.id) }, undo: function (view, model) { model.setData(this.id, this.olddata) view.setData(this.id, this.olddata) view.goTo(this.id) } }, remove: { args: ['id'], apply: function (view, model) { var below = model.nextSibling(this.id) if (undefined === below) below = model.idAbove(this.id) this.saved = model.remove(this.id) view.remove(this.id) view.startEditing(below) }, undo: function (view, model) { var before = model.readd(this.saved) view.addTree(this.saved.node, before) } }, copy: { args: ['id'], apply: function (view, model) { model.clipboard = model.dumpData(this.id, true) }, undo: function (view, model) { } }, cut: { args: ['id'], apply: function (view, model) { var below = model.nextSibling(this.id) if (undefined === below) below = model.idAbove(this.id) model.clipboard = model.dumpData(this.id, true) this.saved = model.remove(this.id) view.remove(this.id) if (view.editing) { view.startEditing(below) } else { view.setSelection([below]) } }, undo: function (view, model) { var before = model.readd(this.saved) view.addTree(this.saved.node, before) } }, paste: { args: ['id'], apply: function (view, model) { var cr = model.importData(this.id, model.clipboard) , ed = view.editing this.newid = cr.node.id view.addTree(cr.node, cr.before) view.setCollapsed(cr.node.parent, false) model.setCollapsed(cr.node.parent, false) if (ed) { view.startEditing(this.newid) } else { view.setSelection([this.newid]) } }, undo: function (view, model) { this.saved = model.remove(this.newid) model.clipboard = this.saved view.remove(this.newid) }, redo: function (view, model) { var before = model.readd(this.saved) view.addTree(this.saved.node, before) } }, move: { args: ['id', 'pid', 'index'], apply: function (view, model) { this.opid = model.ids[this.id].parent this.oindex = model.ids[this.opid].children.indexOf(this.id) var before = model.move(this.id, this.pid, this.index) var parent = model.ids[this.opid] , lastchild = parent.children.length === 0 view.move(this.id, this.pid, before, this.opid, lastchild) view.goTo(this.id) }, undo: function (view, model) { var before = model.move(this.id, this.opid, this.oindex) , lastchild = model.ids[this.pid].children.length === 0 view.move(this.id, this.opid, before, this.pid, lastchild) view.goTo(this.id) } } } <file_sep>/web/ParserProcess.cpp /* * 模块名称: ParserProcess * 功能  : 处理字符串的转换 * 作者  : 张留学 * 日期  : 2013-04-07 * */ #include "ParserProcess.h" #include <iostream> #include <cctype> #include <algorithm> #include <vector> #include <string> #include <boost/regex.hpp> void trim2(string& str) { string::size_type pos = str.find_last_not_of(' '); if(pos != string::npos) { str.erase(pos + 1); pos = str.find_first_not_of(' '); if(pos != string::npos) str.erase(0, pos); } else str.erase(str.begin(), str.end()); } bool isdatestr(string str) { bool isdate = false; { //yyyy-MM-dd HH:mm:ss //str = "2103-10-03"; try { boost::regex regex1( "(\\d{2}|\\d{4})(?:\\-)?([0]{1}\\d{1}|[1]{1}[0-2]{1})(?:\\-)?([0-2]{1}\\d{1}|[3]{1}[0-1]{1})(?:\\s)?([0-1]{1}\\d{1}|[2]{1}[0-3]{1})(?::)?([0-5]{1}\\d{1})(?::)?([0-5]{1}\\d{1})"); boost::smatch what; if (boost::regex_search(str, what, regex1)) isdate = true; else isdate = false; } catch (const std::exception & ex) { std::cerr << ex.what() << std::endl; isdate = false; } /*if(str.length()==19) { if(str.find("-")!=std::string::npos && str.find(":")!=std::string::npos) { isdate = true; }else isdate = false; }*/ } return !isdate; } //转换时间字符串 namespace http { namespace server { CParserProcess::CParserProcess(void) : regex0("&", boost::regbase::normal | boost::regbase::icase) { } CParserProcess::~CParserProcess(void) { } //得到参数列表 parameterVect CParserProcess::getParameterVect(string & strParameter) { std::vector<std::string> value; mp.clear(); boost::regex_split(std::back_inserter(value), strParameter, regex0); for (int i = 0; i < (int) value.size(); i++) { header h; size_t sz = 0; sz = value[i].find_first_of("="); if (sz != std::string::npos) { h.name = value[i].substr(0, sz); h.value = value[i].substr(sz + 1); mp.push_back(h); } } return mp; } int processsdounry(char* p1, string& name, string& value, char *& fpos) { char * p = strstr(p1, "Content-Disposition: form-data; name="); if (p > 0) { p = p + 38; char * tp = strstr(p, "\""); char * rtp = strstr(p, "\r\n\r\n"); if (tp > 0) tp[0] = '\0'; name = p; if (name == "files[]") { char * filename = strstr(p + 8, "filename="); if (filename > 0) { filename = filename + 10; char * tp = strstr(filename, "\""); if (tp > 0) { tp[0] = '\0'; name = "filename"; char * p = strstr(filename, "\r\n"); if (p > 0) p[0] = '\0'; value = filename; fpos = rtp + 4; return 2; } } } else if (name == "filedata") { char * filename = strstr(p + 9, "filename="); if (filename > 0) { filename = filename + 10; char * tp = strstr(filename, "\""); if (tp > 0) { tp[0] = '\0'; name = "filename"; char * p = strstr(filename, "\r\n"); if (p > 0) p[0] = '\0'; value = filename; fpos = rtp + 4; return 2; } } } else { char * filename = strstr(p + 9, "filename="); if (filename > 0) { filename = filename + 10; char * tp = strstr(filename, "\""); if (tp > 0) { tp[0] = '\0'; name = "filename"; char * p = strstr(filename, "\r\n"); if (p > 0) p[0] = '\0'; value = filename; fpos = rtp + 4; return 2; } } } if (rtp > 0) { rtp = rtp + 4; char * p = strstr(rtp, "\r\n"); if (p > 0) p[0] = '\0'; value = rtp; } return 1; } return 0; } parameterVect CParserProcess::getUplodParameterVect(const string & strboundry, char* strParameter, const int len, char*& filestartpos) { //std::vector<std::string> value; //parameterVect mp; int size = strboundry.length(); mp.clear(); //按分解符号拆分 char * pp = strstr(strParameter, strboundry.c_str()); char * tp = NULL; if (pp > 0) { while (pp > 0) { pp = pp + size; tp = pp; pp = strstr(pp, strboundry.c_str()); if (pp > 0) { pp[0] = '\0'; } string name, value; header h; //查找第一个\r\n\r\n if (1 <= processsdounry(tp, h.name, h.value, filestartpos)) mp.push_back(h); } } return mp; } //获取cookie的值 parameterMap getParameterMap(string & strParameter) { std::vector<std::string> value; parameterMap mp; boost::regex regex1(";", boost::regbase::normal | boost::regbase::icase); boost::regex_split(std::back_inserter(value), strParameter, regex1); for (int i = 0; i < (int) value.size(); i++) { header h; size_t sz = 0; sz = value[i].find_first_of("="); if (sz != std::string::npos) { string str = value[i].substr(0, sz); string svalue = value[i].substr(sz + 1); trim2(str); trim2(svalue); mp[str] = svalue; } } return mp; } parameterMap getUplodParameterMap(string & strParameter) { std::vector<std::string> value; std::size_t last_dot_pos = strParameter.find_last_of("?"); if (last_dot_pos != std::string::npos) { strParameter = strParameter.substr(last_dot_pos + 1); } parameterMap mp; boost::regex regex1("&", boost::regbase::normal | boost::regbase::icase); boost::regex_split(std::back_inserter(value), strParameter, regex1); for (int i = 0; i < (int) value.size(); i++) { header h; size_t sz = 0; sz = value[i].find_first_of("="); if (sz != std::string::npos) { string str = value[i].substr(0, sz); string svalue = value[i].substr(sz + 1); trim2(str); trim2(svalue); mp[str] = svalue; } } return mp; } } } <file_sep>/start.sh #!/bin/bash export monitordir="/home/monitor" action=$1 action=${action##*/} kill_process() { NAME=$1 echo $NAME ID=`ps -ef | grep "$NAME" | grep -v "$0" | grep -v "grep" | awk '{print $2}'` echo $ID echo "---------------" for id in $ID do kill -9 $id while [[ $? != 0 ]]; do echo "killed $id" kill -9 $id done echo "killed $id" done echo "---------------" } copyfile() { cd "${monitordir}" if([ -f "Waiter1" ]); then echo "Copy" cp -f "Waiter1" "Waiter" else echo "Waiter1 No exist" fi chmod +x "Waiter" } start_waiter() { echo "startup Waiter" fuser -k -n tcp 8099 cd "${monitordir}" ./Waiter 0.0.0.0 172.16.58.3 8099 32000 ./page } kill_process "Waiter" copyfile start_waiter <file_sep>/web/server.hpp /* // server.hpp 系统采用单IO处理,可以扩展为多IO操作 */ #ifndef HTTP_SERVER_HPP #define HTTP_SERVER_HPP #include <boost/asio.hpp> #include <string> #include "connection.hpp" #include "connection_manager.hpp" #include "request_handler.hpp" #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include "io_service_pool.hpp" namespace http { namespace server { typedef boost::shared_ptr< boost::asio::ip::tcp::socket > socket_ptr; class server: public boost::enable_shared_from_this<server>, private boost::noncopyable { public: server(const server&) = delete; server& operator=(const server&) = delete; explicit server(const std::string& address, const std::string& port, const std::string& doc_root,std::size_t pool_size); void run(); void stop() { io_service_pool_.stop(); } private: void do_accept(); void do_await_stop(); io_service_pool io_service_pool_; boost::asio::signal_set signals_; boost::asio::ip::tcp::acceptor acceptor_; connection_manager connection_manager_; request_handler request_handler_; }; } // namespace server } // namespace http typedef boost::shared_ptr<http::server::server> CWebSVR_ptr; #endif // HTTP_SERVER_HPP <file_sep>/web/request_handler.cpp // // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 <NAME> (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" #include <sys/stat.h> #include "boost/format.hpp" #include "boost/lexical_cast.hpp" namespace http { namespace server { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } std::string request_handler::get_fullpath(const request& req, reply& rep,std::string& extension) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return ""; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return ""; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } if(request_path.find(doc_root_)==0) return request_path; // return full_path return doc_root_ + request_path; } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } //RANGE: bytes=2000070- //Content-Range=bytes 2000070-106786027/106786028 //接受完所有参数信息 int istart = -1; int iend = -1; for (int i = 0; i < (int) req.headers.size(); i++) { if (req.headers[i].name == "RANGE") { std::string mstr = req.headers[i].value; size_t so = mstr.find("bytes="); if (so != std::string::npos) { so = so + 6; size_t se = mstr.find("-"); if (se != std::string::npos) { istart = atoi(req.headers[i].value.c_str() + so); iend = atoi(req.headers[i].value.c_str() + se + 1); } } break; } } struct stat st; stat(full_path.c_str(), &st); size_t size = st.st_size; //如果长度大于1M则启用断点续传 if (istart == -1 || size <= 1024 * 1024) { rep.headers.resize(2); rep.status = reply::ok; char buf[1024]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } else { boost::format fmter("bytes %d-%d/%d"); fmter % "true" % 1 % size; char buf[1024]; bool first = false; if (istart > 0) is.seekg(istart); rep.headers.resize(3); rep.status = reply::partial_content; rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); rep.headers[2].name = "Content-Range"; rep.headers[2].value = std::to_string(rep.content.size()); int len = 0; int readlen = size; if (iend > 0) { readlen = iend - istart; if (readlen < 0) readlen = size; } while (readlen > 0) { int plen = 1024; if (readlen > 1024) { len = is.readsome(buf, 1024); } else { len = is.readsome(buf, readlen); plen = readlen; } readlen = readlen - len; if (!first) { rep.content.append(buf, is.gcount()); first = true; if (iend <= 0) { fmter % istart % (size - 1) % size; } else { fmter % istart % (iend - istart) % size; } } else { } } } } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server } // namespace http <file_sep>/CFrame.h /* * CFrame.cpp * * Created on: Mar 26, 2014 * Author: zlx */ #pragma once #include <boost/progress.hpp> #include "sstream" #define BOOST_SPIRIT_THREADSAFE #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> // utf8转换用 #include <boost/program_options/detail/convert.hpp> #include <boost/program_options/detail/utf8_codecvt_facet.hpp> #include <boost/asio.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/tuple/tuple.hpp> #include <iomanip> #include <string> #include <sstream> #include <vector> #include "boost/bind.hpp" #include "boost/date_time/posix_time/posix_time_types.hpp" #include "serialization_mcast.hpp" #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/export.hpp> struct JsonMessage { public: std::string getstring() { return json; } void setstring(std::string str) { json = str; } private: friend class boost::serialization::access; std::string json; template<typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(json); } }; typedef boost::shared_ptr<JsonMessage> JsonMessage_ptr; class CFrame: public boost::enable_shared_from_this<CFrame>, private boost::noncopyable { public: CFrame(boost::asio::io_service &p_ios, const std::string p_address, const std::string m_address, const std::string p_port); void send(JsonMessage_ptr p_mesg); void process_message(JsonMessage_ptr p_mesg); void start(); void read(); private: mcast_connection_ptr m_con_ptr; std::vector< JsonMessage_ptr > recvmsgs_; void handle_write(const boost::system::error_code& err); void handle_read(const boost::system::error_code& err ); boost::asio::io_service& m_ios; }; typedef boost::shared_ptr<CFrame> CFrame_ptr; <file_sep>/page/lib/json-to-table.js /** * JavaScript format string function * */ String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : '{' + number + '}'; }); }; function ConvertJsonToTable(parsedJson, tableId, tableClassName, linkText) { //Patterns for links and NULL value var italic = '<i>{0}</i>'; var link = linkText ? '<a href="{0}">' + linkText + '</a>' : '<a href="{0}">{0}</a>'; //Pattern for table var idMarkup = tableId ? ' id="' + tableId + '"' : ''; var classMarkup = tableClassName ? ' class="' + tableClassName + '"' : ''; var tbl = '<table width="80%" border="1" cellpadding="0" cellspacing="1"' + idMarkup + classMarkup + '>{0}{1}</table>'; //Patterns for table content var th = '<thead>{0}</thead>'; var tb = '<tbody>{0}</tbody>'; var tr = '<tr>{0}</tr>'; var thRow = '<th>{0}</th>'; var tdRow = '<td>{0}</td>'; var thCon = ''; var tbCon = ''; var trCon = ''; if (parsedJson) { var isStringArray = typeof (parsedJson[0]) == 'string'; var headers; // Create table headers from JSON data // If JSON data is a simple string array we create a single table header if (isStringArray) thCon += thRow.format('value'); else { // If JSON data is an object array, headers are automatically computed if (typeof (parsedJson[0]) == 'object') { headers = array_keys(parsedJson[0]); for (i = 0; i < headers.length; i++) thCon += thRow.format(headers[i]); } } th = th.format(tr.format(thCon)); // Create table rows from Json data if (isStringArray) { for (i = 0; i < parsedJson.length; i++) { tbCon += tdRow.format(parsedJson[i]); trCon += tr.format(tbCon); tbCon = ''; } } else { if (headers) { var urlRegExp = new RegExp(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig); var javascriptRegExp = new RegExp(/(^javascript:[\s\S]*;$)/ig); var i=0; var j=0; for (i = 0; i < parsedJson.length; i++) { for (j = 0; j < headers.length; j++) { var value = parsedJson[i][headers[j]]; var isUrl = urlRegExp.test(value) || javascriptRegExp.test(value); if (isUrl) // If value is URL we auto-create a link tbCon += tdRow.format(italic.format(value)); //tbCon += tdRow.format(link.format(value)); else { if (value) { if (typeof (value) == 'object') { //for supporting nested tables tbCon += tdRow.format(ConvertJsonToTable(eval(value.data), value.tableId, value.tableClassName, value.linkText)); } else { tbCon += tdRow.format(value); } } else { // If value == null we format it like PhpMyAdmin NULL values tbCon += tdRow.format(italic.format(value).toUpperCase()); } } } trCon += tr.format(tbCon); tbCon = ''; } } } tb = tb.format(trCon); tbl = tbl.format(th, tb); return tbl; } return null; } function array_keys(input, search_value, argStrict) { var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = ''; if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array return input.keys(search_value, argStrict); } for (key in input) { if (input.hasOwnProperty(key)) { include = true; if (search) { if (strict && input[key] !== search_value) include = false; else if (input[key] != search_value) include = false; } if (include) tmp_arr[tmp_arr.length] = key; } } return tmp_arr; } <file_sep>/page/lib/model.js function Model(root, ids, db) { this.ids = ids this.root = root this.db = db this.nextid = 100 this.clipboard = false } /** * A single node is * - id: * - parent: id * - children: [id, id, id] * - data: {} */ Model.prototype = { newid: function () { while (this.ids[this.nextid]) { this.nextid += 1 } var id = this.nextid this.nextid += 1 return id }, dumpData: function (id, noids) { if (arguments.length === 0) { id = this.root } var res = {} , n = this.ids[id] for (var name in n.data) { res[name] = n.data[name] } if (n.children.length) { res.children = [] for (var i=0; i<n.children.length; i++) { res.children.push(this.dumpData(n.children[i], noids)) } } if (!noids) res.id = id res.collapsed = n.collapsed return res }, importData: function (beforeId, data) { var bnode = this.ids[beforeId] , parent if ((bnode.children.length && !bnode.collapsed) || !bnode.parent) { pid = beforeId parent = bnode index = 0 } else { pid = bnode.parent parent = this.ids[pid] index = parent.children.indexOf(beforeId) + 1 } return this.createNodes(pid, index, data) /* var before = false if (index < parent.children.length - 1) { before = parent.children[index + 1] } return { node: node, before: beforeId } */ }, createNodes: function (pid, index, data) { var cr = this.create(pid, index, data.name) cr.node.collapsed = data.collapsed if (data.children) { for (var i=0; i<data.children.length; i++) { this.createNodes(cr.node.id, i, data.children[i]) } } return cr }, // operations create: function (pid, index, text) { var node = { id: this.newid(), data: {name: text || '', done: false}, parent: pid, children: [] } this.ids[node.id] = node this.ids[pid].children.splice(index, 0, node.id) var before = false if (index < this.ids[pid].children.length - 1) { before = this.ids[pid].children[index + 1] } // this.dom.add(node, before, this.bounds(node.id)) return { node: node, before: before } }, remove: function (id) { if (id === this.root) return var n = this.ids[id] , p = this.ids[n.parent] , ix = p.children.indexOf(id) p.children.splice(ix, 1) delete this.ids[id] return {id: id, node: n, ix: ix} }, setData: function (id, data) { for (var name in data) { this.ids[id].data[name] = data[name] } }, setCollapsed: function (id, isCollapsed) { this.ids[id].collapsed = isCollapsed }, isCollapsed: function (id) { return this.ids[id].collapsed }, hasChildren: function (id) { return this.ids[id].children.length }, // add back something that was removed readd: function (saved) { this.ids[saved.id] = saved.node var children = this.ids[saved.node.parent].children children.splice(saved.ix, 0, saved.id) var before = false if (saved.ix < children.length - 1) { before = children[saved.ix + 1] } return before }, move: function (id, pid, index) { var n = this.ids[id] , p = this.ids[n.parent] , ix = p.children.indexOf(id) p.children.splice(ix, 1) if (index === false) index = this.ids[pid].children.length this.ids[pid].children.splice(index, 0, id) this.ids[id].parent = pid var before = false if (index < this.ids[pid].children.length - 1) { before = this.ids[pid].children[index + 1] } return before }, appendText: function (id, text) { this.ids[id].data.name += text }, // movement calculation getParent: function (id) { return this.ids[id].parent }, getChild: function (id) { if (this.ids[id].children && this.ids[id].children.length) { return this.ids[id].children[0] } return this.nextSibling(id) }, prevSibling: function (id, noparent) { var pid = this.ids[id].parent if (undefined === pid) return var ix = this.ids[pid].children.indexOf(id) if (ix > 0) return this.ids[pid].children[ix-1] if (!noparent) return pid }, nextSibling: function (id) { var pid = this.ids[id].parent if (undefined === pid) return this.ids[id].children[0] var ix = this.ids[pid].children.indexOf(id) if (ix < this.ids[pid].children.length - 1) return this.ids[pid].children[ix + 1] return this.ids[id].children[0] }, lastSibling: function (id) { var pid = this.ids[id].parent if (undefined === pid) return this.ids[id].children[0] var ix = this.ids[pid].children.indexOf(id) if (ix === this.ids[pid].children.length - 1) return this.ids[id].children[0] return this.ids[pid].children[this.ids[pid].children.length - 1] }, firstSibling: function (id) { var pid = this.ids[id].parent if (undefined === pid) return // this.ids[id].children[0] var ix = this.ids[pid].children.indexOf(id) if (ix === 0) return pid return this.ids[pid].children[0] }, idAbove: function (id) { var pid = this.ids[id].parent , parent = this.ids[pid] if (!parent) return var ix = parent.children.indexOf(id) if (ix == 0) { return pid } var previd = parent.children[ix - 1] while (this.ids[previd].children && this.ids[previd].children.length && !this.ids[previd].collapsed) { previd = this.ids[previd].children[this.ids[previd].children.length - 1] } return previd }, // get the place to shift left to shiftLeftPlace: function (id) { var pid = this.ids[id].parent , parent = this.ids[pid] if (!parent) return var ppid = parent.parent , pparent = this.ids[ppid] if (!pparent) return var pix = pparent.children.indexOf(pid) return { pid: ppid, ix: pix + 1 } }, shiftUpPlace: function (id) { var pid = this.ids[id].parent , parent = this.ids[pid] if (!parent) return var ix = parent.children.indexOf(id) if (ix == 0) { var pl = this.shiftLeftPlace(id) if (!pl) return pl.ix -= 1 return pl } return { pid: pid, ix: ix - 1 } }, shiftDownPlace: function (id) { var pid = this.ids[id].parent , parent = this.ids[pid] if (!parent) return var ix = parent.children.indexOf(id) if (ix >= parent.children.length - 1) { return this.shiftLeftPlace(id) } return { pid: pid, ix: ix + 1 } }, moveBeforePlace: function (id, tid) { var sib = this.ids[id] , pid = sib.parent , opid = this.ids[tid].parent if (undefined === pid) return var parent = this.ids[pid] return { pid: pid, ix: parent.children.indexOf(id) } }, moveAfterPlace: function (id, oid) { var sib = this.ids[id] , pid = sib.parent , opid = this.ids[oid].parent if (undefined === pid) return var oix = this.ids[opid].children.indexOf(oid) var parent = this.ids[pid] , ix = parent.children.indexOf(id) + 1 if ( pid === opid && ix > oix) ix -= 1 return { pid: pid, ix: ix } }, idBelow: function (id) { if (this.ids[id].children && this.ids[id].children.length && !this.ids[id].collapsed) { return this.ids[id].children[0] } var pid = this.ids[id].parent , parent = this.ids[pid] if (!parent) return var ix = parent.children.indexOf(id) while (ix == parent.children.length - 1) { parent = this.ids[parent.parent] if (!parent) return ix = parent.children.indexOf(pid) pid = parent.id } return parent.children[ix + 1] }, idNew: function (id, before) { var pid = this.ids[id].parent , parent , nix if (before) { parent = this.ids[pid] nix = parent.children.indexOf(id) } else if (id === this.root || (this.ids[id].children && this.ids[id].children.length && !this.ids[id].collapsed)) { pid = id nix = 0 } else { parent = this.ids[pid] nix = parent.children.indexOf(id) + 1 } return { pid: pid, index: nix } }, samePlace: function (id, place) { var pid = this.ids[id].parent if (!pid || pid !== place.pid) return false var parent = this.ids[pid] , ix = parent.children.indexOf(id) return ix === place.ix }, findCollapser: function (id) { if ((!this.ids[id].children || !this.ids[id].children.length || this.ids[id].collapsed) && this.ids[id].parent !== undefined) { id = this.ids[id].parent } return id }, } <file_sep>/web/mime_types.cpp // // mime_types.cpp // ~~~~~~~~~~~~~~ //header('Content-Type: text/event-stream'); //header('Cache-Control: no-cache'); // #include "mime_types.hpp" #include <string> #include <boost/algorithm/string.hpp> extern void freshregx(); namespace http { namespace server { namespace mime_types { struct mapping { const char* extension; const char* mime_type; } mappings[] = { {"*","application/octet-stream"}, {"323","text/h323"}, {"action","text/html"}, {"acx","application/internet-property-stream"}, {"ai","application/postscript"}, {"aif","audio/x-aiff"}, {"aifc","audio/x-aiff"}, {"aiff","audio/x-aiff"}, {"asf","video/x-ms-asf"}, {"asp","text/html"}, {"asr","video/x-ms-asf"}, {"asx","video/x-ms-asf"}, {"au","audio/basic"}, {"avi","video/x-msvideo"}, {"axs","application/olescript"}, {"bas","text/plain"}, {"bcpio","application/x-bcpio"}, {"bin","application/octet-stream"}, {"bmp","image/bmp"}, {"c","text/plain"}, {"cat","application/vnd.ms-pkiseccat"}, {"call","text/html"}, {"cdf","application/x-cdf"}, {"cer","application/x-x509-ca-cert"}, {"class","application/octet-stream"}, {"clp","application/x-msclip"}, {"cmd","text/html"}, {"cmx","image/x-cmx"}, {"cod","image/cis-cod"}, {"cpio","application/x-cpio"}, {"crd","application/x-mscardfile"}, {"crl","application/pkix-crl"}, {"crt","application/x-x509-ca-cert"}, {"csh","application/x-csh"}, {"css","text/css"}, {"csp","text/html"}, {"dcr","application/x-director"}, {"der","application/x-x509-ca-cert"}, {"dir","application/x-director"}, {"dll","application/x-msdownload"}, {"dms","application/octet-stream"}, {"doc","application/msword"}, {"dot","application/msword"}, {"dvi","application/x-dvi"}, {"dxr","application/x-director"}, {"eps","application/postscript"}, {"etx","text/x-setext"}, {"evy","application/envoy"}, {"exe","application/octet-stream"}, {"fif","application/fractals"}, {"flr","x-world/x-vrml"}, {"flv","video/x-flv"}, {"gif","image/gif"}, {"gtar","application/x-gtar"}, {"gz","application/x-gzip"}, {"h","text/plain"}, {"hdf","application/x-hdf"}, {"hlp","application/winhlp"}, {"hqx","application/mac-binhex40"}, {"hta","application/hta"}, {"htc","text/x-component"}, {"htm","text/html"}, {"html","text/html"}, {"htt","text/webviewhtml"}, {"ico","image/x-icon"}, {"ief","image/ief"}, {"iii","application/x-iphone"}, {"ins","application/x-internet-signup"}, {"isp","application/x-internet-signup"}, {"jfif","image/pipeg"}, {"jpe","image/jpeg"}, {"jpeg","image/jpeg"}, {"jpg","image/jpeg"}, {"js","application/x-javascript"}, {"json","application/json"}, {"jsp","text/html"}, {"latex","application/x-latex"}, {"lha","application/octet-stream"}, {"lsf","video/x-la-asf"}, {"lsx","video/x-la-asf"}, {"lzh","application/octet-stream"}, {"m13","application/x-msmediaview"}, {"m14","application/x-msmediaview"}, {"m3u","audio/x-mpegurl"}, {"man","application/x-troff-man"}, {"mdb","application/x-msaccess"}, {"me","application/x-troff-me"}, {"mht","message/rfc822"}, {"mhtml","message/rfc822"}, {"mid","audio/mid"}, {"mny","application/x-msmoney"}, {"mov","video/quicktime"}, {"movie","video/x-sgi-movie"}, {"mobile","text/html"}, {"mp2","video/mpeg"}, {"mp3","audio/mpeg"}, {"mp4","video/mp4"}, {"mpa","video/mpeg"}, {"mpe","video/mpeg"}, {"mpeg","video/mpeg"}, {"mpg","video/mpeg"}, {"mpp","application/vnd.ms-project"}, {"mpv2","video/mpeg"}, {"ms","application/x-troff-ms"}, {"mvb","application/x-msmediaview"}, {"nws","message/rfc822"}, {"oda","application/oda"}, {"ola","text/html"}, {"p10","application/pkcs10"}, {"p12","application/x-pkcs12"}, {"p7b","application/x-pkcs7-certificates"}, {"p7c","application/x-pkcs7-mime"}, {"p7m","application/x-pkcs7-mime"}, {"p7r","application/x-pkcs7-certreqresp"}, {"p7s","application/x-pkcs7-signature"}, {"pbm","image/x-portable-bitmap"}, {"pdf","application/pdf"}, {"pfx","application/x-pkcs12"}, {"pgm","image/x-portable-graymap"}, {"php","text/html"}, {"pko","application/ynd.ms-pkipko"}, {"pma","application/x-perfmon"}, {"pmc","application/x-perfmon"}, {"pml","application/x-perfmon"}, {"pmr","application/x-perfmon"}, {"pmw","application/x-perfmon"}, {"png","image/png"}, {"pnm","image/x-portable-anymap"}, {"pot,","application/vnd.ms-powerpoint"}, {"ppm","image/x-portable-pixmap"}, {"pps","application/vnd.ms-powerpoint"}, {"ppt","application/vnd.ms-powerpoint"}, {"prf","application/pics-rules"}, {"ps","application/postscript"}, {"pub","application/x-mspublisher"}, {"qt","video/quicktime"}, {"ra","audio/x-pn-realaudio"}, {"ram","audio/x-pn-realaudio"}, {"rar","application/x-rar-compressed"}, {"ras","image/x-cmu-raster"}, {"regex","text/html"}, {"rgb","image/x-rgb"}, {"rmi","audio/mid"}, {"rmvb","application/vnd.rn-realmedia-vbr"}, {"roff","application/x-troff"}, {"rtf","application/rtf"}, {"rtx","text/richtext"}, {"scd","application/x-msschedule"}, {"sct","text/scriptlet"}, {"setpay","application/set-payment-initiation"}, {"setreg","application/set-registration-initiation"}, {"sh","application/x-sh"}, {"shar","application/x-shar"}, {"sit","application/x-stuffit"}, {"snd","audio/basic"}, {"solr","text/html"}, {"spc","application/x-pkcs7-certificates"}, {"spl","application/futuresplash"}, {"src","application/x-wais-source"}, {"sst","application/vnd.ms-pkicertstore"}, {"stl","application/vnd.ms-pkistl"}, {"stm","text/html"}, {"svg","image/svg+xml"}, {"sv4cpio","application/x-sv4cpio"}, {"sv4crc","application/x-sv4crc"}, {"swf","application/x-shockwave-flash"}, {"t","application/x-troff"}, {"tar","application/x-tar"}, {"tcl","application/x-tcl"}, {"tes","text/event-stream"}, {"tex","application/x-tex"}, {"texi","application/x-texinfo"}, {"texinfo","application/x-texinfo"}, {"tgz","application/x-compressed"}, {"tif","image/tiff"}, {"tiff","image/tiff"}, {"tr","application/x-troff"}, {"trm","application/x-msterminal"}, {"tsv","text/tab-separated-values"}, {"txt","text/plain"}, {"uls","text/iuls"}, {"action","text/html"}, {"upload","application/x-ustar"}, {"vcf","text/x-vcard"}, {"vrml","x-world/x-vrml"}, {"wav","audio/x-wav"}, {"wcm","application/vnd.ms-works"}, {"wdb","application/vnd.ms-works"}, {"wks","application/vnd.ms-works"}, {"wmf","application/x-msmetafile"}, {"woff""application/x-woff"}, {"wps","application/vnd.ms-works"}, {"wri","application/x-mswrite"}, {"wrl","x-world/x-vrml"}, {"wrz","x-world/x-vrml"}, {"xaf","x-world/x-vrml"}, {"xbm","image/x-xbitmap"}, {"xla","application/vnd.ms-excel"}, {"xlc","application/vnd.ms-excel"}, {"xlm","application/vnd.ms-excel"}, {"xls","application/vnd.ms-excel"}, {"xlt","application/vnd.ms-excel"}, {"xlw","application/vnd.ms-excel"}, {"xml","application/xml"}, {"xof","x-world/x-vrml"}, {"xpm","image/x-xpixmap"}, {"xwd","image/x-xwindowdump"}, {"z","application/x-compress"}, {"zip","application/zip"}, { 0, 0 } // Marks end of list. }; std::string extension_to_type(const std::string& extension) { if (extension.empty()) { return "application/octet-stream"; } std::string s = boost::to_lower_copy(extension); for (mapping m : mappings) { if (m.extension == NULL) { return "application/octet-stream"; } else if (m.extension == s) { if ("regex" == m.extension) { freshregx(); } return m.mime_type; } } return "text/plain"; } } // namespace mime_types } // namespace server } // namespace http <file_sep>/web/SeessionID.cpp /* * SeessionID.cpp * * Created on: Apr 28, 2014 * Author: zlx */ #include "SeessionID.h" #include <boost/regex.hpp> #include "../JsonMsg.h" Lock myLock; Lock msgLock; SeessionID m_sessionID; Lock cmdUnLock; bool gUnlockflag = false; SeessionID::SeessionID() { kki = 0; } SeessionID::~SeessionID() { } std::string SeessionID::GetIPAddr(const std::string & sid) { ReadLock r_lock(myLock); return ptrsmap[sid].ipaddr; } bool SeessionID::GetUnlock() { ReadLock r_lock(cmdUnLock); return gUnlockflag; } void SeessionID::SetUnlock(bool val) { WriteLock r_lock(cmdUnLock); std::cout<<"SetUnlock"<<val <<std::endl; gUnlockflag = val; } std::string SeessionID::ReadFunction(std::string sid) { std::string msg; bool num = false; ReadLock r_lock_msg(msgLock); if (mmap.size() > 0) { int pknum = ptrsmap[sid].i; int id = pknum; for (msgMap::const_iterator i = mmap.begin(), e = mmap.end(); i != e; ++i) { if (i->i <= id) continue; msg += i->msg; msg += ","; num = true; pknum = i->i; } ptrsmap[sid].i = pknum; } if (num) { msg = msg.substr(0, msg.length() - 1); } msg = "[" + msg; msg = msg + "]"; return msg; } void SeessionID::Clear() { SetUnlock(true); { WriteLock w_lock1(msgLock); mmap.clear(); } { WriteLock w_lock(myLock); ptrsmap.clear(); } } void SeessionID::Clear(const std::string & sid) { WriteLock w_lock(myLock); ptrsmap[sid].ptr_s.clear(); } Ptr_strVector SeessionID::GetVect(const std::string & sid) { ReadLock r_lock(myLock); return ptrsmap[sid].ptr_s; } void SeessionID::SetKillFlag(const std::string & sid, bool flag) { WriteLock w_lock(myLock); //std::cout<<"set killflag:"<<sid<<" "<<flag <<std::endl; ptrsmap[sid].killflag = flag; } bool SeessionID::GetKillFlag(const std::string & sid) { ReadLock r_lock(myLock); //std::cout<<"get killflag:"<<sid<<" "<< ptrsmap[sid].killflag<<std::endl; return ptrsmap[sid].killflag; } void SeessionID::push_back(const std::string & sid, const std::string str) { WriteLock w_lock(myLock); std::vector<std::string> value; boost::regex regex1(" ", boost::regbase::normal | boost::regbase::icase); std::string mstr = str; boost::regex_split(std::back_inserter(value), mstr, regex1); for (int i = 0; i < (int) value.size(); i++) { if (!value[i].empty()) { if (ptrsmap[sid].ptr_s.empty()) { ptrsmap[sid].ptr_s.push_back(value[i]); } else { bool find = false; for (unsigned int j = 0; j < ptrsmap[sid].ptr_s.size(); j++) { if (ptrsmap[sid].ptr_s[j] == value[i]) { find = true; break; } } if (!find) { ptrsmap[sid].ptr_s.push_back(value[i]); } } } } } void SeessionID::WriteFunction(std::string msg) { WriteLock w_lock(msgLock); //保留2000条消息,删除最早的1000条 if (mmap.size() > 2000) { mmap.erase(mmap.begin(),mmap.begin()+1000); } msgstruct_ptr smsg(new msgstruct()); smsg->i = kki; smsg->msg = msg; mmap.push_back(smsg); kki = kki + 1; } void SeessionID::WriteHostInfo(const std::string& sid, const std::string& hostname) { WriteLock w_lock(myLock); ptrsmap[sid].ptr_s.push_back(hostname); } Ptr_strVector SeessionID::GetHostInfo(const std::string& sid) { ReadLock r_lock(myLock); return ptrsmap[sid].ptr_s; } <file_sep>/page/lib/dom-vl.js function ensureInView(item) { var bb = item.getBoundingClientRect() if (bb.top < 0) return item.scrollIntoView() if (bb.bottom > window.innerHeight) { item.scrollIntoView(false) } } function DropShadow(height) { this.node = document.createElement('div') this.node.classList.add('listless__drop-shadow') this.height = height || 10 document.body.appendChild(this.node) } DropShadow.prototype = { moveTo: function (target) { this.node.style.top = target.show.y - this.height/2 + 'px' this.node.style.left = target.show.left + 'px' this.node.style.height = this.height + 'px' // this.node.style.height = target.height + 10 + 'px' this.node.style.width = target.show.width + 'px' }, remove: function () { this.node.parentNode.removeChild(this.node) } } function DomViewLayer(o) { this.dom = {} this.root = null this.o = o } DomViewLayer.prototype = { dropTargets: function (root, model, moving, top) { var targets = [] , bc = this.dom[root].head.getBoundingClientRect() , target , childTarget if (!top) { target = { id: root, top: bc.top, left: bc.left, width: bc.width, height: bc.height, place: 'after', // 'before', show: { left: bc.left,// + 20, width: bc.width,// - 20, y: bc.bottom } } if (model.ids[root].children.length && !model.isCollapsed(root)) { // show insert below children target.show.y = this.dom[root].ul.getBoundingClientRect().bottom } targets.push(target) } if (root === moving) return targets childTarget = { id: root, top: bc.bottom - 7, left: bc.left + 20, width: bc.width, place: 'child', show: { left: bc.left + 40, width: bc.width - 40, y: bc.top + bc.height }, height: 7 } targets.push(childTarget) if (model.isCollapsed(root)) return targets var ch = model.ids[root].children for (var i=0; i<ch.length; i++) { targets = targets.concat(this.dropTargets(ch[i], model, moving)) } return targets }, makeDropShadow: function () { return new DropShadow() }, remove: function (id, pid, lastchild) { var n = this.dom[id] n.main.parentNode.removeChild(n.main) delete this.dom[id] if (lastchild) { this.dom[pid].main.classList.add('listless__item--parent') } }, addNew: function (node, bounds, before) { var dom = this.makeNode(node.id, node.data, bounds) this.add(node.parent, before, dom) if (node.collapsed && node.children.length) { this.setCollapsed(node.id, true) } }, add: function (parent, before, dom) { var p = this.dom[parent] if (before === false) { p.ul.appendChild(dom) } else { var bef = this.dom[before] p.ul.insertBefore(dom, bef.main) } p.main.classList.add('listless__item--parent') }, body: function (id) { return this.dom[id].body }, move: function (id, pid, before, ppid, lastchild) { var d = this.dom[id] d.main.parentNode.removeChild(d.main) if (lastchild) { this.dom[ppid].main.classList.remove('listless__item--parent') } if (before === false) { this.dom[pid].ul.appendChild(d.main) } else { this.dom[pid].ul.insertBefore(d.main, this.dom[before].main) } this.dom[pid].main.classList.add('listless__item--parent') }, clearSelection: function (selection) { for (var i=0; i<selection.length; i++) { if (!this.dom[selection[i]]) continue; this.dom[selection[i]].main.classList.remove('selected') } }, showSelection: function (selection) { if (!selection.length) return ensureInView(this.dom[selection[0]].body.node) for (var i=0; i<selection.length; i++) { this.dom[selection[i]].main.classList.add('selected') } }, setCollapsed: function (id, isCollapsed) { this.dom[id].main.classList[isCollapsed ? 'add' : 'remove']('collapsed') }, setMoving: function (id, isMoving) { this.root.classList[isMoving ? 'add' : 'remove']('moving') this.dom[id].main.classList[isMoving ? 'add' : 'remove']('moving') }, setDropping: function (id, isDropping, isChild) { var cls = 'dropping' + (isChild ? '-child' : '') this.dom[id].main.classList[isDropping ? 'add' : 'remove'](cls) }, makeRoot: function (id, data, bounds) { var node = this.makeNode(id, data, bounds) , root = document.createElement('div') root.classList.add('listless') root.appendChild(node) this.root = root return root }, makeNode: function (id, data, bounds) { var dom = document.createElement('li') , head = document.createElement('div') , body = this.bodyFor(id, data, bounds) , collapser = document.createElement('div') , mover = document.createElement('div') collapser.addEventListener('mousedown', function () {bounds.toggleCollapse()}) collapser.classList.add('listless__collapser') mover.addEventListener('mousedown', function (e) { e.preventDefault() e.stopPropagation() bounds.startMoving() return false }) mover.classList.add('listless__mover') dom.classList.add('listless__item') dom.appendChild(head) head.classList.add('listless__head') head.appendChild(collapser) head.appendChild(body.node); head.appendChild(mover) var ul = document.createElement('ul') ul.classList.add('listless__children') dom.appendChild(ul) this.dom[id] = {main: dom, body: body, ul: ul, head: head} return dom }, /** returns a dom node **/ bodyFor: function (id, data, bounds) { var dom = new this.o.node(data, bounds) dom.node.classList.add('listless__body') return dom }, } <file_sep>/web/connection_manager.cpp // // connection_manager.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 <NAME> (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // //2015-12-07 增加写锁,发现有崩溃现象 #include "connection_manager.hpp" #include <boost/thread/locks.hpp> #include <boost/thread/pthread/shared_mutex.hpp> typedef boost::shared_mutex connection_Lock; typedef boost::unique_lock<connection_Lock> WriteConnLock; typedef boost::shared_lock<connection_Lock> ReadConnLock; connection_Lock connUnLock; namespace http { namespace server { connection_manager::connection_manager() { } void connection_manager::start(connection_ptr c) { WriteConnLock W_lock(connUnLock); connections_.insert(c); c->start(); } void connection_manager::stop(connection_ptr c) { WriteConnLock W_lock(connUnLock); connections_.erase(c); c->stop(); } void connection_manager::stop_all() { WriteConnLock W_lock(connUnLock); for (auto c : connections_) c->stop(); connections_.clear(); } } // namespace server } // namespace http <file_sep>/check_mp.sh #!/bin/bash opt=$1 echo "Monitor $opt" echo "172.16.10.11:" `/home/monitor/check_mp -H 172.16.10.111 -t $opt` echo "172.16.10.12:" `/home/monitor/check_mp -H 172.16.10.112 -t $opt` echo "172.16.10.14:" `/home/monitor/check_mp -H 172.16.10.113 -t $opt` echo "172.16.10.14:" `/home/monitor/check_mp -H 172.16.10.114 -t $opt` echo "172.16.10.15:" `/home/monitor/check_mp -H 172.16.10.115 -t $opt` echo "172.16.10.16:" `/home/monitor/check_mp -H 172.16.10.116 -t $opt` echo "172.16.10.17:" `/home/monitor/check_mp -H 172.16.10.117 -t $opt` echo "172.16.10.18:" `/home/monitor/check_mp -H 172.16.10.118 -t $opt` <file_sep>/CMcast.cpp /* * CMcast.cpp * * Created on: Apr 8, 2014 * Author: zlx * * bugfix:修改popen打开文件read时无法终止的问题 * 单独io时,持续执行脚本时存在无法接受数据的问题 */ #include "CMcast.h" #include <boost/algorithm/string/replace.hpp> #include "JsonMsg.h" #include <boost/algorithm/string.hpp> #include "web/SeessionID.h" using namespace std; using namespace boost::algorithm; char hname[1024]; extern boost::asio::io_service io_service; extern boost::asio::io_service work_io_service; //主机列表 ssmap mapHost; std::string cmdcache; std::string hostcache; std::vector<std::string> hostvec; extern SeessionID m_sessionID; //增加对主机列表的读写锁,防止线程crash Lock ssmapLock; bool boolall = false; #define READ 0 #define WRITE 1 #define ERR 2 /*pid_t popen2(const char **command, int *infp, int *outfp) { int p_stdin[2], p_stdout[2]; pid_t pid; if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0) return -1; pid = fork(); if (pid < 0) return pid; else if (pid == 0) { close(p_stdin[WRITE]); dup2(p_stdin[READ], READ); close(p_stdout[READ]); dup2(p_stdout[WRITE], WRITE); execvp(*command, command); perror("execvp"); exit(1); } if (infp == NULL) close(p_stdin[WRITE]); else *infp = p_stdin[WRITE]; if (outfp == NULL) close(p_stdout[READ]); else *outfp = p_stdout[READ]; return pid; }*/ pid_t popen2(const char *command, int *infp, int *outfp) { int p_stdin[2], p_stdout[2]; pid_t pid; if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0) return -1; pid = fork(); //printf("child %4d %4d %4d/n", getppid(), getpid(), pid); if (pid < 0) return pid; else if (pid == 0) { close(p_stdin[WRITE]); dup2(p_stdin[READ], READ); close(p_stdout[READ]); dup2(p_stdout[WRITE], WRITE); dup2(p_stdout[WRITE], ERR); execl("/bin/sh", "sh", "-c", command, NULL); perror("execl"); exit(1); } if (infp == NULL) close(p_stdin[WRITE]); else *infp = p_stdin[WRITE]; if (outfp == NULL) close(p_stdout[READ]); else *outfp = p_stdout[READ]; return pid; } std::string gethoststr() { hostcache.clear(); BOOST_FOREACH( const std::vector<std::string>::value_type &iter, hostvec ) { hostcache += iter + " "; } return hostcache; } void console_input(CMcast_ptr m_ptr) { gethostname(hname, sizeof(hname)); std::cout << "[" << hname << "]>(Ctrl+C)" << std::endl; while (true) { std::string cmd; std::getline(std::cin, cmd); boost::algorithm::trim(cmd); if (!cmd.empty()) { if (cmd == "get host") { ReadLock r_lock(ssmapLock); BOOST_FOREACH( const ssmap::value_type &iter, mapHost ) { std::cout << "host:" << iter.first << " IP:" << iter.second << std::endl; } std::cout << "[" << hname << ":" << gethoststr() << "]>" << std::endl; } else if (cmd == "set host") { std::cout << "Please hostname(Quit set host(quit)):"; while (1) { std::cout << "[" << hname << ":" << gethoststr() << "](Quit set host(quit))>" << std::endl; std::getline(std::cin, cmd); boost::algorithm::trim(cmd); if (cmd == "quit" || cmd == "q" || cmd == "Q") { std::cout << "[" << hname << ":" << gethoststr() << "]>" << std::endl; break; } else if (cmd == "clear") { hostvec.clear(); } else if (cmd == "all") { bool b = false; for (unsigned int i = 0; i < hostvec.size(); ++i) { if (hostvec[i] == cmd) { b = true; } } if (!b) hostvec.push_back(cmd); } else if (cmd == "del") { std::cout << "Please input (del) hostname:" << std::endl; std::getline(std::cin, cmd); boost::algorithm::trim(cmd); for (vector<std::string>::iterator it = hostvec.begin(); it != hostvec.end();) { if (*it == cmd) { it = hostvec.erase(it); } else { ++it; } } std::cout << "[" << hname << ":" << gethoststr() << "](Quit set host(quit))>" << std::endl; } else { bool f = false; ReadLock r_lock(ssmapLock); BOOST_FOREACH( const ssmap::value_type &iter, mapHost ) { if (iter.first == cmd) { f = true; break; } } if (!f) { std::cout << "This host No exists!(Quit set host(quit))" << std::endl; continue; } f = false; for (unsigned int i = 0; i < hostvec.size(); ++i) { if (hostvec[i] == cmd) { std::cout << "This host exists!(Quit set host(quit))" << std::endl; f = true; break; } } if (!f) hostvec.push_back(cmd); } } } else if (cmd == "msg") { std::cout << "Please input msg(Quit msg(quit)):"; while (1) { std::cout << "[" << hname << ":" << gethoststr() << "](Quit set host(quit))>" << std::endl; std::getline(std::cin, cmd); boost::algorithm::trim(cmd); if (cmd == "quit" || cmd == "q" || cmd == "Q") { std::cout << "[" << hname << ":" << gethoststr() << "]>" << std::endl; break; } else { m_ptr->send_to(cmd, 2); std::cout << "[" << hname << ":" << gethoststr() << "]>" << std::endl; std::cout << "Please input msg(Quit msg(quit)):" << std::endl; } } } else { m_ptr->send_to(cmd, 0); std::cout << "[" << hname << ":" << gethoststr() << "]>" << std::endl; } } } } void ztimeout(const boost::system::error_code& error, tmout_ptr m_ptr) { cout << "ztimeout:" << error << endl; if (!error) { m_ptr->set(true); } } void zpidtimeout(const boost::system::error_code& error, tpidmout_ptr m_ptr) { cout << "ztimeout:" << error.message() << endl; if (!error) { m_ptr->killpid(); } } //设置为非阻塞读取数据,加上超时1秒的设计 extern void stopwebsvr(); void callpid_sh(const std::string& sid, const std::string& script, CMcast_ptr m_ptr) { //开启定时器 timer_ptr m_t_p(new boost::asio::deadline_timer(io_service)); int infp = 0; int fp = 0; pid_t pid = 0; char result_buf[2048 * 4]; int timeout = 50; try { if (script.find("tail", 0) == 0 || script.find("tar", 0) == 0 || script.find("./package.sh", 0) == 0 || script.find("cat", 0) == 0 || script.find("find", 0) == 0) { timeout = 300; pid = popen2(script.c_str(), &infp, &fp); } else { pid = popen2(script.c_str(), &infp, &fp); } tpidmout_ptr m_tptr(new CPidTimeout(pid)); m_t_p->expires_from_now(boost::posix_time::seconds(timeout)); m_t_p->async_wait( boost::bind(&zpidtimeout, boost::asio::placeholders::error, m_tptr)); if (fp == 0) { return; } int d = fp; //设置非阻塞模式读取信息,保证信息的快速读取 int flags; flags = fcntl(d, F_GETFL); flags |= O_NONBLOCK; fcntl(d, F_SETFL, flags); ssize_t r = 0; std::cout << "Recv cmd:" << script << ",pid:" << pid << std::endl; while (true) { //是否接收到全局的停止信号,防止用户持续调用后,忘记关闭(例如 tail -f之类的操作) if (m_sessionID.GetUnlock()) { std::cout << " Recv unlock sig!" << script << "pid:" << pid << std::endl; close(infp); close(fp); m_t_p->cancel(); m_tptr->killpid(); break; } //是否接受到用户的停止信号 if (m_sessionID.GetKillFlag(sid)) { std::cout << " Recv kill sig!" << script << "pid:" << pid << std::endl; close(infp); close(fp); m_t_p->cancel(); m_tptr->killpid(); break; } ::usleep(50); r = ::read(d, result_buf, sizeof(result_buf)); if (r > 0) { result_buf[r] = '\0'; //通过组播发送信息 m_ptr->send_to(sid, script, result_buf, 1); //接受到数据重新设置定时器超时时间 m_t_p->cancel(); m_t_p->expires_from_now(boost::posix_time::seconds(timeout)); m_t_p->async_wait( boost::bind(&zpidtimeout, boost::asio::placeholders::error, m_tptr)); continue; } else if (r == -1 && errno != EAGAIN) { //取消定时器,结束读取 m_t_p->cancel(); close(infp); close(fp); break; } int status = 0; //检查调用的线程是否运行结束 if (pid == waitpid(pid, &status, WNOHANG)) { printf("子进程:%d,end.\n", pid); m_t_p->cancel(); close(infp); close(fp); break; } //检查定时器是否已经启动运行 if (m_tptr->get()) { m_t_p->cancel(); close(infp); close(fp); break; } if (errno == EAGAIN) { //暂时没有数据,可以继续等待,直到有数据或者定时器超时 continue; } } } catch (...) { std::cout << "error!" << std::endl; return; } } #include "./web/SeessionID.h" extern SeessionID m_sessionID; void print_data(JsonMsg_ptr j_ptr, const std::string& addr, const int& port, CMcast_ptr m_ptr, int flag) { stringstream msg; if (flag == 0) { std::cout << "Recv from: " << j_ptr->GetHost() << " IP " << addr << " port:" << port << ", cmd:" << std::endl << j_ptr->GetCmd() << std::endl; if (j_ptr->invect(hname)) callpid_sh(j_ptr->sid, j_ptr->GetCmd(), m_ptr); else std::cout << "[" << hname << "]>(Ctrl+C)" << std::endl; msg << "{" << "\"sid\":\"" << j_ptr->sid << "\",\"host\":\"" << j_ptr->GetHost() << "\",\"ip\":\"" << addr << "\",\"port\":\"" << port << "\",\"flag\":0,\"cmd\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetCmd()) << "\",\"result\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetCmd()) << "\"}"; } else if (flag == 1) { std::cout << "Recv from: " << j_ptr->GetHost() << " IP " << addr << " port:" << port << ", result:" << std::endl << j_ptr->GetResult() << std::endl; std::cout << "[" << hname << "]>(Ctrl+C)" << std::endl; msg << "{" << "\"sid\":\"" << j_ptr->sid << "\",\"host\":\"" << j_ptr->GetHost() << "\",\"ip\":\"" << addr << "\",\"port\":\"" << port << "\",\"flag\":1,\"cmd\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetCmd()) << "\",\"result\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetResult()) << "\"}"; } else if (flag == 2) { std::cout << "Recv from: " << j_ptr->GetHost() << " IP " << addr << " port:" << port << ", msg:" << std::endl << " " << j_ptr->GetResult() << std::endl; msg << "{" << "\"sid\":\"" << j_ptr->sid << "\",\"host\":\"" << j_ptr->GetHost() << "\",\"ip\":\"" << addr << "\",\"port\":\"" << port << "\",\"flag\":2,\"cmd\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetCmd()) << "\",\"result\":\"" << boost::property_tree::json_parser::create_escapes( j_ptr->GetResult()) << "\"}"; std::cout << "[" << hname << ":" << gethoststr() << "]>" << "Please input msg(Quit msg(quit)):" << std::endl; } else if (flag == 3) { } else { return; } if (flag != 3) m_sessionID.WriteFunction(msg.str()); } CMcast::CMcast(boost::asio::io_service& io_service, const boost::asio::ip::address& listen_address, const boost::asio::ip::address& multicast_address, const short multicast_port) : listen_endpoint(listen_address, multicast_port), socket_(io_service), timer_( io_service), heartbeattimer_(io_service), endpoint_( multicast_address, multicast_port), m_zipptr(new CGzipProcess()) { inbound_data_.resize(max_length); socket_.open(listen_endpoint.protocol().v4()); socket_.set_option( boost::asio::ip::multicast::outbound_interface( listen_address.to_v4())); socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true)); boost::asio::ip::multicast::hops optiona(4); socket_.set_option(optiona); socket_.bind(listen_endpoint); socket_.set_option( boost::asio::ip::multicast::join_group(multicast_address.to_v4())); } void CMcast::start() { socket_.async_receive_from( boost::asio::buffer(inbound_data_.data(), max_length), sender_endpoint_, boost::bind(&CMcast::handle_receive_from, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); //启动console //workthread_pool_ptr->schedule( // boost::bind(console_input, shared_from_this())); heartbeattimer_.expires_from_now(boost::posix_time::seconds(30)); heartbeattimer_.async_wait( boost::bind(&CMcast::handle_sendheartbeat, shared_from_this(), boost::asio::placeholders::error)); gethostname(hname, sizeof(hname)); } void CMcast::handle_sendheartbeat(const boost::system::error_code& error) { if (!error) { send_to("heart beat", 3); heartbeattimer_.expires_from_now(boost::posix_time::seconds(30)); heartbeattimer_.async_wait( boost::bind(&CMcast::handle_sendheartbeat, shared_from_this(), boost::asio::placeholders::error)); } } std::string CMcast::get_remote_addr() { return sender_endpoint_.address().to_string(); } int CMcast::get_remote_port() { return sender_endpoint_.port(); } void CMcast::handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd) { if (!error) { std::istringstream is( std::string(inbound_data_.begin(), inbound_data_.begin() + header_length + header_length)); int flag = 1; if (!(is >> std::hex >> inbound_data_size >> flag)) { std::clog << "Invalid header." << std::endl; boost::system::error_code error( boost::asio::error::invalid_argument); inbound_data_size = 0; socket_.async_receive_from( boost::asio::buffer(inbound_data_.data(), max_length), sender_endpoint_, boost::bind(&CMcast::handle_receive_from, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); return; } //std::string msg = inbound_data_.data() + 16; //仅仅对消息做gzip处理 string msg; { filtering_istream os; m_zipptr->UnGzipToData((char*) inbound_data_.data() + 16, inbound_data_size, os); while (!os.eof()) { char *bt = new char[1024 + 1]; std::streamsize i = read(os, &bt[0], 1024); if (i < 0) { delete[] bt; break; } else { msg.append(bt, i); delete[] bt; } } } string addr = get_remote_addr(); { if (msg.empty()) { socket_.async_receive_from( boost::asio::buffer(inbound_data_.data(), max_length), sender_endpoint_, boost::bind(&CMcast::handle_receive_from, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } JsonMsg_ptr j_ptr(new JsonMsg()); j_ptr->ParseJson(msg); if (!j_ptr->GetHost().empty()) { bool host = false; if (mapHost.size() > 0) { ReadLock w_lock(ssmapLock); map<string, string>::iterator iter = mapHost.find( j_ptr->GetHost()); if (iter != mapHost.end() && iter->second != addr) { host = true; } if (iter == mapHost.end()) { host = true; } } else { host = true; } if (host) { WriteLock w_lock(ssmapLock); mapHost[j_ptr->GetHost()] = addr; } } //如果收到心跳包,则继续接受 if (flag == 3) { socket_.async_receive_from( boost::asio::buffer(inbound_data_.data(), max_length), sender_endpoint_, boost::bind(&CMcast::handle_receive_from, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); return; } //检查是否需要运行该命令 if (j_ptr->invect(hname) && flag == 0) { string script = j_ptr->cmdString; string sid = j_ptr->sid; std::cout << "Recv a script:" << script << std::endl; //设置主机 if (script.find("set host ") != string::npos) { string cmd = script.substr(9); boost::algorithm::trim(cmd); if (cmd == "clear") { m_sessionID.Clear(sid); } else { m_sessionID.push_back(sid, cmd); } //m_ptr->send_to(sid, script, script + ": set ok!", 1); goto endloop; } //清除主机列表和缓存 else if (script.find("clear all") != string::npos) { m_sessionID.Clear(); //m_ptr->send_to(sid, script, script + ": set ok!", 1); goto endloop; } else if (script.find("lock", 0) == 0) { std::cout << "System normal state!" << std::endl; m_sessionID.SetUnlock(false); m_sessionID.SetKillFlag(sid, false); send_to(sid, script, "set ok!", 1); goto endloop; } else if (script.find("unblock", 0) == 0) { std::cout << "User normal state!" << std::endl; m_sessionID.SetKillFlag(sid, false); send_to(sid, script, "set ok!", 1); goto endloop; } else if (script.find("block", 0) == 0) { m_sessionID.SetKillFlag(sid, true); send_to(sid, script, "set ok!", 1); goto endloop; } else if (script.find("unlock", 0) == 0) { m_sessionID.SetUnlock(true); std::cout << "System unlock state!" << std::endl; send_to(sid, script, "set ok!", 1); goto endloop; } if (m_sessionID.GetKillFlag(sid)) { send_to(sid, script, ": 您的会话已经锁定!请选择\"启动查询\"!", 1); goto endloop; } } //启用工作io { work_io_service.post( boost::bind(&CMcast::process_data, shared_from_this(), j_ptr, addr, get_remote_port(), flag)); } } endloop: socket_.async_receive_from( boost::asio::buffer(inbound_data_.data(), max_length), sender_endpoint_, boost::bind(&CMcast::handle_receive_from, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void CMcast::process_data(JsonMsg_ptr j_ptr, const std::string& addr, const int& port, int flag) { workthread_pool_ptr->schedule( boost::bind(print_data, j_ptr, addr, get_remote_port(), shared_from_this(), flag)); } void CMcast::handle_send_to(const boost::system::error_code& error) { if (!error) { timer_.expires_from_now(boost::posix_time::seconds(1)); timer_.async_wait( boost::bind(&CMcast::handle_timeout, shared_from_this(), boost::asio::placeholders::error)); } } void CMcast::handle_timeout(const boost::system::error_code& error) { if (!error) { //send_to( // "{}1i09810483204{}{}1i09810483204{}{}1i09810483204{}{}1i09810483204{}{}1i09810483204{}{}1i09810483204{}{}1i09810483204{}"); } } void CMcast::handle_send(const boost::system::error_code& error) { if (!error) { std::cout << "send suc!" << std::endl; } } //发送组播信息 void CMcast::send_to(const string & sid, const string & cmd, std::string msg, int flag) { std::ostringstream header_stream; JsonMsg_ptr m_json(new JsonMsg()); m_json->cmddstVector = m_sessionID.GetVect(sid); m_json->sid = sid; m_json->AddCmd(cmd); if (flag == 1) { m_json->AddHost(hname); m_json->AddResult(msg); } else if (flag == 0) { m_json->AddHost(hname); //m_json->AddCmd(msg); } else if (flag == 2) { m_json->AddHost(hname); m_json->AddResult(msg); } else if (flag == 3) { m_json->AddHost(hname); } std::vector<boost::asio::const_buffer> buffers; m_json->MakeJsonString(); msg = m_json->GetJsonString(); size_t st = 0; std::string zipmsg; //压缩处理 { filtering_istream os; m_zipptr->GzipFromData((char*) msg.c_str(), (const int) msg.size(), os); while (!os.eof()) { char bt[1024 + 1]; std::streamsize i = read(os, &bt[0], 1024); if (i < 0) { break; } else { st += i; zipmsg.append(bt, i); } } } header_stream << std::setw(header_length) << std::hex << st << std::setw(header_length) << std::hex << flag; outbound_header_ = header_stream.str(); buffers.push_back(boost::asio::buffer(outbound_header_)); buffers.push_back(boost::asio::buffer(zipmsg.c_str(), st)); socket_.async_send_to(buffers, endpoint_, boost::bind(&CMcast::handle_send_to, shared_from_this(), boost::asio::placeholders::error)); } void CMcast::send_to(std::string msg, int flag) { std::ostringstream header_stream; JsonMsg_ptr m_json(new JsonMsg()); if (flag == 1) { m_json->AddHost(hname); m_json->AddResult(msg); } else if (flag == 0) { m_json->AddHost(hname); m_json->AddCmd(msg); } else if (flag == 2) { m_json->AddHost(hname); m_json->AddResult(msg); } else if (flag == 3) { m_json->AddHost(hname); } std::vector<boost::asio::const_buffer> buffers; m_json->MakeJsonString(); msg = m_json->GetJsonString(); size_t st = 0; std::string zipmsg; { filtering_istream os; m_zipptr->GzipFromData((char*) msg.c_str(), (const int) msg.size(), os); while (!os.eof()) { char *bt = new char[1024 + 1]; std::streamsize i = read(os, &bt[0], 1024); if (i < 0) { delete[] bt; break; } else { st += i; zipmsg.append(bt, i); delete[] bt; } } } //简单的协议:长度8:消息长度;长度8:消息类型;消息 header_stream << std::setw(header_length) << std::hex << st << std::setw(header_length) << std::hex << flag; outbound_header_ = header_stream.str(); buffers.push_back(boost::asio::buffer(outbound_header_)); buffers.push_back(boost::asio::buffer(zipmsg.c_str(), st)); socket_.async_send_to(buffers, endpoint_, boost::bind(&CMcast::handle_send_to, shared_from_this(), boost::asio::placeholders::error)); } <file_sep>/JsonMsg.cpp /* * JsonMsg.cpp * * Created on: Apr 16, 2014 * Author: zlx */ #include "JsonMsg.h" #include "CMcast.h" #include "./web/SeessionID.h" extern std::vector<std::string> hostvec; extern ssmap mapHost; extern Lock ssmapLock; JsonMsg::JsonMsg() { Reset(); } JsonMsg::~JsonMsg() { } void JsonMsg::AddHost(std::string host) { hostStr = host; } std::string JsonMsg::MakeJsonString() { if (cmddstVector.size() == 0) { if (hostvec.size() > 0) { boost::property_tree::ptree array; bool b = false; for (unsigned int i = 0; i < hostvec.size(); ++i) { if (hostvec[i] == "all") { b = true; } } if (!b) { for (unsigned int i = 0; i < hostvec.size(); ++i) { array.add("name", hostvec[i]); } } else { ReadLock r_lock(ssmapLock); BOOST_FOREACH( const ssmap::value_type &iter, mapHost ) { array.add("name", iter.first); } } jsonParse.push_back(std::make_pair("dst", array)); } } else { if (cmddstVector.size() > 0) { boost::property_tree::ptree array; bool b = false; for (unsigned int i = 0; i < cmddstVector.size(); ++i) { if (cmddstVector[i] == "all") { b = true; } } if (!b) { for (unsigned int i = 0; i < cmddstVector.size(); ++i) { array.add("name", cmddstVector[i]); } } else { ReadLock r_lock(ssmapLock); BOOST_FOREACH( const ssmap::value_type &iter, mapHost ) { array.add("name", iter.first); } } jsonParse.push_back(std::make_pair("dst", array)); } } if (!hostStr.empty()) { jsonParse.add("host", hostStr); } if (!cmdString.empty()) { jsonParse.add("cmd", cmdString); } if (!sid.empty()) { jsonParse.add("sid", sid); } if (!resultString.empty()) { jsonParse.add("result", resultString); } std::stringstream ss; boost::property_tree::json_parser::write_json(ss, jsonParse); jsonStr = ss.str(); return jsonStr; } std::string JsonMsg::GetJsonString() { return jsonStr; } void JsonMsg::AddCmd(std::string cmd) { cmdString = cmd; } void JsonMsg::AddResult(std::string result) { resultString = result; } bool JsonMsg::invect(std::string str) { for (unsigned int i = 0; i < dstVector.size(); ++i) { if (dstVector[i] == str) { return true; } else if (dstVector[i] == "all") { return true; } } return false; } void JsonMsg::Reset() { jsonStr.clear(); cmdString.clear(); hostStr.clear(); resultString.clear(); jsonStream.clear(); } void JsonMsg::ParseJson(std::string str) { if(str.empty()) return; try { Reset(); jsonStr = str; jsonStream.str(str); //支持中文输入 str = boost::property_tree::json_parser::create_escapes(str); boost::property_tree::json_parser::read_json(jsonStream, jsonParse); boost::property_tree::ptree::const_assoc_iterator it = jsonParse.find( "host"); if (it != jsonParse.not_found()) hostStr = jsonParse.get<std::string>("host"); it = jsonParse.find("cmd"); if (it != jsonParse.not_found()) cmdString = jsonParse.get<std::string>("cmd"); it = jsonParse.find("sid"); if (it != jsonParse.not_found()) sid = jsonParse.get<std::string>("sid"); it = jsonParse.find("result"); if (it != jsonParse.not_found()) resultString = jsonParse.get<std::string>("result"); it = jsonParse.find("dst"); if (it != jsonParse.not_found()) { boost::property_tree::ptree pChild = jsonParse.get_child("dst"); BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pChild) { dstVector.push_back(v.second.data()); } } } catch (const boost::property_tree::json_parser::json_parser_error& e) { cout << "Invalid JSON:" << str << endl; // Never gets here } catch (const std::runtime_error& e) { cout << "Invalid JSON:" << str << endl; // Never gets here } catch (...) { cout << "Invalid JSON:" << str << endl; // Never gets here } } std::string JsonMsg::GetHost() { return hostStr; } std::string JsonMsg::GetCmd() { return cmdString; } std::string JsonMsg::GetResult() { return resultString; } <file_sep>/page/lib/mem-pl.js module.exports = MemPL function MemPL() { this.data = {} } MemPL.prototype = { save: function (type, id, data) { if (!this.data[type]) { this.data[type] = {} } this.data[type][id] = data }, update: function (type, id, update) { for (var name in update) { this.data[type][id][name] = update[name] } }, findAll: function (type) { var items = [] if (this.data[type]) { for (var id in this.data[type]) { items.push(this.data[type][id]) } } return new Promise(function (res, rej) { res(items) }) }, remove: function (type, id) { delete this.data[type][id] } } <file_sep>/web/server.cpp // // server.cpp // #include "server.hpp" #include <signal.h> #include <utility> namespace http { namespace server { server::server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t pool_size) : io_service_pool_(pool_size), signals_(io_service_pool_.get_io_service()), acceptor_(io_service_pool_.get_io_service()), connection_manager_(), request_handler_(doc_root) { signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // defined(SIGQUIT) do_await_stop(); boost::asio::ip::tcp::resolver resolver(acceptor_.get_io_service()); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve( { address, port }); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(1)); acceptor_.bind(endpoint); acceptor_.listen(); do_accept(); } void server::run() { io_service_pool_.run(); } socket_ptr socket_; void server::do_accept() { try { socket_.reset( new boost::asio::ip::tcp::socket( io_service_pool_.get_io_service())); acceptor_.async_accept(*socket_, [this](boost::system::error_code ec) { if (!acceptor_.is_open()) { return; } if (!ec) { connection_manager_.start(std::make_shared<connection>( std::move(*socket_), connection_manager_, request_handler_)); } do_accept(); }); } catch (std::exception & ex) { std::cout << "do_accept error:" << ex.what() << std::endl; return; } } void server::do_await_stop() { signals_.async_wait([this](boost::system::error_code /*ec*/, int /*signo*/) { acceptor_.close(); connection_manager_.stop_all(); }); } } // namespace server } // namespace http <file_sep>/monitor.sh #!/bin/bash startup() { cd /home/monitor ./start.sh $1 } inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f %e' --event create /home/monitor/page/update | while read date time file event do case $event in CREATE) # echo $event'-'$file; if [[ $event == "CREATE" && $file == '/home/monitor/page/update/start.txt' ]]; then echo "recv start.txt" startup "1" rm -rf /home/monitor/page/update/start.txt fi ;; esac done <file_sep>/web/connection.hpp /* // connection.hpp * 功能:主要用于web数据接受和处理,主要相应消息和文件上下载等命令。 * 文件的上下载采用异步方式,不会对阻塞系统运行 2014-10-22 异步发送文件时文件句柄可能被复用 ,tcp复用keepalive 系统没有考虑单个文件多分段下载要求 */ #ifndef HTTP_CONNECTION_HPP #define HTTP_CONNECTION_HPP #include <array> #include <memory> #include <boost/asio.hpp> #include "reply.hpp" #include "request.hpp" #include "request_handler.hpp" #include "request_parser.hpp" #include <iostream> #include <fstream> using namespace std; namespace http { namespace server { class connection_manager; typedef struct m_data { int first; int end; } m_data; //读取文件句柄的智能指针 typedef boost::shared_ptr<std::ifstream> is_ptr; class connection: public std::enable_shared_from_this<connection> { public: connection(const connection&) = delete; connection& operator=(const connection&) = delete; explicit connection(boost::asio::ip::tcp::socket socket, connection_manager& manager, request_handler& handler); void start(); void stop(); std::string full_path; void do_zip_file(const request& req, reply& rep, std::string& extension); private: void do_read(); void do_write(); void do_file(const request& req, reply& rep, std::string& extension); //接受数据长度 size_t recv_datalen; std::string ctype; std::string boundary; std::string ansmsg; std::string filename; std::string fullfilename; size_t contentlen; size_t f_len; bool bheader; size_t h_len; std::ofstream os; bool wfirst; size_t f_offset; //异步接受文件:用于文件的上传 void asyncrecv_file(); //异步发送文件:用于文件的下载 char buf[8192]; is_ptr is; size_t ifirst; size_t iend; int readlen; void asyncsend_file(is_ptr is,int style,int ifirst, const boost::system::error_code& e); boost::asio::ip::tcp::socket socket_; connection_manager& connection_manager_; request_handler& request_handler_; std::array<char, 8192> buffer_; request request_; request_parser request_parser_; bool bkeepalive; reply reply_; std::string sessionid; }; typedef std::shared_ptr<connection> connection_ptr; } // namespace server } // namespace http #endif // HTTP_CONNECTION_HPP <file_sep>/JsonMsg.h /* * JsonMsg.h * * Created on: Apr 16, 2014 * Author: zlx */ #include <boost/progress.hpp> #include "sstream" #define BOOST_SPIRIT_THREADSAFE #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> // utf8转换用 #include <boost/program_options/detail/convert.hpp> #include <boost/program_options/detail/utf8_codecvt_facet.hpp> // 包含源代码(注意目录,在libs下,不是boost下),这样就不用库了,和前面的#define BOOST_ALL_NO_LIB配合使用 //#include <libs/program_options/src/utf8_codecvt_facet.cpp> #ifndef JSONMSG_H_ #define JSONMSG_H_ class JsonMsg:public boost::enable_shared_from_this<JsonMsg>, private boost::noncopyable { public: JsonMsg(); virtual ~JsonMsg(); void AddDst(std::string dst); void AddHost(std::string host); std::string GetJsonString(); std::string MakeJsonString(); void AddCmd(std::string cmd); void AddResult(std::string result); void Reset(); void ParseJson(std::string str); std::string GetHost(); std::string GetCmd(); std::string GetResult(); std::vector<std::string> GetDst(); bool invect(std::string str); std::vector<std::string> cmddstVector; std::string sid; std::string cmdString; private: std::string jsonStr; std::string hostStr; std::vector<std::string> dstVector; std::stringstream jsonStream; std::string resultString; boost::property_tree::ptree jsonParse; }; typedef boost::shared_ptr<JsonMsg> JsonMsg_ptr; #endif /* JSONMSG_H_ */ <file_sep>/page/lib/util.js function extend(a, b) { for (var c in b) { a[c] = b[c] } return a } function make_listed(data, nextid, collapse) { var ids = {} , children = [] , ndata = {} , res if (undefined === nextid) nextid = 100 if (data.children) { for (var i=0; i<data.children.length; i++) { res = make_listed(data.children[i], nextid, collapse) for (var id in res.tree) { ids[id] = res.tree[id] } children.push(res.id) nextid = res.id + 1 } // delete data.children } for (var name in data) { // if (name === 'children') continue ndata[name] = data[name] } ndata.done = false ids[nextid] = { id: nextid, data: ndata, children: children, collapsed: !collapse } for (var i=0; i<children.length; i++) { ids[children[i]].parent = nextid; } return {id: nextid, tree: ids} } <file_sep>/GzipProcess.h #pragma once #include <fstream> #include <iostream> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; using namespace boost::iostreams; typedef void (*Process_Stream)(const char * data, const int& len); typedef boost::shared_ptr<ifstream> ifstream_ptr; class CGzipProcess { public: CGzipProcess(void); ~CGzipProcess(void); int GzipFromFile(const string& infilename, const string& outfilename); int UnGzipToFile(const string& infilename, const string& outfilename); int GzipFromData(const char * data, const int& len, filtering_istream & in); int UnGzipToData(const char * data, const int& len, filtering_istream & in); void GzipAndCallback(const char * data, const int& len, const int& chunksize, Process_Stream callback); void UnGzipAndCallback(const char * data, const int& len, const int& chunksize, Process_Stream callback); void GzipAndCallbackFromFile(const string& infilename, const int& chunksize, Process_Stream callback); void UnGzipAndCallbackFromFile(const string& infilename, const int& chunksize, Process_Stream callback); int GzipDataToFile(const string& outfilename, const char * data, const int & len); int UnGzipDataToFile(const string& outfilename, const char * data, const int & len); private: filtering_istream all_zip; filtering_istream all_unzip; ifstream_ptr zipfile_ptr; ifstream_ptr unzipfile_ptr; public: void PushDataToZip(const char* data, const int & len); void PushDataToUnZip(const char* data, const int & len); int PushFileDataToZip(const char* infilename); int PushFileDataToUnZip(const char* infilename); void GetDataCallbackFromZip(const int& chunksize, Process_Stream callback); void GetDataCallbackFromUnZip(const int& chunksize, Process_Stream callback); int GetDataFromZip(char ** data, const int & len); int GetDataFromUnZip(char ** data, const int & len); }; typedef boost::shared_ptr<CGzipProcess> CGzipProcess_ptr; <file_sep>/reWaiter.sh #!/bin/bash netstat -nlp | grep :8099 | awk '{print $7}' | awk -F"/" '{ print $1 }' |xargs kill -9 sleep 1s netstat -nlp | grep :8099 | awk '{print $7}' | awk -F"/" '{ print $1 }' |xargs kill -9 sleep 5s /home/zlx/NLPNEW/Waiter/Waiter 0.0.0.0 192.168.3.11 8099 32000 /home/zlx/NLPNEW/Waiter/page/ <file_sep>/page/lib/base-node.js module.exports = BaseNode var keys = require('./keys') , util = require('./util') function BaseNode(data, options, isNew) { this.name = data.name this.isNew = isNew this.o = options this.o.keybindings = util.merge(this.default_keys, options.keys) this.editing = false this.setupNode(); } BaseNode.addAction = function (name, binding, func) { if (!this.extra_actions) { this.extra_actions = {} } this.extra_actions[name] = { binding: binding, func: func } } BaseNode.prototype = { // public startEditing: function (fromStart) { }, stopEditing: function () { }, addEditText: function (text) { }, setData: function (data) { }, setAttr: function (attr, value) { }, // protexted isAtStart: function () { }, isAtEnd: function () { }, isAtBottom: function () { }, isAtTop: function () { }, setupNode: function () { }, setInputValue: function (value) { }, getInputValue: function () { }, setTextContent: function (value) { }, getSelectionPosition: function () { }, // Should there be a canStopEditing? focus: function () { this.startEditing(); }, blur: function () { this.stopEditing(); }, keyHandler: function () { var actions = {} , name for (name in this.o.keybindings) { actions[this.o.keybindings[name]] = this.actions[name] } if (this.extra_actions) { for (name in this.extra_actions) { if (!actions[name]) { actions[this.extra_actions[name].binding] = this.extra_actions[name].action } } } return keys(actions).bind(this) }, default_keys: { 'undo': 'ctrl+z', 'redo': 'ctrl+shift+z', 'collapse': 'alt+left', 'uncollapse': 'alt+right', 'dedent': 'shift+tab, shift+alt+left', 'indent': 'tab, shift+alt+right', 'move up': 'shift+alt+up', 'move down': 'shift+alt+down', 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'add after': 'return', 'insert return': 'shift+return', 'merge up': 'backspace', 'stop editing': 'escape', }, actions: { 'undo': function () { this.o.undo() }, 'redo': function () { this.o.redo() }, 'collapse': function () { this.o.toggleCollapse(true) }, 'uncollapse': function () { this.o.toggleCollapse(false) }, 'dedent': function () { this.o.moveLeft() }, 'indent': function () { this.o.moveRight() }, 'move up': function () { this.o.moveUp() }, 'move down': function () { this.o.moveDown() }, 'up': function () { if (this.isAtTop()) { this.o.goUp(); } else { return true } }, 'down': function () { if (this.isAtBottom()) { this.o.goDown() } else { return true } }, 'left': function () { if (this.isAtStart()) { return this.o.goUp() } return true }, 'right': function () { if (this.isAtEnd()) { return this.o.goDown(true) } return true }, 'insert return': function (e) { return true }, 'add after': function () { var ss = this.getSelectionPosition() , name = this.getInputValue() , rest = null if (name.indexOf('\n') !== -1) { return true } if (ss < name.length) { rest = name.slice(ss) this.name = name.slice(0, ss) this.setInputValue(this.name) this.setTextContent(this.name) } else { this.name = name this.setInputValue(this.name) this.setTextContent(this.name) } if (!this.isNew) this.o.changed('name', this.name) this.o.addAfter(rest) }, // on backspace 'merge up': function () { var value = this.getInputValue() if (!value) { return this.o.remove() } if (this.isAtStart()) { return this.o.remove(value) } return true }, 'stop editing': function () { this.stopEditing(); } }, } <file_sep>/page/lib/d3tree.js var i = 0, duration = 750, root; //添加一个提示框 var tooltip = d3.select("body") .append("div") .attr("class", "tooltip") .style("opacity", 0.0); var tree = d3.layout.tree() .children(function (d) { if (!d.hidesChildren && d.children && d.collapsed && d.children.length) { d.hidesChildren = true } return d.collapsed ? null : d.children }) .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function (d) { return [d.y, d.x]; }); var svg = d3.select("#d3view").append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var listed var root var conved function start(flare) { root = flare; conved = make_listed(flare, undefined, true) , main = document.getElementById('editme'); conved.tree[conved.id].collapsed = false; listed = new Listed(conved.id, conved.tree, main) function setCollapsed(id, doCollapse) { listed.ctrl.setCollapsed(id, doCollapse) listed.ctrl.view.startEditing(id) } root = listed.ctrl.model.dumpData() root.x0 = height / 2; root.y0 = 0; update(root, setCollapsed); listed.ctrl.on('change', function () { var root = listed.ctrl.model.dumpData() root.x0 = height / 2; root.y0 = 0; update(root, setCollapsed) }) } d3.select(self.frameElement).style("height", "800px"); var COLORS = { done: '#0f0', parent: 'lightsteelblue' } var keymsg; function savePageAs(fileName) { $(".export").attr({ 'download': fileName, 'href': "data:text/html;charset=utf-8," + keymsg, 'target': '_blank' }); // return window.open( "data:x-application/external;charset=utf-8," + keymsg); }//end savePageAs function save_record(filename) { $('<div></div>').appendTo('body') .html('<div><h6>配置文件内容如下:<br>' + 'var flare_data=' + keymsg + ';</h6></div>') .dialog({ modal: true, title: '配置文件', zIndex: 10000, autoOpen: true, width: 'auto', resizable: true, buttons: { "关闭": function () { $(this).dialog("close"); } }, close: function (event, ui) { $(this).remove(); } }); } function update(source, setCollapsed) { keymsg = $.toJSON(source); // Compute the new tree layout. var nodes = tree.nodes(source).reverse(), links = tree.links(nodes); // Normalize for fixed-depth. nodes.forEach(function (d) { d.y = d.depth * 180; }); // Update the nodes… var node = svg.selectAll("g.node") .data(nodes, function (d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function (d) { var _source = d.parent || source return "translate(" + _source.y + "," + _source.x + ")"; }) ; nodeEnter.append("circle") .attr("r", 1e-6) .style('stroke', function (d) { return d.hidesChildren ? '' : (d.done ? COLORS.done : '') }) .style("fill", function (d) { if (d.done) return COLORS.done return d.hidesChildren ? COLORS.parent : "#fff"; }) .on("click", click) .on("mouseover", function (d) { if (d.ip != undefined) { tooltip.html(d.name + " IP:" + "<br />" + d.ip) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY + 20) + "px") .style("opacity", 1.0); } }) .on("mousemove", function (d) { tooltip.style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY + 20) + "px"); }) .on("mouseout", function (d) { tooltip.style("opacity", 0.0); }); nodeEnter.append("text") .attr("x", function (d) { return d.hidesChildren ? -10 : 10; }) .attr("dy", ".35em") .attr("text-anchor", function (d) { return d.hidesChildren ? "end" : "start"; }) .text(function (d) { return d.name; }) .style("fill-opacity", 1e-6) .on("dblclick", dblclick) .on("mouseover", function (d) { if (d.ip != undefined) { tooltip.html(d.name + " IP:" + "<br />" + d.ip) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY + 20) + "px") .style("opacity", 1.0); } }) .on("mousemove", function (d) { tooltip.style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY + 20) + "px"); }) .on("mouseout", function (d) { tooltip.style("opacity", 0.0); }); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("circle") .attr("r", 8.5) .style('stroke', function (d) { return d.hidesChildren ? '' : (d.done ? COLORS.done : '') }) .style("fill", function (d) { if (d.done) return COLORS.done return d.hidesChildren ? COLORS.parent : "#000"; }); nodeUpdate.select("text") .text(function (d) { return d.name; }) .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function (d) { return "translate(" + d.parent.y + "," + d.parent.x + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 1e-6); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links… var link = svg.selectAll("path.link") .data(links, function (d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("path", "g") .attr("class", "link") .attr("d", function (d) { var source = d.source var o = { x: source.x, y: source.y }; return diagonal({ source: o, target: o }); }); // Transition links to their new position. link.transition() .duration(duration) .attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(duration) .attr("d", function (d) { var o = { x: d.source.x, y: d.source.y }; return diagonal({ source: o, target: o }); }) .remove(); // Stash the old positions for transition. nodes.forEach(function (d) { d.x0 = d.x; d.y0 = d.y; }); var last; function openchatdialog(str) { if ($("#dialog").length == 0) { return; } //dialog options if (last != undefined && last != null) { last.dialog('open'); $(".ui-dialog-title")[0].innerHTML = "和服务器聊天:" + str; $("#dialog").dialogExtend("maximize"); return; } var dialogOptions = { "title": "和服务器聊天:" + str, "width": 1300, "height": 800, "modal": false, "resizable": true, "draggable": true }; if ($("#button-cancel").is(":checked")) { dialogOptions.buttons = { "Cancel": function () { $(this).dialog("close"); } }; } // dialog-extend options var dialogExtendOptions = { "closable": true, "maximizable": true, "minimizable": true, "collapsable": true }; // open dialog last = $("#dialog").dialog(dialogOptions).dialogExtend(dialogExtendOptions); $("#dialog").dialogExtend("maximize"); } var hostname = ""; function gethostname(d) { if (d.children != undefined) { for (var j = 0; j < d.children.length; j++) { gethostname(d.children[j]); } } else { if (d.ip == "" || d.ip == null || d.ip == undefined) return; else { hostname += d.name; hostname += " "; } } } function dblclick(d) { hostname = ""; if (d.depth == 0) { d.name = "all"; d.ip = "所有主机" hostname = "all"; } else { gethostname(d); } if (hostname.length == 0) { $("#Tishi")[0].innerText = "请选择可以联系的服务器!"; return; } if ($("#catinfo", window.parent.document).length > 0) { window.parent.closedialog(); } $("#Tishi")[0].innerText = "查询主机:" + hostname; $.cookie('sethostname', hostname, { expires: 24 * 60 * 60 }); $.post("/chat/sendmsg.asp", $.toJSON({ sendmsg: "set host clear" }), function (result) { jmsg = $.parseJSON(result); $.post("/chat/sendmsg.asp", $.toJSON({ sendmsg: "set host " + hostname }), function (result) { jmsg = $.parseJSON(result); }); }); openchatdialog(hostname); } // Toggle children on click. function click(d) { setCollapsed(d.id, !d.collapsed); } } start(flare_data); <file_sep>/CMain.cpp //#include "serialization_mcast.hpp" //#include "CFrame.h" //boost::asio::io_service m_ios; //int main() //{ // CFrame_ptr m_ptr(new CFrame(m_ios,"192.168.244.128","192.168.127.12","8888")); // m_ptr->start(); // m_ios.run(); // return 1; //} #include "CMcast.h" #include "boost/threadpool.hpp" #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <execinfo.h> using namespace boost::threadpool; boost::asio::io_service io_service; boost::asio::io_service work_io_service; //工作线程池 pool_ptr workthread_pool_ptr; //多播接受池 CMcast_ptr mcast_r; std::string webroot; extern std::string sendcmdexp; void sig_term(int signo) { cout << "program terminated,wait for all threads over!" << endl; cout << "reason:" << signo << endl; std::ofstream fout("./Spider.bug", ios::out | ios::app); struct tm *newtime; char tmpbuf[128]; time_t lt1; time(&lt1); newtime = ::localtime(&lt1); strftime(tmpbuf, 128, "Today is %A, day %d of %B in the year %Y %X./n", newtime); fout << "time:" << tmpbuf << endl << "sig_term:" << signo << endl; if (signo == SIGSEGV || signo == SIGFPE || signo == SIGINT || signo == SIGABRT) { void *array[10]; size_t size; char **strings; size_t i; size = backtrace(array, 10); strings = (char **) backtrace_symbols(array, size); fout << " Stack trace:\n"; for (i = 0; i < size; i++) { fout << i << " " << strings[i] << endl; } free(strings); char cmd[256] = "addr2line -C -f -e"; char* prog = cmd + strlen(cmd); readlink("/proc/self/exe", prog, sizeof(cmd) - strlen(cmd) - 1); // 获取进程的完整路径 sprintf(cmd, "%s>>./dump.log", cmd); FILE* fp = popen(cmd, "w"); if (fp != NULL) { for (i = 0; i < size; ++i) { fprintf(fp, "%p\n", array[i]); } pclose(fp); } } fout.close(); cout << "program over!" << endl; exit(-1); return; } extern int webmain(const std::string& ip, const std::string& port, const std::string& doc); void recv_thread(std::string ipdaar, std::string maddr,const short port) { //对mcast启用双io处理 mcast_r.reset( new CMcast(io_service, boost::asio::ip::address::from_string(ipdaar), boost::asio::ip::address::from_string(maddr),port)); mcast_r->start(); boost::shared_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(work_io_service)); boost::shared_ptr<boost::thread> thread( new boost::thread( boost::bind(&boost::asio::io_service::run, &io_service))); boost::shared_ptr<boost::thread> thread1( new boost::thread( boost::bind(&boost::asio::io_service::run, &work_io_service))); thread->join(); thread1->join(); } void freshregx() { std::string full_path = webroot + "/exp.regex"; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { std::cout << "远程shell匹配规则文件:" << full_path << "不存在!" << std::endl; return; } else { string str; sendcmdexp.clear(); while (is >> str) { sendcmdexp += str; ; } is.close(); } } #define NDEBUG int main(int argc, char* argv[]) { if (argc < 6) { std::cerr << "Usage: Waiter <listen_address> <multicast_address> <web port> <multicast port> <web root_path>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " Waiter 0.0.0.0 172.16.58.3 8099 32000 /page\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " Waiter 0::0ff31::8000:12348099 8099 32000 /page \n"; return 1; } //防止产生僵尸进程 //signal( SIGCHLD, SIG_IGN ); #ifdef NDEBUG int pid; if ((pid = fork())) exit(0); else if (pid < 0) exit(1); setsid(); if ((pid = fork())) exit(0); else if (pid < 0) exit(1); signal(SIGTERM, sig_term); /* arrange to catch the signal */ signal(SIGKILL, sig_term); /* arrange to catch the signal */ signal(SIGSEGV, sig_term); /* arrange to catch the signal */ signal(SIGFPE, sig_term); /* arrange to catch the signal */ signal(SIGILL, sig_term); /* arrange to catch the signal */ signal(SIGABRT, sig_term); /* arrange to catch the signal */ signal(SIGINT, sig_term); /* arrange to catch the signal */ signal(SIGQUIT, sig_term); /* arrange to catch the signal */ #endif try { std::string ipdaar = argv[1]; std::string maddr = argv[2]; std::string webport = argv[3]; webroot = argv[5]; // freshregx(); short port = atoi(argv[4]); workthread_pool_ptr.reset(new pool(80)); workthread_pool_ptr->schedule(boost::bind(recv_thread, ipdaar, maddr,port)); workthread_pool_ptr->schedule( boost::bind(webmain, ipdaar, webport, webroot)); workthread_pool_ptr->wait(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <file_sep>/logger.hpp #ifndef __LOGGER_HPP__ #define __LOGGER_HPP__ #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <iostream> #include <string> namespace Logger { class Log : public boost::iostreams::sink { public: Log( int level_, const char * name_, std::ostream *out_= &std::clog ) : m_level(level_), m_name( name_ ), m_ostream( out_ ) { }; std::streamsize write( const char* s, std::streamsize n) { if( m_filter >= m_level ){ *m_ostream << m_name << "(" << m_level << "):\t"; boost::iostreams::write( *m_ostream, s, n); } return n; }; static void setLevel( const int p_level ) { m_filter = p_level; } private: static int m_filter; const int m_level; const std::string m_name; std::ostream *m_ostream; }; }; #define CREATE_LOG( level, name ) \ boost::iostreams::stream<Logger::Log> name( level, #name ) #define CREATE_EXTERN_LOG( level, name ) \ boost::iostreams::stream<Logger::Log> name #define CREATE_STD_LOGS() \ namespace Logger { \ CREATE_LOG(7, Debug); \ CREATE_LOG(6, Info); \ CREATE_LOG(5, Notice); \ CREATE_LOG(4, Warn); \ CREATE_LOG(3, Error); \ CREATE_LOG(2, Critical); \ CREATE_LOG(1, Alert); \ CREATE_LOG(0, Fatal); \ } #define CREATE_EXTERN_STD_LOGS() \ namespace Logger { \ extern CREATE_EXTERN_LOG(7, Debug); \ extern CREATE_EXTERN_LOG(6, Info); \ extern CREATE_EXTERN_LOG(5, Notice); \ extern CREATE_EXTERN_LOG(4, Warn); \ extern CREATE_EXTERN_LOG(3, Error); \ extern CREATE_EXTERN_LOG(2, Critical); \ extern CREATE_EXTERN_LOG(1, Alert); \ extern CREATE_EXTERN_LOG(0, Fatal); \ } #endif // __LOGGER_HPP__ <file_sep>/web/ParserProcess.h #pragma once #include <string> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include "request_parser.hpp" #include "request.hpp" #include "boost/format.hpp" #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; struct header { std::string name; std::string value; }; void trim2(string& str); //处理参数 namespace http { namespace server { typedef std::vector<header> parameterVect; class CParserProcess { public: CParserProcess(void); ~CParserProcess(void); //得到参数列表 parameterVect getParameterVect(string & strParameter); //文件上载参数获得 parameterVect getUplodParameterVect(const string & strboundry, string& strParameter); parameterVect getUplodParameterVect(const string & strboundry, char* strParameter, const int len, char*& filestartpos); private: //&分割 boost::regex regex0; parameterVect mp; }; typedef std::map<string, string> parameterMap; parameterMap getParameterMap(string & strParameter); parameterMap getUplodParameterMap(string & strParameter); } } ; <file_sep>/web/CRegex.cpp #include <stdlib.h> #include <boost/regex.hpp> #include <string> #include <iostream> using namespace boost; std::string sendcmdexp; bool process_sendcmd(const std::string& msg) { cmatch what; //"^(ls|yum|top|wget|cat|find|tail|date|hostname|free|df|du)( )*.*|^sysctl( )*vm\\.drop_caches=1|^killall( )*(find|tail|cat|Waiter|du)( )*|^set( )*.*(host( )*.*)|^\\.\\/Waiter( )*.*$" regex expression(sendcmdexp); if(regex_match(msg.c_str(), what, expression)) { return true; } return false; } <file_sep>/GzipProcess.cpp #include "GzipProcess.h" using namespace std; CGzipProcess::CGzipProcess(void) { all_zip.push(gzip_compressor()); all_unzip.push(gzip_decompressor()); } CGzipProcess::~CGzipProcess(void) { } int CGzipProcess::GzipFromFile( const string& infilename,const string& outfilename) { using namespace std; try { ifstream file(infilename.c_str(), ios_base::in | ios_base::binary); if(!file.good()) return 1; filtering_istream in; in.push(gzip_compressor()); in.push(file); ofstream f(outfilename.c_str(), ios_base::out | ios_base::binary); boost::iostreams::copy(in, f); } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return 1; } return 0; } int CGzipProcess::UnGzipToFile( const string& infilename,const string& outfilename) { using namespace std; try{ ifstream file(infilename.c_str(), ios_base::in | ios_base::binary); if(!file.good()) return 1; filtering_istream in; in.push(gzip_decompressor()); in.push(file); ofstream f(outfilename.c_str(), ios_base::out | ios_base::binary); boost::iostreams::copy(in, f); } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return 1; } return 0; } int CGzipProcess::GzipFromData(const char * data,const int& len,filtering_istream & in) { using namespace std; try{ in.push(gzip_compressor()); in.push(boost::make_iterator_range(&data[0],&data[len])); } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return 1; } return 0; } int CGzipProcess::UnGzipToData(const char * data,const int& len,filtering_istream & in) { using namespace std; try{ in.push(gzip_decompressor()); in.push(boost::make_iterator_range(&data[0],&data[len])); } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return 1; } return 0; } void CGzipProcess::GzipAndCallback(const char * data,const int& len,const int& chunksize,Process_Stream callback) { filtering_istream os; GzipFromData(data,len,os); while(!os.eof()) { char *bt = new char[chunksize+1]; std::streamsize i = read(os, &bt[0], chunksize); if(i<0) { delete[]bt; break; } else { callback(bt,i); delete[]bt; } } } void CGzipProcess::UnGzipAndCallback(const char * data,const int& len,const int& chunksize,Process_Stream callback) { filtering_istream os; UnGzipToData(data,len,os); while(!os.eof()) { char *bt = new char[chunksize+1]; std::streamsize i = read(os, &bt[0], chunksize); if(i<0) { delete[]bt; break; } else { callback(bt,i); delete[]bt; } } } void CGzipProcess::GzipAndCallbackFromFile(const string& infilename, const int& chunksize,Process_Stream callback) { using namespace std; try { ifstream file(infilename.c_str(), ios_base::in | ios_base::binary); if(!file.good()) return ; filtering_istream in; in.push(gzip_compressor()); in.push(file); while(!in.eof()) { char *data = new char[chunksize+1]; std::streamsize i = read(in, &data[0], chunksize); if(i<0) { delete[]data; break; } else { callback(data,i); delete[]data; } } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return; } return; } void CGzipProcess::UnGzipAndCallbackFromFile( const string& infilename,const int& chunksize,Process_Stream callback) { using namespace std; try { ifstream file(infilename.c_str(), ios_base::in | ios_base::binary); if(!file.good()) return ; filtering_istream in; in.push(gzip_decompressor()); in.push(file); while(!in.eof()) { char *data = new char[chunksize+1]; std::streamsize i = read(in, &data[0], chunksize); if(i<0) { delete[]data; break; } else { callback(data,i); delete[]data; } } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return; } } int CGzipProcess::GzipDataToFile(const string& outfilename,const char * data,const int & len) { int res =0; filtering_istream os; res = GzipFromData(data,len,os); ofstream f(outfilename.c_str(), ios_base::out | ios_base::binary); if(!f.good()) return 1; boost::iostreams::copy(os, f); return res; } int CGzipProcess::UnGzipDataToFile(const string& outfilename,const char * data,const int & len) { int res =0; filtering_istream os; res = UnGzipToData(data,len,os); ofstream f(outfilename.c_str(), ios_base::out | ios_base::binary); if(!f.good()) return 1; boost::iostreams::copy(os, f); return res; } void CGzipProcess::PushDataToZip(const char* data,const int & len) { all_zip.push(boost::make_iterator_range(&data[0],&data[len])); } void CGzipProcess::PushDataToUnZip(const char* data,const int & len) { all_unzip.push(boost::make_iterator_range(&data[0],&data[len])); } int CGzipProcess::PushFileDataToZip(const char* infilename) { zipfile_ptr.reset(new ifstream(infilename, ios_base::in | ios_base::binary)); if(!zipfile_ptr->good()) return 0; all_zip.push(*zipfile_ptr); return 1; } int CGzipProcess::PushFileDataToUnZip(const char* infilename) { unzipfile_ptr.reset(new ifstream(infilename, ios_base::in | ios_base::binary)); if(!unzipfile_ptr->good()) return 0; all_unzip.push(*unzipfile_ptr); return 1; } void CGzipProcess::GetDataCallbackFromZip(const int& chunksize,Process_Stream callback) { try { while(!all_zip.eof()) { char *data = new char[chunksize+1]; std::streamsize i = read(all_zip, &data[0], chunksize); if(i<0) { delete[]data; break; } else { callback(data,i); delete[]data; } } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return; } } void CGzipProcess::GetDataCallbackFromUnZip(const int& chunksize,Process_Stream callback) { try { while(!all_unzip.eof()) { char *data = new char[chunksize+1]; std::streamsize i = read(all_unzip, &data[0], chunksize); if(i<0) { delete[]data; break; } else { callback(data,i); delete[]data; } } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; return; } } int CGzipProcess::GetDataFromZip(char ** data,const int & len) { try { if(!all_zip.eof()) { std::streamsize i = read(all_zip, *data, len); return (int)i; } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; } return -1; } int CGzipProcess::GetDataFromUnZip(char ** data,const int & len) { try { if(!all_unzip.eof()) { std::streamsize i = read(all_unzip, *data, len); return (int)i; } } catch(const boost::iostreams::gzip_error& e){ std::cout << e.what() << '\n'; } return -1; } <file_sep>/Release/web/subdir.mk ################################################################################ # Automatically-generated file. Do not edit! ################################################################################ # Add inputs and outputs from these tool invocations to the build variables CPP_SRCS += \ ../web/CRegex.cpp \ ../web/ParserProcess.cpp \ ../web/SeessionID.cpp \ ../web/connection.cpp \ ../web/connection_manager.cpp \ ../web/io_service_pool.cpp \ ../web/main.cpp \ ../web/md5.cpp \ ../web/mime_types.cpp \ ../web/reply.cpp \ ../web/request_handler.cpp \ ../web/request_parser.cpp \ ../web/server.cpp C_SRCS += \ ../web/md5coll.c OBJS += \ ./web/CRegex.o \ ./web/ParserProcess.o \ ./web/SeessionID.o \ ./web/connection.o \ ./web/connection_manager.o \ ./web/io_service_pool.o \ ./web/main.o \ ./web/md5.o \ ./web/md5coll.o \ ./web/mime_types.o \ ./web/reply.o \ ./web/request_handler.o \ ./web/request_parser.o \ ./web/server.o C_DEPS += \ ./web/md5coll.d CPP_DEPS += \ ./web/CRegex.d \ ./web/ParserProcess.d \ ./web/SeessionID.d \ ./web/connection.d \ ./web/connection_manager.d \ ./web/io_service_pool.d \ ./web/main.d \ ./web/md5.d \ ./web/mime_types.d \ ./web/reply.d \ ./web/request_handler.d \ ./web/request_parser.d \ ./web/server.d # Each subdirectory must supply rules for building sources it contributes web/%.o: ../web/%.cpp @echo 'Building file: $<' @echo 'Invoking: GCC C++ Compiler' g++ -I/home/zlx/boost_1_55_0 -O3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" @echo 'Finished building: $<' @echo ' ' web/%.o: ../web/%.c @echo 'Building file: $<' @echo 'Invoking: GCC C Compiler' gcc -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" @echo 'Finished building: $<' @echo ' ' <file_sep>/web/md5.hpp #pragma once #include "md5.h" #include <sstream> using namespace std; namespace zmd5 { typedef unsigned char md5digest[16]; inline void md5(const void *buf, int nbytes, md5digest digest) { md5_state_t st; md5_init(&st); md5_append(&st, (const md5_byte_t *) buf, nbytes); md5_finish(&st, digest); } inline void md5(const char *str, md5digest digest) { md5(str, strlen(str), digest); } inline std::string digestToString( md5digest digest ){ static const char * letters = "0123456789abcdef"; stringstream ss; for ( int i=0; i<16; i++){ unsigned char c = digest[i]; ss << letters[ ( c >> 4 ) & 0xf ] << letters[ c & 0xf ]; } return ss.str().substr(0, 32); } inline std::string md5simpledigest( const void* buf, int nbytes){ md5digest d; md5( buf, nbytes , d ); return digestToString( d ); } inline std::string md5simpledigest( const std::string& s ){ return md5simpledigest(s.data(), s.size()); } } // namespace zmd5 <file_sep>/CFrame.cpp /* * CFrame.cpp * * Created on: Mar 27, 2014 * Author: zlx */ #include "CFrame.h" #include "logger.hpp" #include <boost/foreach.hpp> #define foreach BOOST_FOREACH CFrame::CFrame(boost::asio::io_service &p_ios, const std::string p_address, const std::string m_address, const std::string p_port ): m_ios(p_ios) { m_con_ptr = mcast_connection_ptr(new mcast_connection(p_ios,atoi(p_port.c_str()),address::from_string(p_address),address::from_string(m_address))); } void CFrame::send(JsonMessage_ptr p_mesg) { std::vector< JsonMessage_ptr > msgs_; msgs_.push_back( p_mesg ); m_con_ptr->async_send_to(msgs_,boost::bind(&CFrame::handle_write, shared_from_this(), boost::asio::placeholders::error)); } void CFrame::handle_write(const boost::system::error_code& err) { } void CFrame::handle_read(const boost::system::error_code& err) { if( !err ) { foreach( JsonMessage_ptr msg, recvmsgs_ ) { process_message( msg ); } } else { throw boost::system::system_error(err); } m_con_ptr->async_receive_from(recvmsgs_,boost::bind(&CFrame::handle_read, shared_from_this(),boost::asio::placeholders::error)); } void CFrame::process_message(JsonMessage_ptr m_mesg) { std::cout<<"recv:"<<m_con_ptr->get_remote_addr()<<" port:"<<m_con_ptr->get_remote_port()<<m_mesg->getstring()<<std::endl; JsonMessage_ptr p_mesg(new JsonMessage()); p_mesg->setstring("{2222send data:zxc;lkzxc;k!}"); send(p_mesg); } void CFrame::start() { JsonMessage_ptr p_mesg(new JsonMessage()); p_mesg->setstring("send data!"); send(p_mesg); read(); } void CFrame::read() { m_con_ptr->async_receive_from(recvmsgs_,boost::bind(&CFrame::handle_read, shared_from_this(),boost::asio::placeholders::error)); } <file_sep>/web/SeessionID.h /* * SeessionID.h * * Created on: Apr 28, 2014 * Author: zlx */ #ifndef SEESSIONID_H_ #define SEESSIONID_H_ #include <string> #include <map> #include <boost/thread/locks.hpp> #include <boost/thread/pthread/shared_mutex.hpp> #include <boost/ptr_container/ptr_container.hpp> #include <atomic> typedef struct msgstruct { int i; std::string msg; }msgstruct; typedef std::auto_ptr<msgstruct>msgstruct_ptr; typedef boost::ptr_map<std::string, int> sidMap; typedef boost::ptr_map<std::string, int>::iterator s_ite; typedef boost::ptr_vector<msgstruct> msgMap; typedef boost::ptr_vector<msgstruct>::iterator m_ite; typedef std::vector<std::string> Ptr_strVector; typedef boost::shared_mutex Lock; typedef boost::unique_lock<Lock> WriteLock; typedef boost::shared_lock<Lock> ReadLock; typedef struct sessionStruct { std::atomic<int> i; std::string ipaddr; Ptr_strVector ptr_s; bool killflag; sessionStruct() { i = 0; killflag = false; } }sessionStruct; typedef boost::ptr_map<std::string, sessionStruct> Ptr_sidMap; //查询主机的名称列表 //typedef boost::ptr_map<std::string, std::string> hostMap; class SeessionID { public: SeessionID(); virtual ~SeessionID(); //读取sid的消息没有发送的消息 std::string ReadFunction(std::string sid); //存储sid和消息 void WriteFunction(std::string msg); void WriteHostInfo(const std::string& sid,const std::string& hostname); Ptr_strVector GetHostInfo(const std::string& sid); void Clear(); void Clear(const std::string & sid); void push_back(const std::string & sid,const std::string str); bool GetKillFlag(const std::string & sid); void SetKillFlag(const std::string & sid,bool flag); Ptr_strVector GetVect(const std::string & sid); std::string GetIPAddr(const std::string & sid); bool GetUnlock(); void SetUnlock(bool val); private: //hostMap QueryHost; //sidMap smap; Ptr_sidMap ptrsmap; msgMap mmap; std::atomic<int> kki; }; #endif /* SEESSIONID_H_ */ <file_sep>/web/connection.cpp // // connection.cpp // 文件上下载需要改成异步事件 // #include "connection.hpp" #include <utility> #include <vector> #include "connection_manager.hpp" #include "request_handler.hpp" #include <fstream> #include "boost/format.hpp" #include "boost/lexical_cast.hpp" #include "mime_types.hpp" #include "../CMcast.h" #include "ParserProcess.h" #include "md5.hpp" #include "../JsonMsg.h" #include "SeessionID.h" #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string.hpp> #include <syslog.h> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include <unistd.h> extern char hname[1024]; /* * * {"files": [ { "picture1.jpg": true }, { "picture2.jpg": true } ]} {"files": [ { "name": "picture1.jpg", "size": 902604, "error": "Filetype not allowed" }, { "name": "picture2.jpg", "size": 841946, "error": "Filetype not allowed" } ]} {"files": [ { "name": "picture1.jpg", "size": 902604, "url": "http:\/\/example.org\/files\/picture1.jpg", "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg", "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg", "deleteType": "DELETE" }, { "name": "picture2.jpg", "size": 841946, "url": "http:\/\/example.org\/files\/picture2.jpg", "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg", "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg", "deleteType": "DELETE" } ]} * */ using namespace boost::algorithm; extern std::string webroot; extern SeessionID m_sessionID; extern CMcast_ptr mcast_r; extern ssmap mapHost; extern Lock ssmapLock; extern bool process_sendcmd(const std::string& msg); extern std::vector<std::string> hostvec; namespace http { namespace server { connection::connection(boost::asio::ip::tcp::socket socket, connection_manager& manager, request_handler& handler) : socket_(std::move(socket)), connection_manager_(manager), request_handler_( handler), bkeepalive(true), f_offset(0) { #if defined OS_WINDOWS int32_t timeout = 15000; setsockopt(socket_.native(), SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); setsockopt(socket_.native(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(timeout)); #else struct timeval tv; tv.tv_sec = 30; tv.tv_usec = 0; setsockopt(socket_.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); setsockopt(socket_.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); //检查socket的状态 boost::asio::socket_base::keep_alive option(true); socket_.set_option(option); //int keepalive = 1; // 开启keepalive属性 int keepidle = 60; // 如该连接在60秒内没有任何数据往来,则进行探测 int keepinterval = 5; // 探测时发包的时间间隔为5 秒 int keepcount = 3; // 探测尝试的次数.如果第1次探测包就收到响应了,则后2次的不再发. //setsockopt(socket.native(), SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive , sizeof(keepalive )); setsockopt(socket_.native(), SOL_TCP, TCP_KEEPIDLE, (void*) &keepidle, sizeof(keepidle)); setsockopt(socket_.native(), SOL_TCP, TCP_KEEPINTVL, (void *) &keepinterval, sizeof(keepinterval)); setsockopt(socket_.native(), SOL_TCP, TCP_KEEPCNT, (void *) &keepcount, sizeof(keepcount)); #endif } void connection::start() { do_read(); } void connection::stop() { socket_.close(); } //异步接受文件:用于文件的上传 void connection::asyncrecv_file() { auto self(shared_from_this()); socket_.async_read_some( boost::asio::buffer(buffer_.data() + f_offset, 8192 - f_offset), [this, self](boost::system::error_code ec, std::size_t bytes_transferred) { if (!ec) { //处理文件上传事宜 char *ss = buffer_.data(); boost::format fmter( "{\"files\":[{\"name\":\"%s\",\"size\":%d,\"url\":\"%s\",\"thumbnailUrl\": \"%s\",\"deleteUrl\": \"%s\",\"deleteType\": \"DELETE\"}]}"); char* pos = strstr(ss, "\r\n\r\n"); if (!bheader) { if (pos > 0) { bheader = true; h_len = (size_t) (pos - ss); } else { f_offset += bytes_transferred; return asyncrecv_file(); } } recv_datalen += bytes_transferred; if (!wfirst) { char *fpos = strstr(pos + 4, "Content-Disposition: form-data;"); if (fpos != NULL) { wfirst = true; fpos = strstr(fpos, "filename="); char * d = strstr(fpos, "\r\n"); filename = fpos + 10; filename.resize(d - fpos - 11); filename = "/update/" + filename; fullfilename = webroot + filename; std::cout<<"Upload file:"<<filename<<std::endl;; os.open(fullfilename.c_str(), std::ios::out | std::ios::binary); char * sd = strstr(fpos, "\r\n\r\n"); size_t fl = recv_datalen - (int) (sd - ss + 4); f_len = fl; os.write(sd + 4, fl); f_offset = 0; os.flush(); //return asyncrecv_file(); } else { f_offset += bytes_transferred; //return asyncrecv_file(); } } else { if (bytes_transferred > 0) { os.write(ss, bytes_transferred); } } if (recv_datalen - h_len == contentlen + 4) { os.close(); //读取文件尾部数据 size_t boffset = boundary.length() + 4; struct stat st; stat(fullfilename.c_str(), &st); size_t size = st.st_size; std::ifstream is(fullfilename.c_str(), std::ios::out | std::ios::binary); is.seekg(size - boffset); std::string mend; char *p = new char[boffset + 1]; is.read(p, boffset); char* cpos = NULL; if ((cpos = strstr(p, boundary.c_str())) > 0) //找到边界 { char tp = '-'; boffset = boffset + 1; while (tp == '-') { is.seekg(size - boffset); is.read(&tp, 1); boffset = boffset + 1; } is.close(); f_len = size - boffset; truncate(fullfilename.c_str(), f_len); fmter % filename % f_len % filename % "/pic/add.png" % filename; ansmsg = fmter.str(); } else { boost::format fmter( "{\"files\":[{\"name\":\"%s\",\"size\":%s,\"error\":\"%s\")}]}"); fmter % filename % f_len % "文件接受错误"; ansmsg = fmter.str(); } delete[] p; reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = ansmsg; reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type("cmd"); return do_write(); } else { return asyncrecv_file(); } } else if (ec != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); remove(fullfilename.c_str()); return; } }); } //异步发送文件:用于文件的下载 //异步发送文件,文件句柄复用bug void connection::asyncsend_file(is_ptr is,int style,int ifirst, const boost::system::error_code& e) { int len = 0; if (!e) { if (style == 0) { is->seekg(ifirst); is->read(buf, sizeof(buf)); len = is->gcount(); if(len>0) { ifirst = ifirst + len; boost::asio::async_write(socket_, boost::asio::buffer(buf, len), boost::bind(&connection::asyncsend_file, shared_from_this(), is, style, ifirst, boost::asio::placeholders::error)); return; } } else if (style == 1) { { is->seekg(ifirst); if (readlen > 0) { if (readlen <= 8192) { is->read(buf, readlen); len = is->gcount(); if (len > 0) { ifirst = ifirst + len; readlen = readlen - len; boost::asio::async_write(socket_, boost::asio::buffer(buf, len), boost::bind(&connection::asyncsend_file, shared_from_this(), is, style,ifirst, boost::asio::placeholders::error)); return; } } else { is->read(buf, sizeof(buf)); len = is->gcount(); { if ((len = is->gcount()) > 0) { ifirst = ifirst + len; readlen = readlen - len; boost::asio::async_write(socket_, boost::asio::buffer(buf, len), boost::bind(&connection::asyncsend_file, shared_from_this(), is, style,ifirst, boost::asio::placeholders::error)); return; } } } } } } if (bkeepalive) { do_read(); } else { boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } } else { std::cout << "error:" << e.message() << std::endl; if (e != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } } } void connection::do_read() { if (f_offset >= 8192) f_offset = 0; auto self(shared_from_this()); socket_.async_read_some( boost::asio::buffer(buffer_.data() + f_offset, 8192 - f_offset), [this, self](boost::system::error_code ec, std::size_t bytes_transferred) { if (!ec) { bytes_transferred = f_offset+bytes_transferred; request_parser::result_type result; { //异步接受时需要重置:变量会累加 request_.headers.clear(); request_.method.clear(); request_.uri.clear(); } std::tie(result, std::ignore) = request_parser_.parse( request_, buffer_.data(), buffer_.data() + bytes_transferred); if (result == request_parser::good) { //接受完所有参数信息 for (int i = 0; i < (int) request_.headers.size(); i++) { if (request_.headers[i].name == "Content-Length") { contentlen = boost::lexical_cast<long unsigned int>(request_.headers[i].value.c_str()); break; } } int hsize = request_.headers.size(); std::string cookies; parameterMap gmap; sessionid.clear(); for (int i = 0; i < hsize; i++) { if (request_.headers[i].name == "Cookie") { cookies = request_.headers[i].value; gmap = getParameterMap(cookies); sessionid = gmap["sid"]; break; } } if (request_.method == "POST") { for (int i = 0; i < (int) request_.headers.size(); i++) { if (request_.headers[i].name == "Content-Type") { ctype = request_.headers[i].value; if(ctype.find("multipart/form-data")!=std::string::npos) { size_t cpos= ctype.find("boundary="); if(cpos!=std::string::npos) { cpos = cpos+9; const char * p = ctype.c_str(); while(p[cpos]=='-') { cpos = cpos +1; } boundary = ctype.c_str()+cpos; } } break; } } if(request_.uri == "/uploadfile.action" && !boundary.empty()) //处理文件上传事宜 { char *ss = buffer_.data(); char* pos = 0; pos = strstr(ss, "\r\n\r\n"); bool finished = false; if (pos > 0) { if (pos - ss != (int) bytes_transferred - contentlen - 4) finished = false; else finished = true; } boost::format fmter("{\"files\":[{\"name\":\"%s\",\"size\":%d,\"url\":\"%s\",\"thumbnailUrl\": \"%s\",\"deleteUrl\": \"%s\",\"deleteType\": \"DELETE\"}]}\r\n\r\n"); if(finished) { char *fpos = strstr(pos+4,"Content-Disposition: form-data;"); if(fpos!=NULL) { fpos = strstr(fpos,"filename="); char * d = strstr(fpos,"\r\n"); filename = fpos+10; filename.resize(d-fpos-11); pos = strstr(d,"\r\n\r\n"); pos = pos+4; int h_len = (size_t)(pos-ss); std::cout<<"Upload file:"<<filename<<std::endl;; filename = "/update/"+filename; fullfilename = webroot+filename; std::ofstream os(fullfilename.c_str(), std::ios::out | std::ios::binary); os.write(pos,bytes_transferred - h_len -4); os.flush(); os.close(); //读取文件尾部数据 size_t boffset = boundary.length()+4; struct stat st; stat(fullfilename.c_str(), &st); size_t size = st.st_size; std::ifstream is(fullfilename.c_str(), std::ios::out | std::ios::binary); is.seekg(size-boffset); std::string mend; char *p = new char[boffset+1]; is.read(p,boffset); char* cpos = NULL; if((cpos = strstr(p,boundary.c_str()))>0) //找到边界 { char tp = '-'; boffset = boffset +1; while(tp == '-') { is.seekg(size-boffset); is.read(&tp,1); boffset = boffset +1; } is.close(); f_len = size - boffset; truncate(fullfilename.c_str(),f_len); fmter % filename % f_len % filename % "/pic/add.png" % filename; ansmsg = fmter.str(); } else { remove(filename.c_str()); boost::format fmter("{\"files\":[{\"name\":\"%s\",\"size\":%s,\"error\":\"%s\")}]}\r\n\r\n"); fmter % filename % f_len % "文件接受错误"; ansmsg = fmter.str(); } delete [] p; reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = ansmsg; reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type("cmd"); return do_write(); } } else { ctype.clear(); ansmsg=""; filename.clear(); fullfilename.clear();; f_len=0; bheader=false; h_len=0; wfirst=false; recv_datalen = bytes_transferred; f_offset = recv_datalen; return asyncrecv_file(); } } else { char *ss = buffer_.data(); char* pos = 0; pos = strstr(ss, "\r\n\r\n"); bool finished = false; if (pos > 0) { if (pos - ss != (int) bytes_transferred - contentlen - 4) finished = false; else finished = true; } if (pos == 0 || !finished) { f_offset = bytes_transferred; //采用异步接受 return do_read(); } else { f_offset = 0; } } } std::string ppstr; if (request_.method == "POST" && request_.uri == "/saveconfig.asp") { char * p = buffer_.data(); p[bytes_transferred] = '\0'; char* pos = strstr(p, "\r\n\r\n"); ppstr.append(pos + 4); std::ofstream os(webroot+"/lib/flare-data.js", std::ios::out | std::ios::binary); os <<"var flare_data ="<< ppstr<<";"; os.close(); boost::format fmter("{\"success\":%s,\"status\":\"%d\"}"); fmter % "true" % 1; reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = fmter.str(); reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "cmd"); return do_write(); } else if (request_.method == "POST" && request_.uri == "/getconfig.asp") { string str = "{\"name\":\"Ola Voice服务系统\",\"done\":false,\"id\":100,\"collapsed\":false,\"x0\":380,\"y0\":0,\"children\":["; boost::format fmtstr("{\"name\":\"%s\",\"ip\":\"%s\",\"done\":false,\"id\":%d,\"collapsed\":false},"); int i= 101; { ReadLock r_lock(ssmapLock); BOOST_FOREACH( const ssmap::value_type &iter, mapHost ) { fmtstr % iter.first % iter.second % i++; str += fmtstr.str(); } } if(i>101) { str = str.substr(0,str.length()-1); } str += "]}"; boost::format fmter("{\"success\":%s,\"result\":%s}\r\n\r\n"); fmter % "true" % str; reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = fmter.str(); reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "cmd"); return do_write(); } else if (request_.method == "POST" && request_.uri == "/chat/sendmsg.asp") { //收到消息,通过组播发送,接受组播数据回传到web端 char * p = buffer_.data(); p[bytes_transferred] = '\0'; char* pos = strstr(p, "\r\n\r\n"); ppstr.append(pos + 4); std::cout<<"recv msg:"<<ppstr<<std::endl; { //记载日志 struct tm *newtime; char tmpbuf[80]; time_t lt1; time(&lt1); newtime = ::localtime(&lt1); strftime(tmpbuf,80,"%Y-%m-%d %I:%M:%S",newtime); string ipstr; //nginx 传递的IP for (int i = 0; i < (int) request_.headers.size(); i++) { if (request_.headers[i].name == "X-Real-IP") { ipstr = request_.headers[i].value.c_str(); break; } } try { if(ipstr.empty()) ipstr = socket_.remote_endpoint().address().to_string(); syslog(LOG_INFO, "%s IP:%s REQ: %s %s \r\n", tmpbuf,ipstr.c_str(),request_.uri.c_str(),ppstr.c_str()); } catch(std::exception & ex) { std::cout<<"error:"<<ex.what()<<std::endl; connection_manager_.stop(shared_from_this()); return; } } boost::format fmter("{\"success\":%s,\"id\":\"%s\",\"webhostname\":\"%s\",\"status\":\"%d\"}\r\n\r\n"); { string md5str; if(sessionid.empty()) { srand((unsigned) time(0)); int num = rand(); format fmter2("%s:%d:%d"); fmter2 % socket_.remote_endpoint().address().to_string() % socket_.remote_endpoint().port() % num; md5str = zmd5::md5simpledigest(fmter2.str()); } else { md5str = sessionid; } fmter % "true" % md5str % hname % 1; if(!ppstr.empty()) { try { std::stringstream jsonStream; boost::property_tree::ptree jsonParse; jsonStream.str(ppstr); ppstr = boost::property_tree::json_parser::create_escapes(ppstr); boost::property_tree::json_parser::read_json(jsonStream, jsonParse); boost::property_tree::ptree::const_assoc_iterator it = jsonParse.find( "sendmsg"); if (it != jsonParse.not_found()) { ppstr = jsonParse.get<std::string>("sendmsg"); if(!ppstr.empty()) { if( ppstr.find("set host ") != string::npos ) { string cmd = ppstr.substr(9); boost::algorithm::trim(cmd); if(cmd == "clear") { m_sessionID.Clear(sessionid); mcast_r->send_to(sessionid,ppstr,"",0); } else { m_sessionID.push_back(sessionid,cmd); mcast_r->send_to(sessionid,ppstr,"",0); } } else if( ppstr.find("clear all") != string::npos ) { m_sessionID.Clear(); mcast_r->send_to(sessionid,ppstr,"",0); } else { boost::property_tree::ptree::const_assoc_iterator itflag = jsonParse.find("flag"); int flag=0; if (itflag != jsonParse.not_found()) { flag = jsonParse.get<int>("flag"); } //验证 if(flag == 0) { if(process_sendcmd(ppstr)) { mcast_r->send_to(sessionid,ppstr,"",0); } else { mcast_r->send_to(sessionid,ppstr,"",1); } } else { mcast_r->send_to(sessionid,ppstr,"",flag); } } } } } catch (const boost::property_tree::json_parser::json_parser_error& e) { cout << "sendmsg Invalid JSON:" << ppstr << " " <<e.what()<< endl; // Never gets here } catch (const std::runtime_error& e) { cout << "sendmsg Invalid JSON:" << ppstr << " " <<e.what() << endl; // Never gets here } catch (...) { cout << "sendmsg Invalid JSON:" << ppstr << endl; // Never gets here } } } reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = fmter.str(); reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "cmd"); return do_write(); } else if (request_.method == "POST" && request_.uri == "/chat/recvmsg.asp") { //收到消息,通过组播发送,接受组播数据回传到web端 string msg; msg = m_sessionID.ReadFunction(sessionid); boost::format fmter("{\"success\":%s,\"webhostname\":\"%s\",\"status\":\"%d\",\"msg\":%s}\r\n\r\n\r\n\r\n"); fmter % "true" % hname % 1 % msg; bool bgzip = false; for (int i = 0; i < (int) request_.headers.size(); i++) { if (request_.headers[i].name == "Accept-Encoding") { if (request_.headers[i].value.find_first_of("gzip") != string::npos) { bgzip = true; break; } } } if(bgzip && fmter.size()>=2048) { reply_.headers.resize(3); reply_.status = reply::ok; reply_.headers[0].name = "Content-Length"; reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type("cmd"); reply_.headers[2].name = "Content-Encoding"; reply_.headers[2].value = "gzip"; CGzipProcess_ptr m_zipptr(new CGzipProcess()); filtering_istream os; string msg = fmter.str(); m_zipptr->GzipFromData((char*) msg.c_str(), (const int) msg.length(), os); size_t len = 0; char buf[8192]; char *bt = buf; while (!os.eof()) { std::streamsize i = read(os, &bt[0], 8192); if (i < 0) { break; } else { reply_.content.append(bt, i); len += i; } } reply_.headers[0].value = boost::lexical_cast<std::string>(len); } else { reply_.status = reply::ok; reply_.headers.resize(2); reply_.content = fmter.str(); reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "cmd"); } return do_write(); } else if (request_.uri == "/chat/recvmsg.tes") { //收到消息,通过组播发送,接受组播数据回传到web端 string msg; msg = m_sessionID.ReadFunction(sessionid); boost::format fmter("data:{\"success\":%s,\"webhostname\":\"%s\",\"status\":\"%d\",\"msg\":%s}\r\n\r\n\r\n\r\n"); fmter % "true" % hname % 1 % msg; bool bgzip = false; for (int i = 0; i < (int) request_.headers.size(); i++) { if (request_.headers[i].name == "Accept-Encoding") { if (request_.headers[i].value.find_first_of("gzip") != string::npos) { bgzip = true; break; } } } if(bgzip && fmter.size()>=2048) { reply_.headers.resize(3); reply_.status = reply::ok; reply_.headers[0].name = "Content-Length"; reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type("tes"); reply_.headers[2].name = "Content-Encoding"; reply_.headers[2].value = "gzip"; CGzipProcess_ptr m_zipptr(new CGzipProcess()); filtering_istream os; string msg = fmter.str(); m_zipptr->GzipFromData((char*) msg.c_str(), (const int) msg.length(), os); size_t len = 0; char buf[8192]; char *bt = buf; while (!os.eof()) { std::streamsize i = read(os, &bt[0], 8192); if (i < 0) { break; } else { reply_.content.append(bt, i); len += i; } } reply_.headers[0].value = boost::lexical_cast<std::string>(len); } else { reply_.status = reply::ok; reply_.headers.resize(3); reply_.content = fmter.str(); reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "tes"); reply_.headers[2].name = "Cache-Control"; reply_.headers[2].value = "no-cache"; } return do_write(); } else { std::string extension; full_path = request_handler_.get_fullpath(request_, reply_,extension); if(request_.method == "DELETE" && full_path.find("/update/")!=std::string::npos) { remove(full_path.c_str()); reply_.status = reply::ok; reply_.headers.resize(3); reply_.content = ""; reply_.headers[0].name = "Content-Length"; reply_.headers[0].value = boost::lexical_cast<std::string>( reply_.content.size()); reply_.headers[1].name = "Content-Type"; reply_.headers[1].value = mime_types::extension_to_type( "tes"); reply_.headers[2].name = "Cache-Control"; reply_.headers[2].value = "no-cache"; return do_write(); } else { return do_file(request_, reply_,extension); } } } else if (result == request_parser::bad) { reply_ = reply::stock_reply(reply::bad_request); return do_write(); } else { return do_read(); } } else if (ec != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } void connection::do_zip_file(const request& req, reply& rep, std::string& extension) { replace_all(full_path, "\\", "/"); struct stat st; stat(full_path.c_str(), &st); size_t size = st.st_size; //判断时间戳 string filetmstr; char tm_str[29]; bool bgzip = false; for (int i = 0; i < (int) req.headers.size(); i++) { if (req.headers[i].name == "Accept-Encoding") { if (req.headers[i].value.find_first_of("gzip") != string::npos) { bgzip = true; break; } } } for (int i = 0; i < (int) req.headers.size(); i++) { if (req.headers[i].name == "If-Modified-Since") { filetmstr = req.headers[i].value; namespace fs = boost::filesystem; try { time_t m_t = boost::filesystem::last_write_time(full_path); strftime(tm_str, 29, "%a,%d %b %Y %H:%M:%S GMT", ::localtime(&m_t)); } catch (...) { rep = reply::stock_reply(reply::not_found); return do_write(); } replace_all(filetmstr, ", ", ","); if (strcasecmp(tm_str, filetmstr.c_str()) == 0) { rep.status = reply::not_modified; return do_write(); } } } CGzipProcess mp; if (bgzip) { if (0 == mp.PushFileDataToZip(full_path.c_str())) { rep = reply::stock_reply(reply::not_found); do_write(); return; } namespace fs = boost::filesystem; time_t m_t = fs::last_write_time(full_path); strftime(tm_str, 29, "%a,%d %b %Y %H:%M:%S GMT", ::localtime(&m_t)); rep.status = reply::ok; char buf[8192]; char *p = buf; int isize = 0; rep.headers.resize(4); rep.headers[0].name = "Content-Length"; rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); rep.headers[2].name = "Last-Modified"; rep.headers[2].value = tm_str; rep.headers[3].name = "Content-Encoding"; rep.headers[3].value = "gzip"; size_t len = 0; while ((isize = mp.GetDataFromZip(&p, sizeof(buf))) > 0) { rep.content.append(buf, isize); len += isize; } rep.headers[0].value = boost::lexical_cast<std::string>(len); do_write(); return; } else { is.reset(new std::ifstream(full_path.c_str(), std::ios::in | std::ios::binary)); if (!is->is_open()) { rep = reply::stock_reply(reply::not_found); do_write(); return; } namespace fs = boost::filesystem; time_t m_t = fs::last_write_time(full_path); strftime(tm_str, 29, "%a,%d %b %Y %H:%M:%S GMT", ::localtime(&m_t)); rep.status = reply::ok; char buf[8192]; rep.headers.resize(3); rep.headers[0].name = "Content-Length"; rep.headers[0].value = boost::lexical_cast<std::string>(size); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); rep.headers[2].name = "Last-Modified"; rep.headers[2].value = tm_str; while (is->read(buf, sizeof(buf)).gcount() > 0) { rep.content.append(buf, is->gcount()); } rep.headers[0].value = boost::lexical_cast<std::string>( rep.to_buffers().size()); do_write(); return; } return; } void connection::do_file(const request& req, reply& rep, std::string& extension) { replace_all(full_path, "\\", "/"); /*if(is.is_open()) { is.close(); }*/ is.reset(new std::ifstream(full_path.c_str(), std::ios::in | std::ios::binary)); //is.open(full_path.c_str(), std::ios::in | std::ios::binary); if (!is->is_open()) { rep = reply::stock_reply(reply::not_found); do_write(); return; } //判断时间戳 string filetmstr; char tm_str[29]; namespace fs = boost::filesystem; try { time_t m_t = boost::filesystem::last_write_time(full_path); strftime(tm_str, 29, "%a,%d %b %Y %H:%M:%S GMT", ::localtime(&m_t)); } catch (...) { rep = reply::stock_reply(reply::not_found); return do_write(); } for (int i = 0; i < (int) req.headers.size(); i++) { if (req.headers[i].name == "If-Modified-Since") { filetmstr = req.headers[i].value; replace_all(filetmstr, ", ", ","); if (strcasecmp(tm_str, filetmstr.c_str()) == 0) { rep.status = reply::not_modified; return do_write(); } } } struct stat st; stat(full_path.c_str(), &st); size_t size = st.st_size; bool brange = false; vector<m_data> v_m_data; for (int i = 0; i < (int) req.headers.size(); i++) { if (req.headers[i].name == "Range") { std::string mstr = req.headers[i].value; size_t so = mstr.find("bytes="); brange = true; if (so != std::string::npos) { so = so + 6; vector<string> strVec; string str = req.headers[i].value.c_str() + so; split(strVec, str, is_any_of(",")); if (strVec.size() > 1) { vector<string>::iterator it = strVec.begin(); for (; it != strVec.end(); it++) { cout << *it << endl; vector<string> str1Vec; split(str1Vec, *it, is_any_of("-")); if (str1Vec.size() == 2) { m_data m1; trim(str1Vec[0]); trim(str1Vec[1]); if (str1Vec[0].empty()) m1.first = -1; else m1.first = atoi(str1Vec[0].c_str()); if (str1Vec[1].empty()) m1.end = -1; else m1.end = atoi(str1Vec[1].c_str()); v_m_data.push_back(m1); } } } else { vector<string> str1Vec; split(str1Vec, str, is_any_of("-")); if (str1Vec.size() == 2) { m_data m1; if (str1Vec[0].empty()) m1.first = -1; else m1.first = atoi(str1Vec[0].c_str()); if (str1Vec[1].empty()) m1.end = -1; else m1.end = atoi(str1Vec[1].c_str()); v_m_data.push_back(m1); } } break; } } } if (!brange) { rep.headers.resize(3); rep.status = reply::ok; //char buf[1024]; rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(size); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); rep.headers[2].name = "Last-Modified"; rep.headers[2].value = tm_str; //if (is.read(buf, sizeof(buf)).gcount() >= 0) { //int len = is.gcount(); //rep.content.append(buf, len); //ifirst = ifirst + len; boost::asio::async_write(socket_, rep.to_buffers(), boost::bind(&connection::asyncsend_file, shared_from_this(), is, 0, ifirst, boost::asio::placeholders::error)); //} return; } else { boost::format fmter("bytes %d-%d/%d"); if (v_m_data.size() == 1) { ifirst = 0; iend = 0; if (v_m_data[0].first == -1) { ifirst = size - v_m_data[0].end; iend = size - 1; } else { if (v_m_data[0].end == -1) { iend = size - 1; } else { iend = v_m_data[0].end; } ifirst = v_m_data[0].first; } rep.headers.resize(4); rep.status = reply::partial_content; rep.headers[0].name = "Content-Length"; rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); rep.headers[2].name = "Last-Modified"; rep.headers[2].value = tm_str; rep.headers[3].name = "Content-Range"; fmter % ifirst % iend % size; rep.headers[3].value = fmter.str(); readlen = iend - ifirst + 1; rep.headers[0].value = std::to_string(readlen); //size_t len = 0; //char buf[1024]; //if (is.read(buf, sizeof(buf)).gcount() > 0) //len = is.gcount(); //rep.content.append(buf, len); //ifirst = ifirst + len; boost::asio::async_write(socket_, rep.to_buffers(), boost::bind(&connection::asyncsend_file, shared_from_this(), is, 1, ifirst, boost::asio::placeholders::error)); return; } else { std::cout << "v_m_data.size:" << v_m_data.size() << std::endl; } } if (bkeepalive) { do_read(); } else { boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } } void connection::do_write() { auto self(shared_from_this()); boost::asio::async_write(socket_, reply_.to_buffers(), [this, self](boost::system::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. if(bkeepalive) { do_read(); } else { boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } } if (ec != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } } // namespace server }// namespace http <file_sep>/serialization_mcast.hpp // // connection.hpp // ~~~~~~~~~~~~~~ #ifndef SERIALIZATION_MCAST_HPP #define SERIALIZATION_MCAST_HPP #include <boost/asio.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/tuple/tuple.hpp> #include <iomanip> #include <string> #include <sstream> #include <vector> #include "boost/bind.hpp" #include "boost/date_time/posix_time/posix_time_types.hpp" #include "boost/asio/placeholders.hpp" #define MAXBUF 400 using namespace boost::asio::ip; class mcast_connection: public boost::enable_shared_from_this<mcast_connection>, private boost::noncopyable { public: mcast_connection(boost::asio::io_service& io_service, unsigned short port, const boost::asio::ip::address& listen_address, const boost::asio::ip::address& multicast_address) : socket_(io_service), endpoint_(listen_address, port), recv_len(0){ inbound_data_.resize(MAXBUF); socket_.open(endpoint_.protocol()); socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true)); socket_.bind(endpoint_); boost::asio::socket_base::receive_buffer_size receSize(2*1024*1024); socket_.set_option(receSize); socket_.set_option( boost::asio::ip::multicast::join_group(multicast_address)); } boost::asio::ip::udp::socket& socket() { return socket_; } template<typename T, typename Handler> void async_send_to(const T& t, Handler handler) { std::ostringstream archive_stream; boost::archive::xml_oarchive archive(archive_stream); archive << BOOST_SERIALIZATION_NVP(t); outbound_data_ = archive_stream.str(); std::ostringstream header_stream; header_stream << std::setw(header_length) << std::hex << outbound_data_.size(); if (!header_stream || header_stream.str().size() != header_length) { boost::system::error_code error( boost::asio::error::invalid_argument); socket_.get_io_service().post(boost::bind(handler, error)); return; } outbound_header_ = header_stream.str(); std::vector<boost::asio::const_buffer> buffers; buffers.push_back(boost::asio::buffer(outbound_header_)); buffers.push_back(boost::asio::buffer(outbound_data_)); socket_.async_send_to(buffers, endpoint_, handler); } template<typename T, typename Handler> void async_receive_from(T& t, Handler handler) { void (mcast_connection::*f)(const boost::system::error_code&,std::size_t, T&, boost::tuple<Handler>) = &mcast_connection::handle_read_data<T, Handler>; socket_.async_receive_from(boost::asio::buffer(inbound_data_.data()+recv_len,inbound_data_.size()-recv_len), remote_endpoint, boost::bind(f, shared_from_this(), boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred, boost::ref(t), boost::make_tuple(handler))); } template<typename T, typename Handler> void handle_read_data(const boost::system::error_code& e,std::size_t bytes_transferred,T& t, boost::tuple<Handler> handler ) { if (e) { boost::get<0>(handler)(e); } else { std::istringstream is( std::string(inbound_data_.begin(), inbound_data_.begin() + header_length)); std::size_t inbound_data_size = 0; if(recv_len == 0) { if (!(is >> std::hex >> inbound_data_size)) { std::clog << "Invalid header." << std::endl; boost::system::error_code error( boost::asio::error::invalid_argument); boost::get<0>(handler)(error); return; } inbound_data_size += 8; }else { inbound_data_size = inbound_data_.size(); } recv_len += bytes_transferred; std::cout<<"len:"<<inbound_data_size<<"recv:"<<bytes_transferred<<" " <<std::endl; //判断包是否接受完整 if(inbound_data_size > recv_len) { inbound_data_.resize(inbound_data_size); void (mcast_connection::*f)(const boost::system::error_code&, std::size_t, T&, boost::tuple<Handler>) = &mcast_connection::handle_read_data<T, Handler>; socket_.async_receive_from( boost::asio::buffer(inbound_data_.data() + recv_len, inbound_data_.size() - recv_len), remote_endpoint, boost::bind(f, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(t), handler)); return; }else { recv_len = 0; } std::string archive_data(inbound_data_.begin() + header_length, (inbound_data_.end())); try { std::istringstream archive_stream(archive_data); boost::archive::xml_iarchive archive(archive_stream); archive >> BOOST_SERIALIZATION_NVP(t); } catch (std::exception& e) { // Unable to decode data. std::clog << "Unable to decode data" << std::endl; #if DEBUG > 7 std::cerr << "Incoming message" << std::endl << archive_data << std::endl; #endif boost::system::error_code error( boost::asio::error::invalid_argument); boost::get<0>(handler)(error); return; } // Inform caller that data has been received ok. boost::get<0>(handler)(e); } } std::string get_remote_addr() { return remote_endpoint.address().to_string(); } int get_remote_port() { return remote_endpoint.port(); } private: boost::asio::ip::udp::socket socket_; boost::asio::ip::udp::endpoint endpoint_; boost::asio::ip::udp::endpoint remote_endpoint; enum { header_length = 8 }; std::string outbound_header_; std::string outbound_data_; std::vector<char> inbound_data_; int recv_len; }; typedef boost::shared_ptr<mcast_connection> mcast_connection_ptr; #endif // SERIALIZATION_MCAST_HPP <file_sep>/package.sh #!/bin/bash path=$1 cd $path datstr=`date "+%Y_%m_%d_%H_%M_%S"` mkdir /mnt/log mkdir /mnt/log/olalog mkdir /mnt/log/olalog/`hostname` # 判断是否在运行 if ps -e | grep "tar jcvf /mnt/log/`hostname`" > /dev/null then echo "Tar Running!" else echo "Tar start!" tar jcvf /mnt/log/olalog/`hostname`/$datstr.tar.bz2 $1 chmod 7777 /mnt/log/olalog/ -R echo "Tar end!" fi <file_sep>/page/lib/view.js function merge(a, b) { var c = {} for (var name in a) { c[name] = a[name] } for (var name in b) { c[name] = b[name] } return c } function findTarget(targets, e) { for (var i=0; i<targets.length; i++) { if (targets[i].top > e.clientY) { return targets[i > 0 ? i-1 : 0] } } return targets[targets.length-1] } function View(bindActions, model, ctrl, options) { options = options || {} this.selection = {} this.editing = false this.o = extend({ node: DefaultNode, }, options) this.o.keybindings = merge(this.default_keys, options.keys) this.vl = new DomViewLayer(this.o) this.bindActions = bindActions this.model = model this.ctrl = ctrl this.attachListeners() } View.prototype = { initialize: function (root, ids) { var node = ids[root] , rootNode = this.vl.makeRoot(root, node.data, this.bindActions(root)) this.populateChildren(root, ids) this.root = root this.goTo(this.root) return rootNode }, populateChildren: function (id, ids) { var node = ids[id] if (!node.children || !node.children.length) return for (var i=0; i<node.children.length; i++) { this.add(ids[node.children[i]], false, true) this.populateChildren(node.children[i], ids) } }, goTo: function (id) { if (this.editing) { this.startEditing(id) } else { this.setSelection([id]) } }, startMoving: function (id) { this.moving = { targets: this.vl.dropTargets(this.root, this.model, id, true), shadow: this.vl.makeDropShadow(), current: null } this.vl.setMoving(id, true) var onMove = function (e) { this.drag(id, e) }.bind(this) var onUp = function (e) { document.body.style.cursor = '' document.removeEventListener('mousemove', onMove) document.removeEventListener('mouseup', onUp) this.drop(id, e) }.bind(this) document.body.style.cursor = 'move' document.addEventListener('mousemove', onMove) document.addEventListener('mouseup', onUp) }, drag: function (id, e) { if (this.moving.current) { this.vl.setDropping(this.moving.current.id, false, this.moving.current.place === 'child') } var target = findTarget(this.moving.targets, e) this.moving.shadow.moveTo(target) this.moving.current = target this.vl.setDropping(target.id, true, this.moving.current.place === 'child') }, drop: function (id, e) { this.moving.shadow.remove() var current = this.moving.current this.vl.setMoving(id, false) if (!this.moving.current) return this.vl.setDropping(current.id, false, current.place === 'child') if (current.id === id) return switch (current.place) { case "child": this.ctrl.actions.moveInto(id, current.id) break; case "before": this.ctrl.actions.moveToBefore(id, current.id) break; default: this.ctrl.actions.moveToAfter(id, current.id) } this.moving = false //console.log("Drop something useful", this.moving.current, //this.model.ids[this.moving.current.id].data) }, default_keys: { 'cut': 'ctrl x, delete', 'copy': 'ctrl c', 'paste': 'p, ctrl v', 'toggle done': 'ctrl return', 'edit': 'return, a, shift a, f2', 'edit start': 'i, shift i', 'first sibling': 'shift [', 'last sibling': 'shift ]', 'move to first sibling': 'shift alt [', 'move to last sibling': 'shift alt ]', 'new after': 'o', 'new before': 'shift o', 'up': 'up, k', 'down': 'down, j', 'left': 'left, h', 'right': 'right, l', 'next sibling': 'alt j, alt down', 'prev sibling': 'alt k, alt up', 'toggle collapse': 'z', 'collapse': 'alt h, alt left', 'uncollapse': 'alt l, alt right', 'indent': 'tab, shift alt l, shift alt right', 'dedent': 'shift tab, shift alt h, shift alt left', 'move down': 'shift alt j, shift alt down', 'move up': 'shift alt k, shift alt up', 'undo': 'ctrl z, u', 'redo': 'ctrl shift z, shift r', }, actions: { 'cut': function () { if (!this.selection.length) return this.ctrl.actions.cut(this.selection[0]) }, 'copy': function () { if (!this.selection.length) return this.ctrl.actions.copy(this.selection[0]) }, 'paste': function () { if (!this.selection.length) return this.ctrl.actions.paste(this.selection[0]) }, 'undo': function () { this.ctrl.undo(); }, 'redo': function () { this.ctrl.redo(); }, 'edit': function () { if (!this.selection.length) { this.selection = [this.root] } this.vl.body(this.selection[0]).startEditing() }, 'edit start': function () { if (!this.selection.length) { this.selection = [this.root] } this.vl.body(this.selection[0]).startEditing(true) }, // nav 'first sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } var first = this.model.firstSibling(this.selection[0]) if (undefined === first) return this.setSelection([first]) }, 'last sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } var last = this.model.lastSibling(this.selection[0]) if (undefined === last) return this.setSelection([last]) }, 'up': function () { var selection = this.selection if (!selection.length) { this.setSelection([this.root]) } else { var top = selection[0] , above = this.model.idAbove(top) if (above === undefined) above = top this.setSelection([above]) } }, 'down': function () { var selection = this.selection if (!selection.length) { this.setSelection([this.root]) } else { var top = selection[0] , above = this.model.idBelow(top) if (above === undefined) above = top this.setSelection([above]) } }, 'left': function () { var selection = this.selection if (!selection.length) { return this.setSelection([this.root]) } var left = this.model.getParent(this.selection[0]) if (undefined === left) return this.setSelection([left]) }, 'right': function () { var selection = this.selection if (!selection.length) { return this.setSelection([this.root]) } var right = this.model.getChild(this.selection[0]) if (this.model.isCollapsed(this.selection[0])) return if (undefined === right) return this.setSelection([right]) }, 'next sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } var sib = this.model.nextSibling(this.selection[0]) if (undefined === sib) return this.setSelection([sib]) }, 'prev sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } var sib = this.model.prevSibling(this.selection[0]) if (undefined === sib) return this.setSelection([sib]) }, 'move to first sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveToTop(this.selection[0]) }, 'move to last sibling': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveToBottom(this.selection[0]) }, 'new before': function () { if (!this.selection.length) return this.ctrl.addBefore(this.selection[0]) this.startEditing() }, 'new after': function () { if (!this.selection.length) return this.ctrl.addAfter(this.selection[0]) this.startEditing(this.selection[0]) }, // movez! 'toggle done': function () { if (!this.selection.length) return var id = this.selection[0] , done = !this.model.ids[id].data.done , next = this.model.idBelow(id) if (next === undefined) next = id this.ctrl.actions.changed(this.selection[0], 'done', done) this.goTo(next) }, 'toggle collapse': function () { this.ctrl.actions.toggleCollapse(this.selection[0]) }, 'collapse': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.toggleCollapse(this.selection[0], true) }, 'uncollapse': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.toggleCollapse(this.selection[0], false) }, 'indent': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveRight(this.selection[0]) }, 'dedent': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveLeft(this.selection[0]) }, 'move down': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveDown(this.selection[0]) }, 'move up': function () { if (!this.selection.length) { return this.setSelection([this.root]) } this.ctrl.actions.moveUp(this.selection[0]) } }, attachListeners: function () { var actions = {} for (var name in this.o.keybindings) { actions[this.o.keybindings[name]] = this.actions[name] } var keydown = keys(actions) window.addEventListener('keydown', function (e) { if (this.editing) return keydown.call(this, e) }.bind(this)) }, addTree: function (node, before) { this.add(node, before) if (!node.children.length) return for (var i=0; i<node.children.length; i++) { this.addTree(this.model.ids[node.children[i]], false) } }, // operations add: function (node, before, dontfocus) { var ed = this.editing this.vl.addNew(node, this.bindActions(node.id), before) if (!dontfocus) { if (ed) { this.vl.body(node.id).startEditing() } else { this.setSelection([node.id]) } } }, remove: function (id) { var pid = this.model.ids[id] , parent = this.model.ids[pid] this.vl.remove(id, pid, parent && parent.children.length === 1) var ix = this.selection.indexOf(id) if (ix !== -1) { this.selection.splice(ix, 1) if (this.selection.length == 0) { this.setSelection([this.root]) } else { this.setSelection(this.selection) } } }, setData: function (id, data) { this.vl.body(id).setData(data) if (this.editing) { this.vl.body(id).startEditing() } }, appendText: function (id, text) { this.vl.body(id).addEditText(text) }, move: function (id, pid, before, ppid, lastchild) { var ed = this.editing this.vl.move(id, pid, before, ppid, lastchild) if (ed) this.startEditing(id) }, startEditing: function (id, fromStart) { if (arguments.length === 0) { id = this.selection.length ? this.selection[0] : this.root } this.vl.body(id).startEditing(fromStart) }, setEditing: function (id) { this.editing = true this.setSelection([id]) }, doneEditing: function () { this.editing = false }, setSelection: function (sel) { this.vl.clearSelection(this.selection) this.selection = sel this.vl.showSelection(sel) }, setCollapsed: function (id, what) { this.vl.setCollapsed(id, what) if (what) { if (this.editing) { this.startEditing(id) } else { this.setSelection([id]) } } // TODO: event listeners? }, // non-modifying stuff goUp: function (id) { // should I check to see if it's ok? var above = this.model.idAbove(id) if (above === false) return this.vl.body(id).body.stopEditing(); this.vl.body(above).body.startEditing(); }, goDown: function (id, fromStart) { var below = this.model.idBelow(id) if (below === false) return this.vl.body(id).body.stopEditing() this.vl.body(below).body.startEditing(fromStart) }, }
5cc4ce98c3b1703d012b0f339d8788289d23096d
[ "JavaScript", "Makefile", "Text", "C++", "Shell" ]
43
C++
einet/intranet-mannager
62e243b67f1f17635a25acb7a78d25b249c98690
5462f124fcd72860e32b32640b54f3839c446def
refs/heads/master
<repo_name>LiuxuyangK/springmvc-study<file_sep>/src/main/java/com/springmvc/lxy/other/Exec_19_01_06.java package com.springmvc.lxy.other; import com.alibaba.fastjson.JSONObject; import java.util.Arrays; import java.util.Comparator; /** * 描述: 动态规划 * <p> * * @author: harry * @date: 2019-01-06 **/ public class Exec_19_01_06 { public static void main(String[] args) { //切钢管 int[] p = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; int n = 4; int cut = cut2(p, n); System.out.println(cut); int cut3 = cut3(p, n); System.out.println(cut3); int cut4 = cut4(p, n); System.out.println(cut4); //选任务,获得收益最大 int[] t = {5, 1, 8, 4, 6, 3, 2, 4}; int[] prev = {-1, -1, -1, 0, -1, 1, 2, 4}; int res = doTask(t, prev); System.out.println(res); int[][] jobs = {{1, 4, 5}, {3, 5, 1}, {0, 6, 8}, {4, 7, 4}, {3, 8, 6}, {5, 9, 3}, {6, 10, 2}, {8, 11, 4}}; int jobRes2 = doTask2(jobs); System.out.println(jobRes2); //计算不相邻的数字 int[] arr = {1, 2, 4, 1, 7, 8, 3}; int i = calcNotXianglin(arr); System.out.println(i); //取钱,递归 int[] arr2 = {3, 34, 4, 12, 5, 2}; boolean money = getMoneyRec(arr2, arr2.length - 1, 9); System.out.println(money); boolean money2 = getMoneyRec(arr2, arr2.length - 1, 10); System.out.println(money2); boolean money3 = getMoneyRec(arr2, arr2.length - 1, 11); System.out.println(money3); boolean money4 = getMoneyRec(arr2, arr2.length - 1, 12); System.out.println(money4); boolean money5 = getMoneyRec(arr2, arr2.length - 1, 13); System.out.println(JSONObject.toJSONString(arr2) + " = 13,result:" + money5); int[] arr3 = {1, 2, 5, 8, 9}; boolean money6 = getMoneyRec(arr3, arr3.length - 1, 25); System.out.println(JSONObject.toJSONString(arr3) + " = 25,result:" + money6); //取钱,非递归 boolean money7 = getMoney(arr3, 25); System.out.println("getMoney:" + JSONObject.toJSONString(arr3) + " = 25,result:" + money7); //重复拿钞票问题 int[] coins = {1, 5}; int sum = 17; int num = getMoneyWithLeastNum(coins, sum); System.out.println("getMoneyWithLeastNum:" + num); } /** * 取货币的方法。 * 递推公式:也是取和不取。 * dp[i] = Math.max(dp[i-1],s - arr[i],dp[i - 1],s) * <p> * 这是递归的方法,注意方法的结束出口 * * @param arr * @param i * @param s * @return */ private static boolean getMoneyRec(int[] arr, int i, int s) { if (s == 0) { return true; } else if (i == 0) { return arr[i] == s; } else if (arr[i] > s) { return getMoneyRec(arr, i - 1, s); } boolean selected = getMoneyRec(arr, i - 1, s - arr[i]); boolean notSelected = getMoneyRec(arr, i - 1, s); return selected || notSelected; } /** * 非递归的方法 * 要用一个二维的数组去设计! * 听这个老师讲课简直不要太清晰! * dp[i][j] 表示: 用前i个钱币,凑金额为j,是否可行。 * 递归公式:dp[i][j] = Math.max(dp[i-1][j-i],dp[i-1][j]) * <p> * 1. 首先列出一个二维数组,"竖高"是钱币的下标以及对应的值,"横宽"是把目标值,从0,1,2...n拆解出来。 * 2. 然后填满第一行,填满第一列。 * 3. 带入去计算了。 * * @param arr * @param s * @return */ private static boolean getMoney(int[] arr, int s) { int[][] dp = new int[arr.length][s + 1]; //赋初始值:第一行 for (int i = 0; i < dp[0].length; i++) { dp[0][i] = 0; if (arr[0] == i) { dp[0][i] = 1; } } //第一列 for (int i = 0; i < dp.length; i++) { dp[i][0] = 1; } for (int i = 1; i < dp.length; i++) { for (int j = 1; j < dp[i].length; j++) { if (arr[i] > j) { dp[i][j] = dp[i - 1][j]; } else { int notSelected = dp[i - 1][j]; int selected = dp[i - 1][j - arr[i]]; dp[i][j] = notSelected == 1 || selected == 1 ? 1 : 0; } } } return dp[arr.length - 1][s] == 1; } /** * 允许重复拿,只要拿的数额最少就行 * min[i] 拿总额是i的钱,最少是几张钞票 * <p> * 递推公式: * 1.当前的钱币,肯定要比 要拿的总额,要小 * 2.如果选了当前钱币,则数量是:min[i - coins[j]] + 1,不选择当前钱币,则数量是:min[i] * <p> * 从 s = 1,2,3,,,s开始算 * 如果当前的币面值比要拿的金额数要小,那表示有机会。只是有机会。 * 进而【遇到一张小的钞票】再判断,是否拿了这张钱币,就能凑够呢?(第一次是这样的思维,因为min[i]刚开始是一个特别大的值) * 进而【遇到一张大的钞票】再判断,是否拿了这张钱币,就能比原来更少呢?(后面几次,就是优化的流程了) * * @param coins * @param sum * @return */ private static int getMoneyWithLeastNum(int[] coins, int sum) { int[] min = new int[sum + 1]; for (int i = 0; i < min.length; i++) { min[i] = Integer.MAX_VALUE - 1; } min[0] = 0; //要拿的总额,从1开始循环。 for (int i = 1; i <= sum; i++) { System.out.println(i); //循环试探每一张钱币,看是否满足条件: //1.当前的钱币,肯定要比 要拿的总额,要小 //2.如果选了当前钱币,则数量是:min[i - coins[j]] + 1,不选择当前钱币,则数量是:min[i] for (int j = 0; j < coins.length; j++) { if (coins[j] <= i) { int a = min[i - coins[j]] + 1; //用当前钞票,看看看看是否能凑够、能优化 int b = min[i]; //不取当前钞票,但是之前已经有别的钞票,能凑够了,可能就是数量多一点而已。 if (a < b) { min[i] = min[i - coins[j]] + 1; } } } } return min[sum]; } /** * 计算不相邻的数字,4,1,1,9。选择某个数字,就没法选相邻的 * 这个是非递归的,也可以写一个递归的 * 递推公式较为简单: * dp[i] = Math.max(dp[i - 1],arr[i] + dp[i - 2]) * * @param arr * @return */ private static int calcNotXianglin(int[] arr) { int[] dp = new int[arr.length]; //初始化好dp,就可以从i= 2开始递归了 dp[0] = arr[0]; dp[1] = Math.max(arr[0], arr[1]); for (int i = 2; i < dp.length; i++) { int notSelected = dp[i - 1]; int selected = arr[i] + dp[i - 2]; dp[i] = Math.max(notSelected, selected); } return dp[dp.length - 1]; } /** * 打劫房屋问题,和上面的 计算不相邻是一个问题。但是这个解法是用两个变量保存状态,理解起来不如上一个方法。 * res2是到目前为止,最大的值 * res1是到目前为止,上一个最大的值 * 所以在进入下一个循环的时候,res2 表示上一个最大的,res1 表示上两个最大的 * 递推公式也就不难理解了:res3 = Math.max(res2, res1 + arr[i]); * 循环结束的时候,依次把 res1 = res2,res2 = res3;把值更新掉。 * @param arr * @return */ private static int houseRobber(int[] arr) { // write your code here int len = arr.length; if (len == 0) return 0; int res1 = 0; int res2 = arr[0]; if (len == 1) { return res2; } for (int i = 1; i < len; i++) { int res3 = Math.max(res2, res1 + arr[i]); res1 = res2; res2 = res3; } return res2; } /** * 打劫系列:https://www.cnblogs.com/Revenent-Blog/p/7569620.html * * 成环打劫:0个和n-1个,是连接在一起的,所以取了0,就不能取 n-1 * 思路和第一种一样,但是要用两个dp数组去维护,算两次 * @param nums * @return */ public static int houseRobber2(int[] nums) { // write your code here if(nums.length==0||nums.length==2||nums==null){ return 0; } if(nums.length==1){ return nums[0]; } int[] DP_1 = new int[nums.length-1]; int[] DP_2 = new int[nums.length-1]; //不打劫最后一所房子则从第一所房子开始打劫 for(int i=0;i<nums.length-1;i++){ if(i==0){ DP_1[i] = nums[0]; } if(i==1){ DP_1[i] = Math.max(nums[1],DP_1[0]); } if(i>1){ DP_1[i] = Math.max(DP_1[i-2]+nums[i],DP_1[i-1]); } } //打劫最后一所房子则从第二所房子开始打劫 for(int i=1;i<nums.length;i++){ if(i==1){ DP_2[i-1] = nums[1]; } if(i==2){ DP_2[i-1] = Math.max(nums[2],DP_2[0]); } if(i>2){ DP_2[i-1] = Math.max(DP_2[i-3]+nums[i],DP_2[i-2]); } } return DP_1[nums.length-2]>DP_2[nums.length-2]?DP_1[nums.length-2]:DP_2[nums.length-2]; } /** * 选任务,获得收益最大。 * 每个任务都会给定时间,如:任务1,1-4点。任务2,3-5点。 * <p> * 我这是最简单的一个实现,人为地把最理想的数据都给出来了prev数组就是在作弊,只用了一个递推公式去解决问题的 * 如果选这个job的收益:vi + opt[prev[i]] * 如果不选这个job的收益:opt[i - 1] * opt[i] = Math.max(选择,不选) * * @param t * @param prev * @return */ private static int doTask(int[] t, int[] prev) { int[] opt = new int[t.length]; for (int i = 0; i < opt.length; i++) { int prevVal = 0; if (prev[i] != -1) { prevVal = opt[prev[i]]; } int notSelected = 0; if (i > 0) { notSelected = opt[i - 1]; } opt[i] = Math.max(t[i] + prevVal, notSelected); } return opt[opt.length - 1]; } /** * 这次输入的是一个二维数组,而不是人为计算那些值,但是用的递推公式 还是不变的 * 这次要手工计算 prev 数据 * * @param jobs * @return */ private static int doTask2(int[][] jobs) { //先对结束时间排个序 Arrays.sort(jobs, Comparator.comparing(arr1 -> arr1[1], (a, b) -> a - b)); //创建dp数据,dp[i]表示总共i个任务的最好值。 int[] dp = new int[jobs.length]; // 给dp[0]初始化一个值,可以避免接下来循环的时候,从0循环,还是从1循环的尴尬 //从0需要判断,0-1 = -1;而从1开始,则不需要尴尬。因为1-1=0,而dp[i]已经有值了 dp[0] = jobs[0][2]; for (int i = 1; i < jobs.length; i++) { //不选当前这个任务 dp[i] = dp[i - 1]; //选择这个任务 int curVal = jobs[i][2]; for (int j = i; j >= 0; j--) { if (jobs[i][0] >= jobs[j][1]) { curVal += dp[j]; break; } } dp[i] = Math.max(dp[i], curVal); } return dp[dp.length - 1]; } /** * 从网上抄来的,切刚断的第一种方法,把每段刚,分成 Math.max(如果不切 , 切了); * 切了可以有很多种,不一定是分成两段,可以分成很多,比如说4,可以是 0+4,1+3,2+2,1+1+2...等等 * 虽然算法里面,写的是把4分成了两端,分别是让i从0-3执行,表示 4 = 0+4,1+3,2+2,3+1, * 但是当进入下一个函数的时候,n就会变成3,变成2,变成1,所以还是会把4,拆解成 很多很多零散的东西, * 最后算出最大值 * * @param p * @param n * @return */ public static int cut(int[] p, int n) { if (n == 0) return 0; int q = Integer.MIN_VALUE; for (int i = 1; i <= n; i++) { q = Math.max(q, p[i - 1] + cut(p, n - i)); } return q; } /** * 自己写cut * * @param p * @param n * @return */ public static int cut2(int[] p, int n) { if (n == 1) { return 1; } if (n == 0) { return 0; } int q = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { q = Math.max(q, p[n - i - 1] + cut(p, i)); } return q; } /** * 自己写cut,利用了备忘录的方法,将计算的过程存储起来,避免不必要的递归调用 * 假设n,不会超过 p.length - 1,否则就爆了 * * @param p * @param n * @return */ public static int cut3(int[] p, int n) { //r[i] 表示计算过的 p[i] int[] r = new int[p.length]; for (int i = 0; i < r.length; i++) { r[i] = -1; } return cut3Action(p, n, r); } private static int cut3Action(int[] p, int n, int[] r) { if (r[n] > 0) { return r[n]; } // if (n == 1) { // return 1; // } if (n == 0) { return 0; } int q = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { q = Math.max(q, p[n - i - 1] + cut3Action(p, i, r)); } r[n] = q; return q; } /** * 动态规划的问题,不用递归,同样也是用一个数组,把之前计算过的数据,存储起来 * 递推公式:ri 是长度为i的时候切割的最大值。ri = r[i-j] + r[j],j = 0,1,,,i * * @param p * @param n * @return */ public static int cut4(int[] p, int n) { //r[i] 表示计算过的 p[i] int[] r = new int[p.length + 1]; //先给初始化好 for (int i = 1; i < r.length; i++) { r[i] = p[i - 1]; } for (int i = 1; i < r.length; i++) { int q = -1; for (int j = 1; j <= i; j++) { q = Math.max(q, r[i - j] + r[j]); } r[i] = q; } return r[n]; } } <file_sep>/src/main/java/com/springmvc/lxy/exec/Exec1.java package com.springmvc.lxy.exec; /** * 描述: java 练习 * <p> * * @author: harry * @date: 2018-12-31 **/ public class Exec1 { public static void main(String[] args) { System.out.println(); //整型变量 int a = 1; int b = 1; int c = a + b; System.out.println("整型变量:" + c); //浮点类型变量 double a1 = 1.5; double b1 = 1.5; double c1 = a1 + b1; System.out.println("浮点类型变量:" + c1); //字符串类型变量 String a11 = "hello "; String b11 = "world"; String c11 = a11 + b11; System.out.println("字符串变量:" + c11); //布尔类型变量 boolean a111 = true; boolean b111 = false; boolean c111 = a111 & b111; System.out.println("布尔类型变量:" + c111); } } <file_sep>/src/main/java/com/springmvc/lxy/other/sort/HeapSort.java package com.springmvc.lxy.other.sort; import java.util.Arrays; /** * 描述: 堆排序(维基百科的) * <p> * * @author: harry * @date: 2018-12-13 **/ public class HeapSort { private int[] arr; public HeapSort(int[] arr) { this.arr = arr; } public static void heapSort(int[] arr) { int len = arr.length -1; for(int i = arr.length/2 - 1; i >=0; i --){ //堆构造 heapAdjust(arr,i,len); } while (len >0){ swap(arr,0,len--); //将堆顶元素与尾节点交换后,长度减1,尾元素最大 heapAdjust(arr,0,len); //再次对堆进行调整 } } /** * * @param arr * @param i * @param len 最后一个值的下标。数组长度为6,则len是5 */ public static void heapAdjust(int[] arr,int i,int len){ int left,right,j ; while((left = 2*i+1) <= len){ //判断当前父节点有无左节点(即有无孩子节点,left为左节点) right = left + 1; //右节点 j = left; //j"指针指向左节点" if(right < len && arr[left] < arr[right]) //右节点大于左节点 j ++; //当前把"指针"指向右节点 if(arr[i] < arr[j]) //将父节点与孩子节点交换(如果上面if为真,则arr[j]为右节点,如果为假arr[j]则为左节点) swap(arr,i,j); else //说明比孩子节点都大,直接跳出循环语句 break; i = j; } } public static void swap(int[] arr,int i,int len){ int temp = arr[i]; arr[i] = arr[len]; arr[len] = temp; } /** * 测试用例 * <p> * 输出: * [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9] */ public static void main(String[] args) { int[] arr = new int[]{3, 5, 3, 0, 8, 6, 1, 5, 8, 6, 2, 4, 9, 4, 7, 0, 1, 8, 9, 7, 3, 1, 2, 5, 9, 7, 4, 0, 2, 6}; int[] arr2 = new int[]{3, 5, 1, 500}; new HeapSort(arr).heapSort(arr2); System.out.println(Arrays.toString(arr2)); } } <file_sep>/src/main/java/com/springmvc/lxy/other/IsToeplitzMatrix_19_01_01.java package com.springmvc.lxy.other; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * 描述: ${description} * <p> * * @author: harry * @date: 2019-01-01 **/ public class IsToeplitzMatrix_19_01_01 { private static final Logger log = LoggerFactory.getLogger(IsToeplitzMatrix_19_01_01.class); public static void main(String[] args) { log.info("***** 2018-01-01...no1【开始】,判断矩阵的一个题目:isToeplitzMatrix"); log.info("***** 2018-01-01...no2【开始】,树的中序遍历的一个题目:isToeplitzMatrix"); log.info("***** 2018-01-01...no3【开始】,栈的一个题目:isToeplitzMatrix"); String[] arr = { "-27276", "D", "+", "+", "C", "D", "+", "-12178", "+" }; // calPoints(arr); int[][] arr2 = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}}; int i = islandPerimeter(arr2); System.out.println(i); binaryGap(22); } public static int binaryGap(int N) { String s = Integer.toBinaryString(N); char[] array = s.toCharArray(); int preIndex = -1; int dis = 0; for (int i = 0; i < array.length; i++) { if (array[i] == '0') { continue; } if (array[i] == '1') { if (preIndex == -1) { preIndex = i; continue; } dis = Math.max(dis, i - preIndex); preIndex = i; } } return dis; } public int peakIndexInMountainArray(int[] A) { boolean small = false; for (int i = 1; i < A.length - 1; i++) { if (A[i] < A[i - 1]) { if (small) { return -1; } } else { small = true; } } return 0; } public int[] diStringMatch(String S) { int n = S.length(), left = 0, right = n; int[] res = new int[n + 1]; for (int i = 0; i < n; ++i) res[i] = S.charAt(i) == 'I' ? left++ : right--; res[n] = left; return res; } public int repeatedNTimes(int[] A) { Map<Integer, Integer> map = new HashMap<>(); for (int i : A) { Integer res = map.get(i); if (res == null) { map.put(i, 1); } else { map.put(i, res + 1); } } int count = A.length / 2; for (Integer integer : map.keySet()) { Integer times = map.get(integer); if (times == count) { return integer; } } return 0; } /** * 岛屿问题,很简单 * * @param grid * @return */ public static int islandPerimeter(int[][] grid) { int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 0) { continue; } count += 4; //上 if (i > 0) { if (grid[i - 1][j] == 1) { count -= 1; } } //下 if (i < grid.length - 1) { if (grid[i + 1][j] == 1) { count -= 1; } } //左 if (j > 0) { if (grid[i][j - 1] == 1) { count -= 1; } } //右 if (j < grid[i].length - 1) { if (grid[i][j + 1] == 1) { count -= 1; } } } } return count; } /** * 修剪二叉树,二叉树是排好序的。要求在[L,R]之间 * 思路:递归解法, * * @param root * @param L * @param R * @return */ public TreeNode trimBSTRec(TreeNode root, int L, int R) { //结束条件 if (root == null) { return null; } //如果root的值,比最小的还小,那就看root的right就行了。 //为什么要返回呢?因为后面的代码是针对该节点的值,在[L,R]范围内的调整, // 进入了这个if判断,就不应该继续走下面的代码了,所以要return if (root.val < L) { return trimBST(root.right, L, R); } //如果root的值,比最大的还大,那就看root的left就行了。 if (root.val > R) { return trimBST(root.left, L, R); } root.left = trimBST(root.left, L, R); root.right = trimBST(root.right, L, R); return root; } /** * 修剪二叉树,二叉树是排好序的。要求在[L,R]之间 * * @param root * @param L * @param R * @return */ public TreeNode trimBST(TreeNode root, int L, int R) { //去掉不在 [L,R] 之间的节点 while (root.val < L || root.val > R) { if (root.val < L) { root = root.right; } if (root.val > R) { root = root.left; } } //去掉左节点上面不符合条件的一些点, // 因为即使root在[L,R]之间,也不一定保证,root.left或者root.right 在[L,R]之间 // 这个循环,就是要去掉比L还小的一些节点。如果root.left比L小,那么就取 比root.left 大的,但是最接近的那个, // 就是root.left.right 去代替 root.left TreeNode dummy = root; while (dummy != null) { while (dummy.left != null && dummy.left.val < L) { //把比dummy.left最接近的一个大的节点,赋值给 dummy.left dummy.left = dummy.left.right; } //再次循环下去,走到dummy.left,判断是否 dummy = dummy.left; } //去掉右节点上面不符合条件的一些点, dummy = root; while (dummy != null) { while (dummy.right != null && dummy.right.val > R) { dummy.right = dummy.right.left; } dummy = dummy.right; } return root; } public static String[] uncommonFromSentences(String A, String B) { String[] split1 = A.split(" "); String[] split2 = B.split(" "); Map<String, Integer> map = new HashMap<>(); for (String s : split1) { Integer integer = map.get(s); if (integer == null) { map.put(s, 1); } else { map.put(s, integer + 1); } } for (String s : split2) { Integer integer = map.get(s); if (integer == null) { map.put(s, 1); } else { map.put(s, integer + 1); } } List<String> result = new ArrayList<>(); for (String s : map.keySet()) { Integer count = map.get(s); if (count == 1) { result.add(s); } } return result.toArray(new String[0]); } public static int calPoints(String[] ops) { Stack<Integer> stack = new Stack<>(); for (String op : ops) { if (op.equals("C")) { stack.pop(); } else if (op.equals("D")) { stack.push(2 * stack.peek()); } else if (op.equals("+")) { int sum = stack.get(stack.size() - 1) + stack.get(stack.size() - 2); stack.push(sum); } else { stack.push(Integer.valueOf(op)); } } Integer sum = stack.stream().mapToInt(i -> i).sum(); // Or // sum = stack.parallelStream().reduce(0, Integer::sum); return sum; } /** * 判断矩阵的一个题目: * [ * [1,2,3], * [4,1,2], * [5,4,1] * ] * 这个节点:"5";"4,4";"1,1,1";"2,2";"3" * * @param matrix * @return */ public static boolean isToeplitzMatrix(int[][] matrix) { for (int i = 0; i < matrix.length - 1; i++) { for (int j = 0; j < matrix[0].length - 1; j++) { if (matrix[i][j] != matrix[i + 1][j + 1]) { return false; } } } return true; } /** * 这个root是排好序的 左 < 根 < 右 * 要输出的结果是:一颗歪脖子树 * left 是null的,只是通过right相连起来。 * * @param root * @return */ public static TreeNode increasingBST(TreeNode root) { //用来当做返回的新的头结点 TreeNode head = null; //访问的上一个节点,因为需要把上一个节点的right设置成当前访问的节点,需要保持一个状态 TreeNode pre = null; Stack<TreeNode> stack = new Stack<>(); TreeNode node = root; while (!stack.isEmpty() || node != null) { //老规矩,访问到最左节点 while (node != null) { stack.push(node); node = node.left; } //除了while以后,node现在是空了 // 出栈,拿到一个node,要把它挂到上一个节点的right上 node = stack.pop(); //head只用一次 if (head == null) { head = node; } //需要保持状态的来了 if (pre != null) { //要把它挂到上一个节点的right上 pre.right = node; } //继承和发展 pre = node; //使命执行结束,可以把left设置成null了,因为后面拿出来的一个节点,它的left 已经被访问过了 pre.left = null; //先坐后右,right可以迟到,但不可以缺席 node = node.right; } return head; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } } <file_sep>/src/main/java/com/springmvc/lxy/dto/TestSpringMvc4Post.java package com.springmvc.lxy.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; /** * 描述: * 1. 大概知道了,"1994-11-25"是Date默认的一种。 * 2. post方法里面,DateTimeFormat,不起作用的,所以testDateFormat2不行。 * 3. post里面一律用JsonFormat,但是序列化 LocalDate,LocalDateTime,LocalTime,有各自不同的限制。比如,LocalDate 不识别 HH,所以一加就会报错。 * 4. date默认是返回 时间戳。 * * <p> * * @author: harry * @date: 2018-08-30 **/ @Data public class TestSpringMvc4Post { //遵守格式可以 "1994-11-25 11"、"1994-11-25 12",但是 "1994-11-25"不行 //输出的时候,还是按照这样的方式输出的:"1994-11-25 11" @JsonFormat(pattern = "yyyy-MM-dd HH", timezone = "GMT+8") private Date testJson; //"1994-11-25" 可以成功,其他都不行。 //输出:785721600000 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date testDateFormat; //"1994-11-25" 可以成功,其他都不行 //输出:785462400000 @DateTimeFormat(pattern = "yyyy-MM") private Date testDateFormat2; //可以:"1994-11-22" private LocalDate localDate; //可以:"1994-11-22" private Date date; //不行 "1994-11-22 12",进不来。 @JsonFormat(pattern = "yyyy-MM-dd HH", timezone = "GMT+8") private LocalDate testJsonLocalDate; //可以的!"1994~11~22",进不来。 @JsonFormat(pattern = "yyyy~MM~dd", timezone = "GMT+8") private LocalDate testJsonLocalDate2; //"1994-11-22 12",进不来。大概猜测了一下,是因为 LocalDate,不知道怎么去解析 HH,所以就失败了。 @DateTimeFormat(pattern = "yyyy-MM-dd HH") private LocalDate testDateFormatLocalDate; //可以进来!"1994-11-22~~11:12:11"。 @JsonFormat(pattern = "yyyy-MM-dd~~HH:mm:ss", timezone = "GMT+8") private LocalDateTime testJsonLocalDateTime; // 还是这样的:2019-02-26 00~~33 @JsonFormat(pattern = "yyyy-MM-dd HH~~mm", timezone = "GMT+8") @JsonSerialize(using = LocalDateTimeSerializer.class) private LocalDateTime extendJsonLocalDate; //这个没用,还是相当于默认的:2019-02-26 00:33:15 @DateTimeFormat(pattern = "yyyy-MM-dd HH") private LocalDateTime extendDateFormatLocalDate; //默认的:2019-02-26 00:33:15 private LocalDateTime extendLocalDate; //输出时间戳 :1551112395575 private Date extendDate; //输出格式:"2019-02-26 00~~36" @JsonFormat(pattern = "yyyy-MM-dd HH~~mm", timezone = "GMT+8") private Date extendDateWithJsonFormat; //输出时间戳 :1551112395575 @DateTimeFormat(pattern = "yyyy-MM-dd HH") private Date extendDateWithDateFormat; } <file_sep>/src/main/java/com/springmvc/lxy/other/Exec_19_02_01.java package com.springmvc.lxy.other; import java.util.Arrays; import java.util.Stack; /** * 描述: ${description} * <p> * * @author: harry * @date: 2019-02-01 **/ public class Exec_19_02_01 { public static void main(String[] args) { Exec_19_02_01 client = new Exec_19_02_01(); int[] arr = {7, 1, 5, 3, 6, 4}; System.out.println(client.maxProfit2(arr)); int[] arr2 = {3, 3}; System.out.println(client.containsDuplicate(arr2)); ; int[] arr3 = {5, 5, 5, 10, 20}; System.out.println(client.lemonadeChange(arr3)); ; } private int sum = 0; /** * bst变成更大树: * 非常漂亮的一个解法! * 观察到,其实每次都是把最右面的子树值,加到root,和left上,然后把root加到left上,搞定。 * 所以每次先遍历right,然后累加到root上以后,再把root,累加到sum 上。 * * @param root * @return */ public TreeNode convertBST(TreeNode root) { if (root != null) { convertBST(root.right); sum += root.val; root.val = sum; convertBST(root.left); } return root; } /** * 上面是递归的招数,接下来要改成迭代的招数。 * @param root * @return */ public TreeNode convertBST2(TreeNode root) { return null; } /** * 找零钱问题:买东西的零钱只有5,10,20,那就好办了 * * @param bills * @return */ public boolean lemonadeChange(int[] bills) { int fives = 0; int tens = 0; for (int i = 0; i < bills.length; i++) { if (bills[i] == 5) { fives++; } else if (bills[i] == 10) { if (fives == 0) { return false; } fives--; tens++; } else { if (tens == 0) { if (fives < 3) { return false; } fives -= 3; } else { if (fives == 0) { return false; } tens--; fives--; } } } return true; } public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { return true; } } return false; } /** * 看t是不是s的 anagram:由颠倒字母顺序而构成的字[短语] * 思路: * 1. 对两个s、t进行排序,然后比较,最简单 * 2. 用一个int[26]table,然后s进行++,t进行--,最后结果应该是,数组里面的值,都是0 * 3. 搞一个hashmap<char,integer> * * @param s * @param t * @return */ public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } char[] str1 = s.toCharArray(); char[] str2 = t.toCharArray(); Arrays.sort(str1); Arrays.sort(str2); return Arrays.equals(str1, str2); } /** * 上一个递归解法,很难。但是包含了递归的一些精髓。 * 这个解法理解起来要容易很多。 * * @param prices * @return */ public int maxProfit2(int[] prices) { int i = 0; int max = 0; while (i < prices.length - 1) { //首先,找一个低谷 while (i < prices.length - 1 && prices[i] >= prices[i + 1]) { i++; } int vally = prices[i]; //第二,找一个高峰 while (i < prices.length - 1 && prices[i] <= prices[i + 1]) { i++; } int peak = prices[i]; max = max + (peak - vally); } return max; } /** * 比较有趣的一个题: * 数组prices 表示 第i天的股票是 prices[i] 的钱 * 如果要获取最大的收益,应该怎么买卖? * <p> * 刚开始第一道,就是这么难的题目。 * 这是一个常规解法,其实还是有一种动态规划的意味在其中。 * * @param prices * @return */ public int maxProfit(int[] prices) { return calcMaxProfit(prices, 0); } private int calcMaxProfit(int[] prices, int start) { if (start >= prices.length) { return 0; } int max = 0; //循环遍历数组中的每个数字 for (int i = start; i < prices.length; i++) { //买当前数字i,对后续数字进行一个买卖,记录每次不同的利润 int maxProfit = 0; //循环遍历后面的每一个数字 for (int j = i + 1; j < prices.length; j++) { //如果后面的数字比前面的数字更大 if (prices[j] > prices[i]) { //进行计算从当前这个数字开始,能得到的利润maxProfit //maxProfit = 从当前的后面的后面(j+1 = i+ 2)那个数字开始的利润 + (后面那个数字 - 当前数字) //j+1是一个核心,因为1,后面是5,但是不从5开始,因为5,只能是卖,最快只能是从3开始 int profit = calcMaxProfit(prices, j + 1) + prices[j] - prices[i]; //由于从当前第i个数字开始,以后每个比i大的数字,都会计算一遍利润 //取最大的利润 maxProfit = Math.max(maxProfit, profit); } } //每个i数字,所能产生的利润,到这里,maxProfit 已经代表了每个数字,所能产生的最大利润maxProfit //更新到max上,取这一波数字 0,1,2...i,所能产生的最大 max = Math.max(max, maxProfit); } return max; } int calc(int[] pieces, int start) { int max = 0; if (start >= pieces.length) { return 0; } for (int i = start; i < pieces.length; i++) { int maxProfit = 0; for (int j = i + 1; j < pieces.length; j++) { if (pieces[i] < pieces[j]) { int profit = calcMaxProfit(pieces, j + 1) + pieces[j] - pieces[i]; maxProfit = Math.max(maxProfit, profit); } } max = Math.max(maxProfit, max); } return max; } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } } <file_sep>/src/main/java/com/springmvc/lxy/service/impl/UserServiceImple.java package com.springmvc.lxy.service.impl; import com.springmvc.lxy.service.UserService; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 描述: ${description} * <p> * * @author: harry * @date: 2018-08-31 **/ @Service public class UserServiceImple implements UserService { @Override public String getUser1() { System.out.println("use1"); return "user1"; } public static void main(String[] args) { //replace和replaceAll,都不动原来的src,只返回一个新的string // String src = new String("ab43a2c43d"); // System.out.println(src.replace("3", "f") + "---" + src); // System.out.println(src.replace('3', 'f') + "---" + src); // System.out.println(src.replaceAll("\\d", "f") + "---" + src); // System.out.println(src.replaceAll("a", "f") + "---" + src); // System.out.println(src.replaceFirst("\\d", " f") + "---" + src); // System.out.println(src.replaceFirst("4", "h") + "---" + src); UserServiceImple userServiceImple = new UserServiceImple(); String hello = userServiceImple.toLowerCase("Hello"); System.out.println(hello); } public int numUniqueEmails(String[] emails) { Set<String> set = new HashSet<>(); for (String email : emails) { String[] strings = email.split("@"); String local = strings[0]; String domain = strings[1]; local = local.replace(".", ""); local = getRidOfPlus(local); set.add(local + "@" + domain); } return set.size(); } public String toLowerCase(String str) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ((int) c <= 90 && (int) c >= 65) { chars[i] = (char) ((int) c + 32); } } return new String(chars); } private String getRidOfPlus(String local) { if (local.contains("+")) { int index = local.indexOf("+"); String pre = local.substring(0, index); local = pre; return getRidOfPlus(local); } return local; } } <file_sep>/src/test/java8/SpliteratorTest.java package java8; import lombok.Getter; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * 描述: ${description} * <p> * * @author: harry * @date: 2018-09-09 **/ public class SpliteratorTest { /** * 方法一:函数版本 * @param s * @return */ public int countWordsIteratively(String s) { int counter = 0; boolean lastSpace = true; for (char c : s.toCharArray()) { if (Character.isWhitespace(c)) { lastSpace = true; } else { if (lastSpace) { counter++; lastSpace = false; } } } return counter; } public static void main(String[] args) { int count = new SpliteratorTest().countWordsIteratively("abc sdf 123"); System.out.println(count ); final String SENTENCE = " Nel mezzo del cammin di nostra vita " + "mi ritrovai in una selva oscura" + " ché la dritta via era smarrita "; Stream<Character> characterStream = IntStream.range(0, SENTENCE.length()) .mapToObj(SENTENCE::charAt); // int i = new Counter(0,false).countWords(characterStream); // System.out.println(i); System.out.println("Found " + new Counter(0, false).countWords(characterStream) + " words"); Spliterator<Character> spliterator = new WordCounterSpliterator(SENTENCE); Stream<Character> stream = StreamSupport.stream(spliterator, true); System.out.println("Found " + new Counter(0, false).countWords(stream) + " words"); } } /** * 方法二:流式,lastIsSpace 表示前面是不是空格 */ @Getter class Counter { private final int counter; private final boolean lastIsSpace; public Counter(int counter, boolean lastIsSpace) { this.counter = counter; this.lastIsSpace = lastIsSpace; } public Counter acculate(Character c) { if (Character.isWhitespace(c)) { return this.lastIsSpace ? this : new Counter(counter, true); } else { return this.lastIsSpace ? new Counter(counter + 1, false) : this; } } public Counter combie(Counter param) { return new Counter(this.counter + param.getCounter(), param.isLastIsSpace()); } public int countWords(Stream<Character> stream) { Counter reduce = stream.reduce(new Counter(0, true), (p, p2) -> p.acculate(p2), Counter::combie); // Counter reduce = stream.reduce(new Counter(0,true),(p,p2) -> p.acculate(p2)); return reduce.getCounter(); } } /** * 方法三:分割器 */ class WordCounterSpliterator implements Spliterator<Character> { private final String string; /** * 这个变量在trySplit中没什么卵用 * 在 tryAdvance 中需要判断是不是还有要遍历的Character */ private int currentChar = 0; public WordCounterSpliterator(String string) { System.out.println(string); this.string = string; } /** * 这个currentChar变量的值,是上一次切分出去的WordCounterSpliterator的末位值 * 和这次的string无关,还是可以判断的 * @param action * @return */ @Override public boolean tryAdvance(Consumer<? super Character> action) { action.accept(string.charAt(currentChar++)); return currentChar < string.length(); } @Override public Spliterator<Character> trySplit() { int currentSize = string.length() - currentChar; if (currentSize < 10) { return null; } for (int splitPos = currentSize / 2 + currentChar; splitPos < string.length(); splitPos++) { if (Character.isWhitespace(string.charAt(splitPos))) { Spliterator<Character> spliterator = new WordCounterSpliterator(string.substring(currentChar, splitPos)); currentChar = splitPos; return spliterator; } } return null; } @Override public long estimateSize() { return string.length() - currentChar; } @Override public int characteristics() { return ORDERED + SIZED + SUBSIZED + NONNULL + IMMUTABLE; } } <file_sep>/src/main/java/com/springmvc/lxy/other/SelfDividingNumbers.java package com.springmvc.lxy.other; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; /** * 描述: ${description} * <p> * * @author: harry * @date: 2018-11-18 **/ public class SelfDividingNumbers { public static void main(String[] args) { SelfDividingNumbers client = new SelfDividingNumbers(); System.out.println("no1..."); int left = 1; int right = 22; List<Integer> integers = client.selfDividingNumbers(left, right); System.out.println(JSONObject.toJSONString(integers)); System.out.println("\nno2..."); int[] arr = {1, 4, 3, 2}; int sum = client.arrayPairSum(arr); System.out.println(sum); System.out.println("\nno2...快速排序"); int[] arr2 = {1, 4, 3, 2}; client.quickSort(arr2,0,arr2.length-1); System.out.println(JSONObject.toJSONString(arr2)); } /** * 非常简单的思路:判断每一个数字的每一位 * 实现的比较不错 * * @param left * @param right * @return */ public List<Integer> selfDividingNumbers(int left, int right) { List<Integer> res = new ArrayList<>(); for (int i = left; i <= right; i++) if (dividingNumber(i)) res.add(i); return res; } boolean dividingNumber(int num) { for (int n = num; n > 0; n = n / 10) { if (n % 10 == 0 || num % (n % 10) != 0) { return false; } } return true; } public int adjustArr(int[] nums, int left, int right) { int temp = nums[left]; while (left < right) { while(left < right && nums[right] > temp){ right--; } if (left < right) { nums[left] = nums[right]; left ++; } while(left < right && nums[left] < temp){ left++; } if (left < right) { nums[right] = nums[left]; right --; } } nums[left] = temp; return left; } public void quickSort(int[] nums, int left, int right) { if (left < right) { int i = adjustArr(nums, left, right); quickSort(nums, left, i - 1); quickSort(nums, i + 1, right); } } public int arrayPairSum(int[] nums) { //jdk 工具类 // Arrays.sort(nums); //冒泡排序 // for (int i = 0; i < nums.length - 1; i++) { // for (int j = i + 1; j < nums.length; j++) { // if (nums[i] > nums[j]) { // int temp = nums[i]; // nums[i] = nums[j]; // nums[j] = temp; // } // } // } quickSort(nums,0,nums.length - 1); int sum = 0; for (int i = 0; i < nums.length; i += 2) { sum += nums[i]; } return sum; } } <file_sep>/src/main/java/com/springmvc/lxy/other/Exec_19_01_27.java package com.springmvc.lxy.other; import java.util.*; /** * 描述: ${description} * <p> * * @author: harry * @date: 2019-01-27 **/ public class Exec_19_01_27 { public static void main(String[] args) { ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); ListNode listNode4 = new ListNode(4); listNode1.next = listNode2; listNode2.next = listNode3; listNode3.next = listNode4; ListNode listNode = reverseList2(listNode1); System.out.println(); } /** * 用前序遍历的方式,拿到一个str * * @param t * @return */ public String tree2str(TreeNode t) { if (t == null) { return ""; } String result = t.val + ""; String left = tree2str(t.left); String right = tree2str(t.right); if (left == "" && right == "") return result; if (left == "") return result + "()" + "(" + right + ")"; if (right == "") return result + "(" + left + ")"; return result + "(" + left + ")" + "(" + right + ")"; } /** * 获取 次数超过 nums.length 的数字 * 【这个答案神了。。。】 * 和com.springmvc.lxy.other.Exec_19_01_21#countBinarySubstrings(java.lang.String) 很像,可以参照一下。 * * @param num * @return */ public int majorityElement(int[] num) { int major = num[0], count = 1; for (int i = 1; i < num.length; i++) { if (count == 0) { count++; major = num[i]; } else if (major == num[i]) { count++; } else count--; } return major; } // Sorting public int majorityElement1(int[] nums) { Arrays.sort(nums); return nums[nums.length / 2]; } // Hashtable public int majorityElement2(int[] nums) { Map<Integer, Integer> myMap = new HashMap<Integer, Integer>(); //Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>(); int ret = 0; for (int num : nums) { if (!myMap.containsKey(num)) myMap.put(num, 1); else myMap.put(num, myMap.get(num) + 1); if (myMap.get(num) > nums.length / 2) { ret = num; break; } } return ret; } /** * 一个链表是 4,1,5,9。只给一个节点node,让你删除。。。 * 牛逼。。。 * * @param node */ public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } /** * 计算 a+b ,但是不能用 + * https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently * * @param a * @param b * @return */ public int getSum(int a, int b) { if (a == b) { return 2 * a; } return (a * a - b * b) / (a - b); } /** * 思路:还是用一个dfs 去搜索,搜索 (k - currentNode.val) 的值 * * @param root * @param k * @return */ public boolean findTarget(TreeNode root, int k) { Set<Integer> set = new HashSet<>(); return dfs(root, set, k); } private boolean dfs(TreeNode root, Set<Integer> set, int k) { if (root == null) { return false; } if (set.contains(k - root.val)) { return true; } set.add(root.val); return dfs(root.left, set, k) || dfs(root.right, set, k); } /** * 递归版本: * 1.每次都用head.next进行迭代,如果已经到了末尾的一个,那就直接return * 2.递归调用的返回值,是原来链表的最后一个值,这个值不动它 * 3.每次递归调用回来的处理:先拿出当前head.next,然后把当前head,缀到head.next 的 next上面 * 4.把head.next = null,因为head.next已经没用了,而且head也已经缀到了最后一个上面。 * * @param head * @return */ public static ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode listNode = reverseList(head.next); ListNode next = head.next; next.next = head; head.next = null; return listNode; } public static ListNode reverseList2(ListNode head) { if (head == null) { return null; } ListNode cur = head; ListNode prev = null; ListNode next = null; while (cur != null) { next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static class ListNode { int val; ListNode next; public ListNode(int x) { val = x; } } } <file_sep>/README.md # springmvc-study 学习spring-mvc的一个项目 <file_sep>/src/main/java/com/springmvc/lxy/programlearn/Exec2.java package com.springmvc.lxy.programlearn; /** * 描述: * <p> * <p> * harryliu * 2019/1/20 */ public class Exec2 { public static void main(String[] args) { int q = 3; if (q > 20) { System.out.println("java好无聊"); } else { System.out.println("继续学习"); } //变量 int[] arr={3,6,7,8,5} ; for(int a=4;a>-1;a=a-1){ System.out.println(arr[a] ); } } }<file_sep>/src/main/java/com/springmvc/lxy/other/Exec_19_01_16.java package com.springmvc.lxy.other; import com.google.common.collect.Lists; import java.util.*; /** * 描述: ${description} * <p> * * @author: harry * @date: 2019-01-16 **/ public class Exec_19_01_16 { public static void main(String[] args) { int a = 'Z'; System.out.println(a); System.out.println("1:" + reverseOnlyLetters("a-bC-dEf-ghIj")); System.out.println("2:" + reverseOnlyLetters2("a-bC-dEf-ghIj")); int[][] arr = {{1, 2}, {3, 4}}; System.out.println("3:" + surfaceArea(arr)); String s = "a1b2"; System.out.println("1:" + letterCasePermutation(s)); ; System.out.println("2:" + letterCasePermutation2(s)); ; } /** * 判断数组是不是单调的。。。 * 越做越跑偏了。。。 * * @param A * @return */ public boolean isMonotonic(int[] A) { if (A.length == 1) { return true; } boolean big = A[1] >= A[0]; for (int i = 1; i < A.length; i++) { if (A[i] == A[i - 1]) { continue; } if (big != A[i] > A[i - 1]) { return false; } } return true; } /** * 这个解答更好一点! * 老老实实拿一个变量判断一下,如果是增长,就这样,如果不增长,就这样; * * @param A * @return */ public boolean ismonotonic2(int[] A) { boolean increasing = (A[A.length - 1] - A[0]) > 0 ? true : false; for (int i = 0; i < A.length - 1; i++) { // if equal, we never hit either condition if (increasing) { if (A[i] > A[i + 1]) return false; } else { if (A[i] < A[i + 1]) return false; } } return true; } /** * Input: S = "a1b2" * Output: ["a1b2", "a1B2", "A1b2", "A1B2"] * 这个题有点意思:用递归的方式更好做。 * * @param S * @return */ public static List<String> letterCasePermutation(String S) { List<String> s = new ArrayList<String>(); if (S == null) { return new ArrayList<>(); } util(S.toCharArray(), s, 0); return s; } /** * 用递归是最好的一种解决办法! * * @param c_arr * @param s * @param index */ public static void util(char[] c_arr, List<String> s, int index) { //下标到了最后的末尾,说明这一次遍历已经结束了,添加到list中,并返回 if (index == c_arr.length) { s.add(new String(c_arr)); return; } //如果是数字直接就来,index+1 if (Character.isDigit(c_arr[index])) { util(c_arr, s, index + 1); return; } //换成小写来一波 c_arr[index] = Character.toLowerCase(c_arr[index]); util(c_arr, s, index + 1); //换成大写来一波 c_arr[index] = Character.toUpperCase(c_arr[index]); util(c_arr, s, index + 1); } /** * 这个方法思路很奇特,但是最后的结果是不可用,因为会有这样的结果 * a1b2 => [2b1a, 2b1A, 2B1a, 2B1A] * * @param S * @return */ public static List<String> letterCasePermutation2(String S) { if (S == null) { return new ArrayList<>(); } List<String> s = perm(S, 0); return s; } private static List<String> perm(String s, int i) { if (s.equalsIgnoreCase("")) { ArrayList<String> objects = new ArrayList<>(); objects.add(""); return objects; } List<String> res = new ArrayList<>(); String substring = s.substring(i + 1, s.length()); List<String> ans = perm(substring, 0); for (String an : ans) { if (Character.isDigit(s.charAt(i))) { res.add(an + s.charAt(i)); } else { res.add(an + ("" + s.charAt(i)).toLowerCase()); res.add(an + ("" + s.charAt(i)).toUpperCase()); } } return res; } /** * 给定一个数组,用这个数组里面的数字,凑成三角形三边长,使得面积最大 * * @param A * @return */ public int largestPerimeter(int[] A) { Arrays.sort(A); int ci = A.length - 1; while (ci > 1) { int c = A[ci]; int a = A[ci - 1]; int b = A[ci - 2]; if (a + b > c) return a + b + c; ci--; } return 0; } /** * 每次可以拿 1--3个,我先手 * * @param n * @return */ public boolean canWinNim(int n) { if (n < 4) { return true; } //只要给对方留下一个4,我就赢了 if (n % 4 == 0) { return false; } return true; } /** * 越坐越偏了。。。 * * @param grid * @return */ public static int surfaceArea(int[][] grid) { int line = 0; for (int i = 0; i < grid.length; i++) { line += Arrays.stream(grid[i]).max().getAsInt(); } int zeroCount = 0; for (int i = 0; i < grid[0].length; i++) { int max = 0; for (int j = 0; j < grid.length; j++) { max = Math.max(max, grid[j][i]); if (grid[j][i] == 0) { zeroCount++; } } line += max; } line = (line + grid.length * grid[0].length) * 2; return line - zeroCount * 2; } /** * 把这道题理解复杂了。。。 * 其实很简单:如果a、b相等,那肯定不行 * 如果a、b不等,那么就取大的就行 * * @param a * @param b * @return */ public int findLUSlength(String a, String b) { if (a.equals(b)) return -1; return Math.max(a.length(), b.length()); } /** * 类似于这种的:a-bC-dEf-ghIj,除了字母之外,其他的符号不能动:j-Ih-gfE-dCba * 所以说,用一个栈去保存字母的顺序,然后pop出来,达到逆转的效果。 * <p> * 有一个快排的答案不错。 * * @param S * @return */ public static String reverseOnlyLetters(String S) { char[] array = S.toCharArray(); char[] res = new char[array.length]; Stack<Character> stack = new Stack<>(); //先把对应的符号放到位置上,字母先存起来,因为要逆转,所以用栈 for (int i = 0; i < array.length; i++) { if (97 <= array[i] && array[i] <= 122 || 65 <= array[i] && array[i] <= 90) { stack.push(array[i]); } res[i] = array[i]; } for (int i = 0; i < array.length; i++) { if (97 <= array[i] && array[i] <= 122 || 65 <= array[i] && array[i] <= 90) { res[i] = stack.pop(); } } return new String(res); } /** * 快排的解决方法,真的非常好 * * @param S * @return */ public static String reverseOnlyLetters2(String S) { char[] array = S.toCharArray(); int left = 0; int right = array.length - 1; while (left < right) { while (left < right && !isAlphabet(array[left])) { left++; } while (left < right && !isAlphabet(array[right])) { right--; } char c = array[left]; array[left++] = array[right]; array[right--] = c; } return new String(array); } public static boolean isAlphabet(char c) { if (97 <= c && c <= 122 || 65 <= c && c <= 90) { return true; } return false; } /** * 翻转二叉树,我擦完美啊! * 翻转左,翻转右,翻转本身 * * @param root * @return */ public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } invertTree(root.left); invertTree(root.right); TreeNode left = root.left; root.left = root.right; root.right = left; return root; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } } <file_sep>/src/main/java/com/springmvc/lxy/other/SearchINBST.java package com.springmvc.lxy.other; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * 描述: ${description} * <p> * * @author: harry * @date: 2018-12-08 **/ public class SearchINBST { private static final Logger log = LoggerFactory.getLogger(SortArrayByPartition2.class); public static void main(String[] args) { SearchINBST client = new SearchINBST(); log.info("\n***** 2018-12-08...no1,在bst中搜索:"); log.info("\n***** 2018-12-08...result:{}"); log.info("\n***** 2018-12-08...no2,smallestRangeI:"); int[] A = {1, 3, 6}; int K = 3; int i = client.smallestRangeI(A, K); log.info("\n***** 2018-12-08...result:{}", i); log.info("\n***** 2018-12-08...no3,maxDepth:"); log.info("\n***** 2018-12-08...no4,transpose:"); int[][] arr = {{1, 2, 3}, {4, 5, 6}}; int[][] transpose = client.transpose(arr); log.info("\n***** 2018-12-08...no4,result:{}", JSON.toJSONString(transpose)); log.info("\n***** 2018-12-08...no5,middleNode:"); log.info("\n***** 2018-12-08...no6,subdomainVisits:"); String[] arr2 = {"9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"}; List<String> strings = client.subdomainVisits(arr2); log.info("\n***** 2018-12-08...no6,subdomainVisits:{}",strings); log.info("\n***** 2018-12-08...no7,reverseWords:"); String str = "Let's take LeetCode contest"; String s = client.reverseWords(str); log.info("\n***** 2018-12-08...no7 ends,reverseWords:{}",s); log.info("\n***** 2018-12-08...no8【开始】,shortestToChar",s); String S = "loveleetcode"; char C = 'e'; int[] ints = client.shortestToChar2(S, C); log.info("\n***** 2018-12-08...no8【结束】,shortestToChar:{}",JSON.toJSONString(ints)); log.info("\n***** 2018-12-08...no9【开始】,findComplement",s);/**/ int num = 5; int result = client.findComplement(num); log.info("\n***** 2018-12-08...no9【结束】,findComplement:{}",result); } /** * 非常棒的一个算法: * 先获取num对应的二进制数:从RIGHTMOST创建一个N位为1的位掩码。我们可以使用体面的Java内置函数Integer.highestOneBit来获得LEFTMOST位1,左移1,然后减1。 * 对输入的数字可以取反 num = ~num * or num和mask ^ * or ~num和mask & * @param num * @return */ public int findComplement(int num) { int mask = (Integer.highestOneBit(num) << 1) - 1; return num ^ mask; } /** * @param root * @param val * @return */ public TreeNode searchBST(TreeNode root, int val) { if (root == null) { return null; } if (root.val == val) { return root; } if (val > root.val) { return searchBST(root.left, val); } return searchBST(root.right, val); } /** * @param root * @param val * @return */ public TreeNode searchBST2(TreeNode root, int val) { while (root != null && root.val != val) { root = val < root.val ? root.left : root.right; } return null; } public int smallestRangeI(int[] A, int K) { if (A.length == 1) { return 0; } int max = A[0]; int min = A[0]; for (int i : A) { if (i > max) { max = i; } if (i < min) { min = i; } } if (max - min > 2 * K) { return max - min - 2 * K; } return 0; } /** * 欣赏一个写的更简洁的版本 * * @param A * @param K * @return */ public int smallestRangeI2(int[] A, int K) { int mx = A[0], mn = A[0]; for (int a : A) { mx = Math.max(mx, a); mn = Math.min(mn, a); } return Math.max(0, mx - mn - 2 * K); } /** * 求深度:递归方式 * * @param root * @return */ public int maxDepth(Node root) { if (root == null) { return 0; } if (root.children == null || root.children.size() == 0) { return 1; } int maxLength = 1; for (Node child : root.children) { maxLength = Math.max(maxLength, maxDepth(child) + 1); } return maxLength; } /** * 求深度:非递归方式 * 巧妙的利用了queue的size,作为一个边界值进行计算。把每个从queue中poll出来的,继续再把其子节点放进去 * * @param root * @return */ public int maxDepth2(Node root) { if (root == null) { return 0; } Queue<Node> queue = new LinkedList<>(); queue.offer(root); int dept = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { Node poll = queue.poll(); for (Node child : poll.children) { queue.offer(child); } } dept++; } return dept; } public int[][] transpose(int[][] A) { if (A == null) { return null; } int[][] result = new int[A[0].length][A.length]; for (int i = 0; i < A[0].length; i++) { int[] temp = new int[A.length]; for (int i1 = 0; i1 < A.length; i1++) { temp[i1] = A[i1][i]; } result[i] = temp; } return result; } /** * 更简洁的这种方式! * * @param A * @return */ public int[][] transpose2(int[][] A) { int[][] result = new int[A[0].length][A.length]; for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[0].length; j++) { result[j][i] = A[i][j]; } } return result; } /** * 一串节点的中间节点:快慢节点 * 只用快的节点计算就行了。两者同时出发。 * * @param head * @return */ public ListNode middleNode(ListNode head) { if (head == null || head.next == null) { return head; } ListNode middleNode = head; ListNode fastNode = head; while (fastNode != null && fastNode.next != null) { middleNode = middleNode.next; fastNode = fastNode.next == null ? null : fastNode.next.next; } return middleNode; } public List<String> subdomainVisits(String[] cpdomains) { Map<String, Integer> map = new HashMap<>(); for (String cpdomain : cpdomains) { String[] strings = cpdomain.split(" "); Integer n = Integer.valueOf(strings[0]); String s = strings[1]; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '.') { String d = s.substring(i + 1); map.put(d, map.getOrDefault(d, 0) + n); } } map.put(s, map.getOrDefault(s, 0) + n); } List<String> res = new ArrayList(); for (String d : map.keySet()) { res.add(map.get(d) + " " + d); } return res; } public String reverseWords(String s) { String[] split = s.split(" "); String result = ""; for (int i = 0; i < split.length; i++) { String str = split[i]; char[] chars = str.toCharArray(); for (int i1 = 0; i1 < chars.length/2; i1++) { char temp = chars[i1]; chars[i1] = chars[chars.length - i1-1]; chars[chars.length - i1 - 1] = temp; } result += new String(chars) + " "; } return result.trim(); } public String reverseString(String s) { return new StringBuffer(s).reverse().toString(); } /** * 首尾交换的方式 * * @param s * @return */ public String reverseString2(String s) { char[] word = s.toCharArray(); int i = 0; int j = s.length() - 1; while (i < j) { char temp = word[i]; word[i] = word[j]; word[j] = temp; i++; j--; } return new String(word); } /** * 很奇怪的递归的方式 * * @param s * @return */ public String reverseString3(String s) { int length = s.length(); if (length <= 1) return s; String leftStr = s.substring(0, length / 2); String rightStr = s.substring(length / 2, length); return reverseString3(rightStr) + reverseString3(leftStr); } public int[] shortestToChar(String S, char C) { int recentCindex = S.indexOf(C); int[] result = new int[S.length()]; for (int i = 0; i < S.toCharArray().length; i++) { if (S.toCharArray()[i] == C) { recentCindex = i; result[i] = 0; continue; } if (i < recentCindex) { result[i] = recentCindex - i; continue; } int i1 = S.indexOf(C, i); if (i1 < 0) { result[i] = Math.abs(i - recentCindex); }else{ result[i] = Math.min(Math.abs(i - recentCindex), Math.abs(i - i1)); } } return result; } /** * 非常棒的一种想法:有点动态规划的意思。 * 第一遍过滤,直接放置是0的 * 第二遍过滤,从前往后,利用前一个值来过滤 * 第三遍过滤,从后往前,利用后一个值来过滤 * * @param S * @param C * @return */ public int[] shortestToChar2(String S, char C) { int n = S.length(); int[] res = new int[n]; for (int i = 0; i < n; ++i) res[i] = S.charAt(i) == C ? 0 : n; for (int i = 1; i < n; ++i) res[i] = Math.min(res[i], res[i - 1] + 1); for (int i = n - 2; i >= 0; --i) res[i] = Math.min(res[i], res[i + 1] + 1); return res; } public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static class Node { public int val; public List<Node> children; public Node() { } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } ; } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springmvc-study</groupId> <artifactId>springmvc-study</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> <properties> <jackson.version>2.8.5</jackson.version> <log4j.version>2.7</log4j.version> <com.alibaba.fastjson.version>1.2.31</com.alibaba.fastjson.version> <validation-api-version>1.1.0.Final</validation-api-version> <hibernate-validator-version>5.1.0.Final</hibernate-validator-version> <hadoop-version>2.9.1</hadoop-version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch --> <!--<dependency>--> <!--<groupId>org.elasticsearch</groupId>--> <!--<artifactId>elasticsearch</artifactId>--> <!--<version>5.5.1</version>--> <!--</dependency>--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.5.1</version> </dependency> <!--测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.8</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!--日志--> <!--<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency>--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <!-- 桥接:告诉Slf4j使用Log4j2 --> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <!-- 桥接:告诉commons logging使用Log4j2 --> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jcl</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <!--J2EE--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--mysql驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <!--springframework--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.6.RELEASE</version> </dependency> <!--<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.6.RELEASE</version> </dependency>--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <!-- fasterxml.jackson --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-smile</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-cbor</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> <exclusions> <exclusion> <artifactId>jackson-annotations</artifactId> <groupId>com.fasterxml.jackson.core</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>${jackson.version}</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${com.alibaba.fastjson.version}</version> </dependency> <!-- 参数校验 --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>${validation-api-version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator-version}</version> </dependency> <!--hadoop--> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>${hadoop-version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>${hadoop-version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-hdfs</artifactId> <version>${hadoop-version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-mapreduce-client-core</artifactId> <version>${hadoop-version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-auth</artifactId> <version>${hadoop-version}</version> </dependency> </dependencies> </project> <file_sep>/src/main/java/com/springmvc/lxy/controller/Controller1.java package com.springmvc.lxy.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.springmvc.lxy.dto.TestSpringMvc4Get; import com.springmvc.lxy.dto.TestSpringMvc4Post; import com.springmvc.lxy.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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.RestController; import javax.servlet.http.HttpServletRequest; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; /** * 描述: 控制器 * <p> * * @author: harry * @date: 2018-08-30 **/ @RestController @RequestMapping("/test1") public class Controller1 { private static final Logger LOG = LoggerFactory.getLogger(Controller1.class); @Autowired private UserService userService; @RequestMapping(value = "/getUser", method = RequestMethod.GET) public ResponseEntity<?> getUser(HttpServletRequest request, TestSpringMvc4Get req) { LOG.info("getUser starts."); String user1 = userService.getUser1(); LOG.info("getUser ends."); return new ResponseEntity<>(user1,HttpStatus.OK); } /** * 测试 get方法,list类型 */ @RequestMapping(value = "/get4list", method = RequestMethod.GET) public ResponseEntity<?> TestSpringMvcGETList(HttpServletRequest request, TestSpringMvc4Get req) { LOG.info("测试 get方法 cityIdList starts."); String cityIdList = request.getParameter("cityIdList"); LOG.info("测试 get方法 cityIdList ends.{}",cityIdList); return new ResponseEntity<>(req,HttpStatus.OK); } /** * 测试 get方法 序列化时间类型 */ @RequestMapping(value = "/get", method = RequestMethod.GET) public ResponseEntity<?> TestSpringMvcGET(HttpServletRequest request, TestSpringMvc4Get req) { LOG.info("测试 get方法 序列化时间类型 starts."); req.setExtendDateFormatLocalDate(LocalDateTime.now()); req.setExtendJsonLocalDate(LocalDateTime.now()); req.setExtendLocalDate(LocalDateTime.now()); LOG.info("测试 get方法 序列化时间类型 ends."); return new ResponseEntity<>(req,HttpStatus.OK); } /** * 测试 post方法 序列化时间类型 */ @RequestMapping(value = "/post", method = RequestMethod.POST) public ResponseEntity<?> TestSpringMvcPOST(HttpServletRequest request, @RequestBody TestSpringMvc4Post req) { LOG.info("测试 post方法 序列化时间类型 starts."); req.setExtendDateFormatLocalDate(LocalDateTime.now()); req.setExtendJsonLocalDate(LocalDateTime.now()); req.setExtendLocalDate(LocalDateTime.now()); req.setExtendDate(new Date()); req.setExtendDateWithDateFormat(new Date()); req.setExtendDateWithJsonFormat(new Date()); LOG.info("测试 post方法 序列化时间类型 ends."); return new ResponseEntity<>(req,HttpStatus.OK); } public static void main(String[] args) throws JsonProcessingException { LocalDate date = LocalDate.now(); ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(date)); } } <file_sep>/src/main/resources/common.properties etraceUrl=etrace-config.alpha.elenet.me:289 classUrl=/WEB-INF/classes/conf/Client.json <file_sep>/src/main/java/com/springmvc/lxy/other/Exec_19_01_31.java package com.springmvc.lxy.other; /** * 描述: ${description} * <p> * * @author: harry * @date: 2019-01-31 **/ public class Exec_19_01_31 { public static void main(String[] args) { titleToNumber("abcd"); } public static int titleToNumber(String s) { int result = 0; for (int i = 0; i < s.length(); i++) { result = result *26 + s.charAt(i) - 'A' + 1; } return result; } } <file_sep>/src/main/java/com/springmvc/lxy/elasticsearch/Client.java package com.springmvc.lxy.elasticsearch; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.get.GetField; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.tophits.TopHits; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * 描述: es的练习类 * <p> * * @author: harry * @date: 2018-10-21 **/ public class Client { protected static TransportClient client = null; private static final Logger log = LoggerFactory.getLogger(Client.class); public static final String INDEX = "fendo"; public static final String TYPE = "fendodate"; static { log.info("start init client..."); Settings settings = Settings.builder() .put("cluster.name", "lxy").build(); try { client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); log.info("init client successfully..."); } catch (UnknownHostException e) { log.error("初始化client 报错了:{}" ,e); } } public static void close() { if (client != null) { client.close(); } } public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { Client client = new Client(); client.index(); // client.close(); // client.get(); // client.delete(); // client.update(); // client.upsert(); // client.multiGet(); // client.search(); // client.searchTermQuery(); // client.searchMatchQuery(); // client.agg1(); // client.topHitAgg(); close(); } /** * set操作 * 1. 如果Index,type都没有,会自动创建 * 2. 如果index-type-id 对应的都有,那么会覆盖 * * @throws IOException */ public void index() throws IOException { IndexResponse response = client.prepareIndex("twitter", "tweet", "20") .setSource(jsonBuilder() .startObject() .field("user", "这个就是我拿来垫底的,就是最后一个怎么了") .field("postDate", new Date()) .field("message", "我也不知道该说点什么好了,马上就去上班了") .field("age", "20") .field("multi", "querying是不会被分词的test虽然夹在中文中但是,会分出来的") .field("price1", 100) .endObject() ) .get(); IndexResponse response2 = client.prepareIndex("twitter", "tweet", "17") .setSource(jsonBuilder() .startObject() .field("user", "刘旭阳 徐雪琴 旅游 有线电视 早餐吃得饱 接送汽车飞机 地铁方便离市中心近 平民价格 大多数人的选择 棒棒的") .field("postDate", new Date()) .field("message", "tryin不行的瞎写的ch2225") .field("age", "34") .field("multi", "这个只有query啊!") .field("price1", 100000) .endObject() ) .get(); IndexResponse response3 = client.prepareIndex("twitter", "tweet", "18") .setSource(jsonBuilder() .startObject() .field("user", "武首昭 雷晓芳 酒店 wifi 泳池可以有用 宾馆非常好 服务 热闹人多可以的 很棒") .field("postDate", new Date()) .field("message", "我想验证一下有没有装ik") .field("age", "199") .field("multi", "有test也有query,还有两个query呢") .field("price1", 24) .endObject() ) .get(); IndexResponse response4 = client.prepareIndex("twitter", "tweet", "19") .setSource(jsonBuilder() .startObject() .field("user", "刘旭阳 武首昭 住宿绝不仅限于住宿 旅馆 特殊的享受 安静 文艺卫生 高级商务") .field("gender", "sdfadfsadfasdf") .field("message", "长春市长春药店可能是真的假的") .field("age", "45") .field("multi", "这些都是宝贵的test数据,不可以轻易的query") .field("price1", 56) .endObject() ) .get(); log.info("<index>,response:{}" , response.toString()); } public void delete() { DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get(); log.info("<delete>,response:{}" , response.toString()); } public void upsert() throws IOException, ExecutionException, InterruptedException { IndexRequest indexRequest = new IndexRequest("index", "type", "1") .source(jsonBuilder() .startObject() .field("name", "<NAME>") .field("gender", "male") .endObject()); UpdateRequest updateRequest = new UpdateRequest("index", "type", "1") .doc(jsonBuilder() .startObject() .field("gender", "male") .endObject()) .upsert(indexRequest); UpdateResponse updateResponse = client.update(updateRequest).get(); } /** * 如果要更新的index,type,id不存在,就会报错。:DocumentMissingException[[type_not_exist][1]: document missing] * * @throws IOException * @throws ExecutionException * @throws InterruptedException */ public void update() throws IOException, ExecutionException, InterruptedException { // UpdateRequest updateRequest = new UpdateRequest(); // updateRequest.index("index"); // updateRequest.type("type"); // updateRequest.id("1"); // updateRequest.doc(jsonBuilder() // .startObject() // .field("gender", "male") // .endObject()); // // UpdateResponse updateResponse = client.update(updateRequest).get(); XContentBuilder xContentBuilder = jsonBuilder() .startObject() .field("gender", "male11") .endObject(); log.info("<update>,req:{}", xContentBuilder.toString()); UpdateResponse updateResponse = client.prepareUpdate("index", "type", "2") .setDoc(xContentBuilder) .get(); log.info("<update>,req:{},response:{}", xContentBuilder.toString() , updateResponse.toString()); } public void get() { GetResponse response = client.prepareGet("twitter", "tweet", "1").get(); Map<String, Object> source = response.getSource(); log.info("get : index:{},type:{},id:{},source:{},version:{}" , response.getIndex(), response.getType(), response.getId(), response.getSourceAsString(), response.getVersion()); log.info("source: --"); for (Map.Entry<String, Object> entry : source.entrySet()) { log.info("key:{},value:{}", entry.getKey(), entry.getValue()); } log.info("field: --"); for (Map.Entry<String, GetField> entry : response.getFields().entrySet()) { log.info("key:{},value-name{},value-value", entry.getKey(), entry.getValue().getName(), entry.getValue().getValue()); } } public void multiGet() { MultiGetResponse multiGetItemResponses = client.prepareMultiGet() .add("twitter", "tweet", "1") .add("twitter", "tweet", "2", "3", "4") .add("index", "type", "1") .get(); log.info("multiGet:--"); for (MultiGetItemResponse itemResponse : multiGetItemResponses) { GetResponse response = itemResponse.getResponse(); if (response.isExists()) { String json = response.getSourceAsString(); log.info("json:{}", json); } } } public void bulkApi() throws IOException { BulkRequestBuilder bulkRequest = client.prepareBulk(); // either use client#prepare, or use Requests# to directly build index/delete requests bulkRequest.add(client.prepareIndex("twitter", "tweet", "7") .setSource(jsonBuilder() .startObject() .field("user", "no7") .field("postDate", new Date()) .field("message", "trying out Elasticsearch no7") .endObject() ) ); bulkRequest.add(client.prepareIndex("twitter", "tweet", "8") .setSource(jsonBuilder() .startObject() .field("user", "kimchyno8") .field("postDate", new Date()) .field("message", "another post no8") .endObject() ) ); BulkResponse bulkResponse = bulkRequest.get(); if (bulkResponse.hasFailures()) { // process failures by iterating through each bulk response item log.error("bulk req faile : {}", bulkResponse.buildFailureMessage()); } else { BulkItemResponse[] items = bulkResponse.getItems(); for (BulkItemResponse item : items) { log.error("bulk req success : itemId:{},id:{}", item.getItemId(), item.getId()); } } } public void search() { SearchResponse response = client.prepareSearch("twitter", "index") .setTypes("tweet", "type") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.termQuery("multi", "test")) // Query .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter .setFrom(0).setSize(60).setExplain(true) .get(); log.info("<search> hits: num:{}", response.getHits().totalHits); SearchHits hits = response.getHits(); for (SearchHit hit : hits) { log.info("<search> hits {}", hit.getSourceAsString()); } } /** * 用了 queryBuilder.filter() 方法去构造请求。 * term:term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇 * <p> * toString() 的方法构造的请求: * { * "bool": { * "filter": [ //两个filter * { * "term": { * "multi": { * "value": "test", * "boost": 1.0 * } * } * }, * { * "range": { * "age": { * "from": 12, * "to": 18, * "include_lower": true, * "include_upper": true, * "boost": 1.0 * } * } * } * ], * "disable_coord": false, * "adjust_pure_negative": true, * "boost": 1.0 * } * } * <p> * 返回的结果:(age在12-18之间,而且查询的只有严格的multi字段是 test 才可以) * {"user":"kiharry4","postDate":"2018-10-21T13:54:42.346Z","message":"tryirch4","age":"15","multi":"test"} */ public void searchTermQuery() { BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.filter(QueryBuilders.termQuery("multi", "test")); queryBuilder.filter(QueryBuilders.rangeQuery("age").from(12).to(18)); log.info("search2 : queryBuilder:{} ", queryBuilder.toString()); SearchResponse response = client.prepareSearch("twitter", "index") .setTypes("tweet", "type") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setPostFilter(queryBuilder) .setFrom(0).setSize(60).setExplain(true) .get(); log.info("<search> hits: num:{}", response.getHits().totalHits); SearchHits hits = response.getHits(); for (SearchHit hit : hits) { log.info("<search> hits {}", hit.getSourceAsString()); } } /** * { * "bool": { * "filter": [ * { * "range": { * "age": { * "from": 12, * "to": 18, * "include_lower": true, * "include_upper": true, * "boost": 1.0 * } * } * }, * { * "match": { * "multi": { * "query": "test", * "operator": "OR", * "prefix_length": 0, * "max_expansions": 50, * "fuzzy_transpositions": true, * "lenient": false, * "zero_terms_query": "NONE", * "boost": 1.0 * } * } * } * ], * "disable_coord": false, * "adjust_pure_negative": true, * "boost": 1.0 * } * } * <p> * 返回的结果:(只能是把test完全漏出来才行 testing,atest,均不行,必须要 is a test sd) * 1. {"user":"kiharry4","postDate":"2018-10-21T13:54:42.346Z","message":"tryirch4","age":"15","multi":"test"} * 2. {"user":"kiharry11","postDate":"2018-10-21T14:09:47.270Z","message":"tryirch11","age":"15","multi":"这次可以把test空出来了 test query"} * <p> * 注意: * 对于match搜索,可以按照分词后的分词集合的or或者and进行匹配,默认为or, * 这也是为什么我们看到前面的搜索都是只要有一个分词出现在文档中就会被搜索出来,同样的,如果我们希望是所有分词都要出现,那只要把匹配模式改成and就行了 */ public void searchMatchQuery() { BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.filter(QueryBuilders.rangeQuery("age").from(12).to(18)); queryBuilder.filter(QueryBuilders.matchQuery("multi", "test")); log.info("searchMatchQuery : queryBuilder:{} ", queryBuilder.toString()); SearchResponse response = client.prepareSearch("twitter", "index") .setTypes("tweet", "type") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setPostFilter(queryBuilder) .setFrom(0).setSize(60).setExplain(true) .get(); log.info("<searchMatchQuery> hits: num:{}", response.getHits().totalHits); SearchHits hits = response.getHits(); for (SearchHit hit : hits) { log.info("<searchMatchQuery> hits {}", hit.getSourceAsString()); } } /** * scroll查询 * https://blog.csdn.net/SunnyYoona/article/details/52810397?utm_source=blogxgwz1 * https://blog.csdn.net/feifantiyan/article/details/54096138?utm_source=blogxgwz2 * http://lxwei.github.io/posts/%E4%BD%BF%E7%94%A8scroll%E5%AE%9E%E7%8E%B0Elasticsearch%E6%95%B0%E6%8D%AE%E9%81%8D%E5%8E%86%E5%92%8C%E6%B7%B1%E5%BA%A6%E5%88%86%E9%A1%B5.html * es官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-request-scroll.html */ public void scrollQuery() { BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.filter(QueryBuilders.rangeQuery("age").from(12).to(18)); queryBuilder.filter(QueryBuilders.matchQuery("multi", "test")); SearchResponse scrollResp = client.prepareSearch("twitter", "index") .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC) .setScroll(new TimeValue(60000)) .setQuery(queryBuilder) .setSize(100).get(); //max of 100 hits will be returned for each scroll //Scroll until no hits are returned do { for (SearchHit hit : scrollResp.getHits().getHits()) { //Handle the hit... } scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet(); } while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop. } /** * IllegalArgumentException[Fielddata is disabled on text fields by default. * Set fielddata=true on [age] in order to load fielddata in memory by uninverting the inverted index. * Note that this can however use significant memory. Alternatively use a keyword field instead. * <p> * 1. 用:age.keyword 就可以了 * 2. 执行如下: * PUT megacorp/_mapping/employee/ * { * "properties": { * "interests": { * "type": "text", * "fielddata": true * } * } * } */ public void agg1() { SearchResponse sr = client.prepareSearch("twitter") .setTypes("tweet") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation( AggregationBuilders.terms("agg1").field("age.keyword") .subAggregation( AggregationBuilders.topHits("top_hit").size(3) ) ).addAggregation( AggregationBuilders.terms("agg2").field("user.keyword") ) .get(); // Get your facet results Terms agg1 = sr.getAggregations().get("agg1"); List<? extends Terms.Bucket> buckets = agg1.getBuckets(); for (Terms.Bucket bucket : buckets) { log.info("<agg1>:{},count:{} ", bucket.getKeyAsString(), bucket.getDocCount()); } // log.info("<agg1> count:{},max:{},min:{}",agg1.get,agg1.getMax(),agg1.getMin()); Terms agg2 = sr.getAggregations().get("agg2"); List<? extends Terms.Bucket> buckets2 = agg2.getBuckets(); for (Terms.Bucket bucket : buckets2) { log.info("<agg2>:{},count:{} ", bucket.getKeyAsString(), bucket.getDocCount()); } } /** * size 表示的是 返回的数量。 * 刚开始没有用terms,size是5,返回了5个,按照price1排序(没有的就排在最后) * SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test"); * * TopHitsAggregationBuilder addtion = AggregationBuilders.topHits("top_price_hits").sort("price", SortOrder.DESC).fieldDataField("price") * .size(5); * * SearchResponse sr =search.addAggregation(addtion).execute().actionGet(); * TopHits topHits = sr.getAggregations().get("top_price_hits"); * System.out.println(); * SearchHit[] hits = topHits.getHits().internalHits(); * for(SearchHit searchHit : hits) { * System.out.println(searchHit.getSourceAsString()); * * } * * 后来用了嵌套的模式:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/_metrics_aggregations.html#java-aggs-metrics-tophits,在官网上都有例子 */ public void topHitAgg() { SearchRequestBuilder search = client.prepareSearch("twitter").setTypes("tweet"); TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("price").field("price1") .subAggregation(AggregationBuilders.topHits("top_price_hits") .sort("price1", SortOrder.DESC).fieldDataField("price") .size(2)); SearchResponse sr = search.addAggregation(termsAggregationBuilder).execute().actionGet(); Terms price1 = sr.getAggregations().get("price"); for (Terms.Bucket bucket : price1.getBuckets()) { Long key = (Long)bucket.getKey(); long docCount = bucket.getDocCount(); log.info("key [{}], doc_count [{}]", key, docCount); TopHits top_price_hits = bucket.getAggregations().get("top_price_hits"); SearchHit[] hits = top_price_hits.getHits().internalHits(); for (SearchHit searchHit : hits) { log.info("<agg2>:{} ", searchHit.getSourceAsString()); } } } } <file_sep>/src/main/java/com/springmvc/lxy/programlearn/Jan26.java package com.springmvc.lxy.programlearn; /** * 描述: * <p> * <p> * harryliu * 2019/1/27 */ class Student { int grade; double score; User parent; } class User { char sex; float height; float weight; String home; String position; String name; public void drink() { System.out.println("喝水。。。"); } public void eat() { System.out.println("吃饭。。。"); } public void eatToomuch() { System.out.println("吃了很多很多。。。"); this.weight++; this.height += 2; } public void love(User user){ System.out.println(this.name + "和谁love:" + user.name); } } public class Jan26 { public static void main(String[] args) { // test1(); // whiletest(); User user2 = new User(); user2.sex = '女'; user2.name = "雪琴"; user2.position = "会计"; user2.home = "安徽芜湖"; user2.weight = 95F; user2.height = 168F; user2.drink(); System.out.println(user2.weight); user2.eatToomuch(); System.out.println(user2.weight); User user3 = new User(); user3.name = "刘旭阳"; user2.love(user3); Student ab = new Student(); ab.grade = 3; ab.parent = user2; ab.score = 88.888D; System.out.println(); } private static void test1() { byte y = 2; short s = 9; int a = 100; long o = 987654321L; float c = 1.23456F; double b = 1.576856788D; boolean g = true; boolean f = false; boolean p = 4 > 5; boolean aa = g == f; boolean ab = g && f; boolean ac = p || g; char qw = '阳'; char qa = 'x'; // System.out.println(qw); // // String er = "liuxuyangshizhu"; // System.out.println(y + "---" + er); int[] arr = {1, 2, 3, 4, 5}; String[] k = {"xuxueqin", "liuxuyang", "pi", "wo"}; for (int t = 0; t < 4; t = t + 1) { System.out.println(arr[t]); for (int u = 0; u < 3; u = u + 1) { System.out.println(k[u]); } } // double [] liu={wo,shi,xu,xue,qin}; } } <file_sep>/src/main/java/com/springmvc/lxy/other/sort/QuickSort.java package com.springmvc.lxy.other.sort; import com.alibaba.fastjson.JSONObject; import com.springmvc.lxy.other.SelfDividingNumbers; import java.util.List; /** * 描述: ${description} * <p> * * @author: harry * @date: 2018-12-16 **/ public class QuickSort { public static void main(String[] args) { QuickSort client = new QuickSort(); System.out.println("\nno2...快速排序"); int[] arr2 = {1, 4, 3, 2}; client.quickSort(arr2,0,arr2.length-1); System.out.println(JSONObject.toJSONString(arr2)); } public int adjustArr(int[] nums, int left, int right) { int temp = nums[left]; while (left < right) { while(left < right && nums[right] > temp){ right--; } if (left < right) { nums[left] = nums[right]; left ++; } while(left < right && nums[left] < temp){ left++; } if (left < right) { nums[right] = nums[left]; right --; } } nums[left] = temp; return left; } public void quickSort(int[] nums, int left, int right) { if (left < right) { int i = adjustArr(nums, left, right); quickSort(nums, left, i - 1); quickSort(nums, i + 1, right); } } }
19aa4ba786689c23789dc37b865c2e339d7a6f67
[ "Markdown", "Java", "Maven POM", "INI" ]
21
Java
LiuxuyangK/springmvc-study
b870da9877dd8b062490a2b6848d4d8d42419a0f
e2d9f2d509041a6423af4b8348a5a7b7be92d6f3
refs/heads/main
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_parse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: polina <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/26 16:42:31 by polina #+# #+# */ /* Updated: 2021/02/11 14:18:46 by polina ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" char *ft_check_name(char *name) { char *point; char *tmp_name; char *new_name; int len; if ((len = ft_strlen(name)) < 2) error("Wrong file name", 0); point = &name[len - 2]; if (!ft_strcmp(point, ".s\n")) error("Wrong file extension", 0); tmp_name = point; while (*(tmp_name - 1) && *(tmp_name - 1) != '/') tmp_name--; new_name = ft_strsub(tmp_name, 0, point - tmp_name); point = new_name; new_name = ft_strjoin(point, ".cor"); free(point); return (new_name); } char *ft_join_with_new_line(char **str) { char *next_line; char *res; next_line = ft_strdup("\n"); res = ft_strjoin_free_all(str, &next_line); return (res); } void ft_read_to_secod_quotes(t_asm *st, char **str) { int red; char *quote_two; char *tmp; char *buf; while ((red = get_next_line(st->fd_orig, &buf)) > 0 && \ !(quote_two = ft_strchr(buf, '"'))) { st->string_num++; *str = ft_strjoin_free_all(str, &buf); *str = ft_join_with_new_line(str); } st->string_num++; if (!quote_two) error("Missing second quotes", 0); tmp = ft_strsub(buf, 0, quote_two - buf); *str = ft_strjoin_free_all(str, &tmp); free(buf); } void ft_parse_name_or_comment(t_asm *st, char *res, char **buf) { char *quote_one; char *quote_two; char *end; char *str; end = *buf; while (*end) end++; // printf("%s\n", *buf); if (!(quote_one = ft_strchr(*buf, '"'))) error("Missing quotes ", st->string_num); if ((quote_two = ft_strchr(++quote_one, '"'))) str = ft_strsub(quote_one, 0, quote_two - quote_one); else { str = ft_strsub(quote_one, 0, end - quote_one); str = ft_join_with_new_line(&str); ft_read_to_secod_quotes(st, &str); // printf("%s\n", str); } ft_strcpy(res, str); if (quote_two && !ft_check_alt_comment(++quote_two)) error("You have something extra at the end of the line ", st->string_num); // printf("ok\n"); free(str); free(*buf); } <file_sep>NAME = asm LIBFTA = $(LIB_DIR)libft.a PRINTFA = $(PRINTF_DIR)libftprintf.a HEADER = $(HEAD_DIR)asm.h LIB_H = $(LIB_DIR)libft.h PRINT_H = $(PRINTF_DIR)$(HEAD_DIR)ft_printf.h LIB_DIR = libft/ HEAD_DIR = includes/ PRINTF_DIR = ft_printf/ HEAD = -I $(HEAD_DIR) LIBFT_H = -I $(LIB_DIR) PRINTF_H = -I $(PRINTF_DIR)$(HEAD_DIR) COMP = gcc -Wall -Werror -Wextra $(HEAD) $(LIBFT_H) $(PRINTF_H) -g DIR = src_asm/ OBJ_DIR = obj/ SRCS = count_bytes_for_command.c ft_init_label.c ft_read.c \ utilits.c count_bytes_for_command2.c ft_parse.c \ ft_second_read.c ft_find_command.c ft_print_command.c main.c OFILE = $(SRCS:%.c=%.o) OBJ = $(addprefix $(OBJ_DIR), $(OFILE)) all: lib $(NAME) lib: @make -C $(LIB_DIR) @make -C $(PRINTF_DIR) $(OBJ_DIR): @mkdir -p $(OBJ_DIR) $(NAME): $(OBJ_DIR) $(OBJ) $(HEADER) $(LIB_H) $(PRINT_H) @$(COMP) $(LIBFTA) $(PRINTFA) $(OBJ) -o $(NAME) @echo -------compile asm finish-------- $(OBJ_DIR)%.o: $(DIR)%.c $(HEADER) @$(COMP) -c $< -o $@ clean: @/bin/rm -rf $(OBJ_DIR) @make -C $(LIB_DIR) clean @make -C $(PRINTF_DIR) clean @echo OBJECTS FILES HAS BEEN DELETED. fclean: clean @/bin/rm -f $(NAME) @make -C $(LIB_DIR) fclean @make -C $(PRINTF_DIR) fclean @echo OBJECT FILES AND EXECUTABLE HAS BEEN DELETED. re: fclean all<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* asm.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: polina <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/17 17:40:38 by polina #+# #+# */ /* Updated: 2021/02/05 14:34:47 by polina ### ########.fr */ /* */ /* ************************************************************************** */ #include "op.h" #include "libft.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> typedef struct s_label { int byte_pos; char *name; struct s_label *next; } t_label; typedef struct s_op { char *name; int count_args; int needs_code_args; int size_dir; } t_op; typedef struct s_asm { t_label *label; t_op op_tab[17]; int little_endian; int header_end; int string_num; unsigned char *exec_code; int index; int curr_pos; int count_bytes; char *comment; char *name; int fd_orig; int fd_res; } t_asm; /* ** ft_parse.c */ char *ft_check_name(char *name); void ft_parse_name_or_comment(t_asm *st, char *res, char **buf); /* ** utilits.c */ void error(char *str, int num_string); int ft_convert_to_big_endian(int elem); char *ft_del_space(char *str, t_asm *st); int ft_find_space(char c); int ft_check_alt_comment(char *start); /* ** ft_find_command.c */ char **ft_get_args(char *args, int count_arg, t_asm *st); int ft_check_type(char *str, t_asm *st); int ft_find_command(char *name, char *args, t_asm *st); int ft_count_type_byte(int arg, int flag); /* ** ft_init_label.c */ char *ft_create_name_label(char *colon, char **buf, t_asm *st); void ft_add_label(char *name, t_asm *st); t_label *ft_find_label(char *name, t_asm *st); /* ** ft_second_read.c */ void ft_second_read(t_asm *st); void ft_check_end_line(t_asm *st); void ft_select_command(t_asm *st, char *name, char *args); /* ** ft_print_command.c */ void ft_print_command(t_asm *st, int index, char *args); /* ** ft_read.c */ void ft_read_command(char *command, t_asm *st, int fl); void ft_read(t_asm *st, char *name, char *old_name); /* ** ft_count_bytes_for_command/2.c */ int ft_add_sub_args(char *args, t_asm *st); int ft_st_args(char *args, t_asm *st); int ft_ld_lld_args(char *args, t_asm * st); int ft_one_dir_args(char *name, char *args, t_asm *st); int ft_logical_args(char *args, t_asm *st); int ft_aff_args(char *args, t_asm *st); int ft_sti_args(char *args, t_asm *st); int ft_ldi_lldi_args(char *args, t_asm *st); <file_sep># Corewar_asm Ассемблер часть для игры Core war
7a2da38311ff06a1298d3614f70877da0761b18e
[ "Markdown", "C", "Makefile" ]
4
C
Vheidy/Corewar_asm
66856bb47feb399dc523d77661e42d6c1b9a3dd8
08306a1895bf763dfae10ceada5406d93e795f93
refs/heads/master
<repo_name>via-platform/server-status<file_sep>/lib/main.js const {CompositeDisposable, Disposable} = require('via'); const ServerStatusIndicator = require('./server-status-indicator'); const ServerStatus = require('./server-status'); const base = 'via://server-status'; const InterfaceConfiguration = { name: 'Server Status', description: 'Monitor Via server status.', command: 'server-status:open', uri: base }; class ServerStatusPackage { initialize(){ this.disposables = new CompositeDisposable(); this.servers = null; this.disposables.add(via.commands.add('via-workspace', { 'server-status:open': () => this.getStatusInstance().show(), 'server-status:hide': () => this.getStatusInstance().hide() })); } getStatusInstance(state = {}){ if(!this.servers){ this.servers = new ServerStatus(state); this.servers.onDidDestroy(() => this.servers = null); } return this.servers; } consumeStatusBar(status){ this.status = status; this.attachStatusBarView(); } attachStatusBarView(){ // if(!this.indicator){ // this.indicator = new ServerStatusIndicator({status: this.status}); // } } deactivate(){ this.disposables.dispose(); if(this.indicator){ this.indicator.destroy(); } if(this.servers){ this.servers.destroy(); } } } module.exports = new ServerStatusPackage();
1b524682976e150ca479fd495e1a099438d6a39d
[ "JavaScript" ]
1
JavaScript
via-platform/server-status
2497f60f5f7c0ae6c19e460fab176dcd3f9f6f9e
dc67435c80e7f5e67b02f700f807e4ef2aa151df
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_and_belongs_to_many :posts has_many :posts has_many :comments has_many :links has_many :atachments end<file_sep>class LinksController < ApplicationController before_filter :check_sign_in # POST /links # POST /links.json def create @link = Link.new(params[:link]) @link.user_id = current_user_id respond_to do |format| if @link.save @post = Post.find(@link.post_id); format.html { redirect_to @link, notice: 'Link was successfully created.' } format.json { render json: @link, status: :created, location: @link } format.js {} else format.html { render action: "new" } format.json { render json: @link.errors, status: :unprocessable_entity } end end end # DELETE /links/1 # DELETE /links/1.json def destroy @link = Link.find(params[:id]) @link.destroy respond_to do |format| format.xml { head :ok } format.js { head :ok } end end end <file_sep>#encoding: utf-8 class Post < ActiveRecord::Base has_many :comments, :dependent => :destroy has_many :links, :dependent => :destroy has_many :attachments, :dependent => :destroy belongs_to :category belongs_to :user has_and_belongs_to_many :users validates_presence_of :subject validates_presence_of :body validates_presence_of :category_id validates_presence_of :user_id end <file_sep>class Link < ActiveRecord::Base belongs_to :post belongs_to :user validates_presence_of :url end <file_sep>#encoding: utf-8 module ApplicationHelper def format_boolean(valor) if valor retorno = "Sim" else retorno = "Não" end end def format_url(url) /^http/.match(url) ? url : "http://#{url}" end def break_line(field) field.gsub(/\n/, '<br>') end def comments(post) comments = "<div id='comments'>" comments << "<h1>" + t(:comments) + "</h1>" comments << render(:partial => "comments/comment", :collection => post.comments) unless post.comments.empty? comments << "</div>" raw comments end def new_comment(post) comments = render(:partial => "comments/new_comment", :locals => { :post => post }) raw comments end def links(post) links = "<div id='links'>" links << "<h1>" + t(:links) + "</h1>" links << render(:partial => "links/link", :collection => post.links) unless post.links.empty? links << "</div>" raw links end def new_link(post) links = render(:partial => "links/new_link", :locals => { :post => post }) raw links end def attachments(post) attachments = "<div id='attachments'>" attachments << "<h1>" + t(:attachments) + "</h1>" attachments << render(:partial => "attachments/attachment", :collection => post.attachments) unless post.attachments.empty? attachments << "</div>" raw attachments end def new_attachment(post) attachments = render(:partial => "attachments/new_attachment", :locals => { :post => post }) raw attachments end def post_users(post) post_users = "<div id='post_users'>" post_users << "<h1>" + t(:users) +"</h1>" post.users.each do |user| post_users << render(:partial => "post_users/post_user", :locals => { :user => user, :post => post}) end #post_users << render(:partial => "post_users/post_user", #:collection => post.users) unless post.users.empty? post_users << "</div>" raw post_users end def new_post_user(post) post_users = render(:partial => "post_users/new_post_user", :locals => { :post => post }) raw post_users end end <file_sep>Rails.application.config.middleware.use OmniAuth::Builder do #provider :facebook, '251834431573170', '80d695620f24d870d79eb2ed1f6190ef' provider :facebook, '419790658038540', '<PASSWORD>' end <file_sep>class AddFontColorCategory < ActiveRecord::Migration def up add_column :categories, :font_color, :string end def down remove_column :categories, :font_color end end <file_sep>class RemoveTimeStampsPotsUsers < ActiveRecord::Migration def up remove_column :posts_users, :created_at remove_column :posts_users, :updated_at end def down end end <file_sep>class Category < ActiveRecord::Base has_many :posts, :dependent => :destroy validates_presence_of :description end <file_sep>namespace :share do require 'iconv' $rails_rake_task = true require(File.join(Rails.root, 'config', 'environment')) desc "Load Database" task :loaddatabase do Rake::Task['share:users'].invoke Rake::Task['share:categories'].invoke Rake::Task['share:posts'].invoke end private task :users do puts "Load Users" @user = User.new @user.provider = "fake" @user.uid = "123456" @user.name = "User Test" @user.email = "<EMAIL>" @user.active = true @user.save puts "Load Users Successfully" end task :categories do puts "Load Categories" @category = Category.new @category.description = "Category 1" @category.color = "000000" @category.user_id = @user.id @category.active = true @category.save @category = Category.new @category.description = "Category 2" @category.color = "000000" @category.user_id = @user.id @category.active = true @category.save puts "Load Categories Successfully" end task :posts do puts "Load Post" @post = Post.new @post.subject = "Post" @post.body = "Text Post" @post.category_id = @category.id @post.public = false @post.user_id = @user.id @post.save puts "Load Post Successfully" end end<file_sep>class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] @user = User.find(:all, :conditions => { :provider => auth["provider"], :uid => auth["uid"]}).first if not @user @user = User.new @user.provider = auth["provider"] @user.uid = auth["uid"] @user.name = auth["info"]["name"] @user.email = auth["info"]["email"] @user.image = auth["info"]["image"] @user.save end puts auth session[:user_id] = @user.id redirect_to posts_path, :notice => "Signed in!" end def destroy session[:user_id] = nil redirect_to login_url end end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :current_user_id def check_sign_in if not user_signed_in? redirect_to login_url end end def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def current_user_id session[:user_id] end def user_signed_in? return true if current_user end #http://stackoverflow.com/questions/8965877/redirect-loop-with-rails-omniauth-on-before-filter end <file_sep>class PostUsersController < ApplicationController before_filter :check_sign_in # POST /links # POST /links.json def create @user = User.find(params[:post][:user_id]) @post = Post.find(params[:posts_user][:post_id]) @post.users << @user respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'User was successfully associated.' } #format.xml { render :xml => @post_user, :status => :created, :location => @post_user } #format.js {} else format.html { render action: "new" } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end # DELETE /comments/1 # DELETE /comments/1.json def destroy parametros = params[:id].split("_") user_id = parametros[0].to_i post_id = parametros[1].to_i post = Post.find(post_id) user = post.users.find(user_id) if user post.users.delete(user) end # @comment = Comment.find(params[:id]) #@comment.destroy respond_to do |format| format.xml { head :ok } format.js { head :ok } end end end<file_sep>class AttachmentsController < ApplicationController before_filter :check_sign_in # POST /attachments # POST /attachments.json def create @attachment = Attachment.new(params[:attachment]) @attachment.user_id = current_user_id respond_to do |format| if @attachment.save @post = Post.find(@attachment.post_id); format.html { redirect_to @post, notice: 'Attachment was successfully updated.' } else format.html { render action: "new" } format.json { render json: @attachment.errors, status: :unprocessable_entity } end end end # DELETE /attachments/1 # DELETE /attachments/1.json def destroy @attachment = Attachment.find(params[:id]) @attachment.destroy respond_to do |format| format.xml { head :ok } format.js { head :ok } end end def download @attachment = Attachment.find(params[:id]) #send_file("#{Rails.root}/public#{@attachment.path}", # :filename => File.basename(@attachment.path.to_s), # :type => "application/pdf") send_file("#{Rails.root}/public#{@attachment.path}") end end <file_sep>#http://www.wetware.co.nz/2009/07/rails-date-formats-strftime/ Time::DATE_FORMATS[:post] = "postado em %m de %B de %Y - %I:%M%p"<file_sep>class Attachment < ActiveRecord::Base belongs_to :post belongs_to :user validates_presence_of :path require 'carrierwave/orm/activerecord' mount_uploader :path, PathUploader end
c7dcc79a5974f45095f38e58bc2adfb66d16e640
[ "Ruby" ]
16
Ruby
sergiomokshin/share
dfca8b56b15d82ef188108fb3f668aed5e93fb2e
76f373e36bb7f8e73d1880b1f4f9e3c7730d1de5
refs/heads/master
<repo_name>deonwu/jilv<file_sep>/1/static/js/jsloader/JSCompressor.php <?php /** * Merges every .js-file in directory/ies $dirs * into one file and compresses them using * Dead Edwards JavaScript-Packer * * @class JSCompressor */ class JSCompressor { private $code; /** * Gets all JS-code in directory/ies $dirs * * @method __construct */ public function __construct($dirs) { $this->getCodeFromDirs($dirs); } /** * Packs the JS-code using Dean Edwards JS-packer * * @method pack */ public function pack() { $packer = new JavaScriptPacker($this->code); return $packer->pack(); } /** * Gets all JS-code in directory/ies $dirs * * @method getCodeFromDirs */ private function getCodeFromDirs($dirs) { $this->code = ''; if(!is_array($dirs)) { $tmp = $dirs; $dirs = array(); $dirs[] = $tmp; } foreach($dirs as $dir) { $dh = opendir($dir); if($dh) { while($f = readdir($dh)) { if('js' == end(explode('.', $f))) { $this->code .= file_get_contents("$dir/$f"); } } } } } } ?><file_sep>/1/static/js/js_loader.php <?php ob_start (); define('JSROOT', realpath(dirname(__FILE__))); if(!function_exists('memcache_init')){ function memcache_init(){ return memcache_connect("127.0.0.1"); } } include_once "jsloader/JSLoader.php"; /* 0 -- 已经压缩过的JS文件,只需要直接输出就可以了。 1 -- 原始文件,需要进行压缩。 */ $common = array( array( "TaodianSdk.js", "app_dailog.js", ), array( "json2.js") ); $group = array( 'business_enter' => array(array("bootstrap/bootstrap-validation.js", "app_fileupload.plugin.js",'shop/business_enter.js')), 'business_product' => array(array("bootstrap/bootstrap-validation.js", "app_fileupload.plugin.js",'shop/business_product.js')), 'admin_shop' => array(array("bootstrap/bootstrap-validation.js","app_fileupload.plugin.js",'admin/shop_list.js')), 'admin_product' => array(array("bootstrap/bootstrap-validation.js","app_fileupload.plugin.js",'admin/product_list.js')), 'admin_home' => array(array("bootstrap/bootstrap-validation.js","app_fileupload.plugin.js", 'admin/home_page.js')), ); $l = new JSLoader(JSROOT, $common, $group); $app_root_path = "{$_SERVER['DOCUMENT_ROOT']}/protected/apps"; if(!is_dir($app_root_path)){ $app_root_path = dirname(dirname(JSROOT)) . "/protected/apps"; } if($_REQUEST['debug'] == 'true'){ echo "root:{$app_root_path}\n"; } $l->set_app_root_path($app_root_path); if($_REQUEST['clean'] == 'y'){ $l->clean_cache(); }else { $l->load(); } ?><file_sep>/1/YunPHP/core/Module.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class Module extends YunPHP { public function __construnct(){ parent::__construct(); } //目前没有想清楚这里写什么函数 public function __destruct(){ parent::__destruct(); } public function model($model){ $model = ucfirst($model); if(file_exists(DOCROOT.'module/'.$model.'Model.class.php')){ require_once DOCROOT.'module/'.$model.'Model.class.php'; }else{ throw new Exception("Action ==> $model model not exists"); } } } ?><file_sep>/1/protected/view/shop/enter/enter_form.php <?php $must = "<span class='red'>*</span>"; $subject_array = array('旅行社', '组织','企业','机构', '个体'); ?> <style> .form-control{width:400px;} h4{font-weight:bold;width:80%;padding-bottom: 10px;} .control-label{font-weight: normal;} .red{color:red;font-weight:bold;padding-right: 2px;vertical-align: middle;font-size: 1.3em;} img{max-width:220px;max-height:200px;overflow:hidden;} </style> <div class="form-horizontal" id="business-enter" role="form"> <input type="hidden" name="id" value="<?=$enter['id']?>"> <h4 style="border-bottom:1px solid #ccc;">1.商家名称</h4> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label"><?=$must?>运营主体</label> <div class="col-sm-10"> <?php foreach ($subject_array as $i=>$subject){?> <label class="radio-inline"> <input type="radio" name="subject" id="optionsRadios1" value="<?=$subject?>" <?=($enter['subject'] == $subject || (!$enter && $i==0)) ? "checked='checked'":''?>><?=$subject?> </label> <?php }?> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>商家名称</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="shop_name" value="<?=$enter['shop_name']?>" placeholder="商家名称,公共产品页面可见" check-type="required" required-message="商家名称不能为空!"> <span class="label label-info"> 商家名称会显示在网站页面上,请不要使用特殊字符,如逗号等。 </span> </div> </div> <h4 style="border-bottom:1px solid #ccc">2.联系方式</h4> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>姓氏</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="surname" value="<?=$enter['surname']?>" placeholder="姓氏" check-type="required" required-message="不能为空!"> <span class="label label-info"> 你的个人资料将会严格保密。 </span> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>名字</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="forename" value="<?=$enter['forename']?>" placeholder="名字" check-type="required" required-message="不能为空!"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>性别</label> <div class="col-sm-10"> <select name="sex" class="form-control"> <option value="1" <?=$enter['sex'] =='1' ? "selected='selected'":""?>>先生</option> <option value="2" <?=$enter['sex'] =='2' ? "selected='selected'":""?>>女士</option> </select> </div> </div> <div class="form-group control-group up-pic"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>身份认证</label> <div class="col-sm-10 "> <input type='file' name="file" class="up-auth" value="<?=$enter['authentication']?>"> <input type="hidden" name="authentication" value="<?=$enter['authentication']?>"> <img src="<?=$enter['authentication'] ? $enter['authentication'].'!190':''?>"> <span class="label label-info"> 请上传运营者身份证或护照的清晰彩色原件照片。 </span> </div> </div> <hr/> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>工商注册名称</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="registration_name" value="<?=$enter['registration_name']?>" check-type="required" required-message="工商注册名称不能为空!" placeholder="工商注册名称"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">邮政编码</label> <div class="col-sm-10"> <input type="text" class="form-control" name="postcode" value="<?=$enter['postcode']?>" placeholder="邮政编码"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>所在地</label> <div class="col-sm-10" style='padding-left: 30px;'> <div class="form-group address_p rel control-group"> <select id="continent" name="continent" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="3"> <option value="-1">--洲--</option> </select> </div> <div class="form-group address_p rel"> <select id="country" name="country" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="4"> <option value="-1">--国家--</option> </select> </div> <div class="form-group address_p rel"> <select id="city" name="city" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="5"> <option value="-1">--城市--</option> </select> </div> </div> </div> <div class="form-group control-group"> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>详细地址</label> <div class="col-sm-10 controls"> <textarea class="form-control" name="address" check-type="required" required-message="详细地址不能为空!"><?=$enter['address']?></textarea> </div> </div> <div class="form-group"> <label for="<PASSWORD>" class="col-sm-2 control-label">网站地址</label> <div class="col-sm-10"> <textarea class="form-control" name="web_url" ><?=$enter['web_url']?></textarea> </div> </div> <div class="form-group control-group up-pic"> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>营业执照</label> <div class="col-sm-10 "> <input type='file' name="file" class="up-license" value="<?=$enter['license']?>"> <input type="hidden" name="license" value="<?=$enter['license']?>"> <img src="<?=$enter['license'] ? $enter['license'].'!190':''?>"> <span class="label label-info"> 请上传合法有效的营业执照清晰彩色原件扫描件 </span> </div> </div> <hr/> <div class="form-group control-group"> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>电话</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="tel" value="<?=$enter['tel']?>" check-type="mobile" > </div> </div> <div class="form-group"> <label for="input<PASSWORD>" class="col-sm-2 control-label">QQ</label> <div class="col-sm-10"> <input type="text" class="form-control" name="qq" value="<?=$enter['qq']?>"> </div> </div> <div class="form-group"> <label for="input<PASSWORD>" class="col-sm-2 control-label">微信</label> <div class="col-sm-10"> <input type="text" class="form-control" name="wx" value="<?=$enter['wx']?>"> </div> </div> <div class="form-group"> <label for="input<PASSWORD>" class="col-sm-2 control-label">微博</label> <div class="col-sm-10"> <input type="text" class="form-control" name="wb" value="<?=$enter['wb']?>"> </div> </div> <h4 style="border-bottom:1px solid #ccc">3.提交上传</h4> <div class="form-group control-group up-pic"> <label for="input<PASSWORD>" class="col-sm-2 control-label"><?=$must?>头像</label> <div class="col-sm-10 " > <input type='file' name="file" class="up-logo" value="<?=$enter['logo']?>"> <input type="hidden" name="logo" value="<?=$enter['logo']?>"> <img src="<?=$enter['logo'] ? $enter['logo'].'!w348':''?>"> <span class="label label-info"> 头像在网站页面可见,禁止上传带有联系方式的头像。 </span> </div> </div> <div class="form-group control-group"> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>商家简介</label> <div class="col-sm-10 controls"> <textarea class="form-control" name="description" check-type="required" required-message="商家简介不能为空!"><?=$enter['description']?></textarea> </div> </div> <h4 style="border-bottom:1px solid #ccc">4.确认入驻条款和条件</h4> <div class="form-group"> <div class=" col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="clause" <?=$enter ? "checked":''?>> 我已阅读《极旅入驻协议》并同意。 </label> </div> </div> </div> <div class="form-group"> <div class=" col-sm-10"> <button type="button" id="confirm-enter" class="btn btn-block btn-info">提交入驻</button> </div> </div> </div><!-- form-horizontal --><file_sep>/1/protected/action/ApiAction.class.php <?php class ApiAction extends Action{ public function __construct(){ parent::__construct(); } /** * bucket变化时,return-url变化,form-api_secret也要变化 * upyun使用:接口地址:http://v0.api.upyun.com 获取签名的地址 * @param bucket 空间名称 * save-key 图片路径 ... * 空间唯一对应的表单API验证密钥格式: * $signature = md5($policy.'&'.$form_api_secret); */ public function get_upyun_key() { $result = array ( status => 'ok' ); $policyfileds = array( 'bucket', 'save-key', 'allow­file­type', 'return-url', 'content­length­range', 'image-width-range', 'image-height-range' ); $policydoc = array(); foreach ($policyfileds as $field){ $post_field = str_replace("-","_",$field); if ($_REQUEST[$post_field]){ $policydoc[$field] = $_REQUEST[$post_field]; } } $policydoc[expiration] = time () + 60 * 5; if (DEBUG){ var_dump("policydoc:",$policydoc); } $json = json_encode($policydoc); $policy = base64_encode($json); //该form_secret为bucket名称为tdcms的密钥 //'mobile01'=>'<KEY> $keys = array( 'jilv-ad'=>'<KEY> '<KEY> <KEY> 'jishop'=>'<KEY> ); $form_api_secret = $keys[$_POST['bucket']]; $sign = md5 ( "{$policy}&{$form_api_secret}" ); $result['json'] = $json; $result ['policy'] = $policy; $result ['sign'] = $sign; header ( 'Content-type: application/json' ); $this->json ( $result ); } public function upload_callback($bucket) { header ( 'Content-type: text/plain; chartset=utf8' ); $data = array ( code => $_REQUEST ['code'], message => $_REQUEST ['message'], url => "http://{$bucket}.b0.upaiyun.com" . $_REQUEST ['url'], image_width => $_REQUEST ['image-width'], image_height => $_REQUEST ['image-height'] ); $this->json ( $data ); } } ?><file_sep>/1/protected/view/cate/product_item_list.php <?php V("cate/header.php"); ?> <?php if(DEBUG){ echo var_export($_SERVER, true); } ?> <div class="row"> <div class = "col-lg-12 col-md-12"> <h1><?=$item['name']?></h1> </div> <div class = "col-lg-12 col-md-12"> <div class = "col-lg-3 col-md-3 sidebar-nav" id="cate_nav_bar"> <?php V ('cate/nav_bar.php');?> </div > <div class = "col-lg-9 col-md-9 hd" > <div id="filter_bar"> <nav class="navbar navbar-default" role="navigation"> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">价格排序</a></li> <li><a href="#">发布时间</a></li> <li><a href="?view=row"><i class="icon-align-justify"></i></a></li> <li><a href="?view=grid"><i class="icon-table"></i></a></li> </ul> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="输入搜索关键字"> </div> <button type="submit" class="btn btn-default">搜索</button> </form> </div><!-- /.navbar-collapse --> </nav> </div> <div class="item_list"> <?php include "item_list_{$view}.php"; ?> </div> </div><!-- col-lg-11 --> </div> </div> <script src="/static/js/product/item_detail.js"></script> <?php V("cate/footer.php"); ?><file_sep>/1/YunPHP/main.php <?php defined('YUNPHP') or exit('can not access!'); $uri = explode("?", $_SERVER['REQUEST_URI']); $uri = $uri[0]; #$uri = explode('.', $uri); #$uri = $uri[0]; $uri = str_replace(".html", "", $uri); if(preg_match("/\.html/", $_SERVER['REQUEST_URI']) > 0){ define('HTML_VIEW', 1); header("Cache-Control: max-age=600"); }else { define('HTML_VIEW', 0); } if(isset($_SERVER['HTTP_X_WX_UUID']) && $_SERVER['HTTP_X_WX_UUID']){ $extra_uri = $_SERVER['HTTP_X_WX_UUID']; }else { list($uri, $extra_uri) = explode("~", $uri, 2); if($extra_uri){ setcookie("YUN_THEMES", $extra_uri, null, "/"); }else { //$extra_uri = $_COOKIE['YUN_THEMES']; } } include_once (YUNPHP.'core/Autoloader.class.php'); include_once (YUNPHP.'core/YunPHP.class.php'); include_once (YUNPHP.'core/Hook.class.php'); include_once (YUNPHP.'core/Action.class.php'); include_once (YUNPHP.'core/Module.class.php'); include_once (YUNPHP.'core/common.php'); require_once(YUNPHP.'lib/Configure.class.php'); require_once(YUNPHP.'lib/Log.class.php'); require_once(YUNPHP.'lib/Db.class.php'); require_once(YUNPHP.'lib/SAECache.class.php'); require_once(YUNPHP.'lib/Router.class.php'); define('DIR_ACTION',DOCROOT.'action/'); define('DIR_MODULE',DOCROOT.'module/'); define('DIR_VIEW',DOCROOT.'view/'); set_exception_handler('my_exception_handler'); $autoloader = new Autoloader(); $autoloader->init(); Configure::load('config'); $RTR = new Router($uri); $uri_argvs = $RTR->getUriArgvs(); $class = $RTR->getClass(); $method = $RTR->getMethod(); $action = ucfirst($class); $action = $action.'Action'; include_once (DIR_ACTION."$action.class.php"); if(!class_exists($action)){ throw new Exception("404 $action not exist!"); } $app = new $action(); if($extra_uri){ $extra_uri = explode(".", $extra_uri); $extra_uri = $extra_uri[0]; list($platform, $style) = explode("-", $extra_uri, 2); } $platform = isset($platform) ? $platform:''; $style = isset($style) ? $style:''; $app->platform = $platform ? $platform : "common"; $app->style = $style ? $style : "default"; define('PLATFORM', $app->platform); define('STYLE', $app->style); // if(DEBUG){ // echo "platform:{$app->platform}, style:{$app->style}\n"; // } if(method_exists($app, "hook_start_request")){ $r = call_user_func_array(array($app, "hook_start_request"), array($method)); if($r === false){ return; } } // $pm = "${method}_${platform}"; if (isset($platform) && $platform){ $pm = $method."_".$platform; } if(isset($pm) && method_exists($app, $pm)){ call_user_func_array(array($app, $pm), array_slice($uri_argvs,2)); }else { call_user_func_array(array($app, $method), array_slice($uri_argvs,2)); } //this is the end of the main.php<file_sep>/1/protected/action/ShopComplaintAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 商家后台。 * * @author deonwu * */ class ShopComplaintAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this,true); if(!($this->shop['shop_id'] > 0) || $this->shop['verify_status'] !== '1'){ header("location: /shopEnter/index"); return false; } $this->assign('main_nav','shop'); } public function business_complaint(){ $this->assign('title','投诉管理-极旅'); $this->assign('nav_index','2_5'); $this->assign('js_group','business_complaint'); $this->display("shop/business/business_complaint.php"); } }<file_sep>/1/protected/module/ProductModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class ProductModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function get_product($pid){ $p = $this->db->getLine("select * from shop_product_info where `id`='{$pid}'"); $u = array('m'=>'分钟', "d"=>'天'); //duration_label if($p['shop_id'] > 0){ $shop = $this->db->getLine("select * from shop_business_enter_info where shop_id='{$p['shop_id']}'"); $price_items = $this->db->getData("select * from shop_product_price_item where pid='{$pid}'"); foreach($price_items as &$i){ $l = $u[$i['duration_unit']] ? $u[$i['duration_unit']] : "分钟"; $i['duration_label'] = "{$i['duration']} {$l}"; } $p['shop'] = $shop; $p['price_items'] = $price_items; $p['imgs'] = explode(";", $p['pic_list']); } return $p; } public function get_product_price_item($iid){ $p = $this->db->getLine("select * from shop_product_price_item where `id`='{$iid}'"); return $p; } public function search_products(){ $sql = <<<SQL select p.*, s.shop_name, v.* from shop_product_info p join shop_business_enter_info s using(shop_id) left join shop_product_view_info v on (p.id=v.pid) SQL; $p = $this->db->getData($sql); if(DEBUG){ echo "count:" . count($p); } $p = $this->convert_prodcuts_for_view(&$p); if(DEBUG){ echo "count 2:" . count($p); } return $p; } public function convert_prodcuts_for_view($items){ foreach($items as &$i){ $i['imgs'] = explode(";", $i['pic_list']); $i['short_description'] = mb_substr($i['description'], 0, 80); } return $items; } }<file_sep>/1/sql/sql/update_min_price.sql -- 修改每个收费项目的价格。 update shop_product_price_item , ( SELECT item_id, MIN( adult_price ) as min_price FROM `shop_product_price_detail` WHERE inventory >0 AND price_date >20140531 GROUP BY item_id ) s set shop_product_price_item.min_price = s.min_price where shop_product_price_item.id=s.item_id; -- 修改商品价格 insert into shop_product_view_info(pid, min_price) SELECT pid, MIN( min_price ) as min_price FROM `shop_product_price_item` GROUP BY pid on duplicate key update min_price = values(min_price);<file_sep>/1/static/ueeditor/php/getContent.php <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <script src="../uparse.js" type="text/javascript"></script> <script> uParse('.content',{ 'highlightJsUrl':'../third-party/SyntaxHighlighter/shCore.js', 'highlightCssUrl':'../third-party/SyntaxHighlighter/shCoreDefault.css' }) </script> <?php //获取数据 error_reporting(E_ERROR|E_WARNING); $content = htmlspecialchars(stripslashes($_POST['myEditor'])); $content1 = htmlspecialchars(stripslashes($_POST['myEditor1'])); //存入数据库或者其他操作 //显示 echo "第1个编辑器的值"; echo "<div class='content'>".htmlspecialchars_decode($content)."</div>"; echo "<br/>第2个编辑器的值<br/>"; echo "<textarea class='content' style='width:623px;height:300px;'>".htmlspecialchars_decode($content1)."</textarea><br/>";<file_sep>/1/protected/view/admin/front/home_page_tab_main.php <div class="panel" > <div class="input-group"> <span class="input-group-addon">上传首页背景</span> <input id="main_file" type="file" name='file' class="form-control" placeholder="新背景图片"> </div> <table class='table' id="main_pic_table"> <tr> <th>图片编号</th> <th>图片</th> <th>操作</th> <th>上传人</th> <th>上传日期</th> </tr> <?php foreach($main_pics as $p){?> <tr <?=$p['active'] == 1 ? 'class="success"' : '' ?>> <td><?=$p['id']?></td> <td> <a href="<?=$p['url']?>" class='thumbnail' style='max-width:300px;'><img src="<?=$p['url']?>"></a> </td> <td class='action' pid='<?=$p['id']?>'> <a href="#" class="active btn btn-success">发布</a> <a href="#" class="remove btn btn-danger">删除</a> </td> <td><?=$p['name']?></td> <td><?=$p['create_time']?></td> </tr> <?php }?> </table> </div><file_sep>/1/protected/view/admin/product/product_list.php <?php V ('admin/header.php');?> <?php $status = array(0=>'未审核',1=>'审核通过',2=>'已驳回'); ?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V ('admin/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10 "> <h3>查询产品</h3> <form action="?" method="get"> 产品名称: <input id="name" name="name" value="<?=$_REQUEST['name']?>" placeholder="例如:济州岛三日游"> 审核状态 : <select name="verify_status"> <option value="">全部</option> <?php foreach ($status as $k=>$s){?> <option value="<?=$k?>" <?=$_REQUEST['verify_status'] === "$k" ? "selected='selected'":""?>><?=$s?></option> <?php }?> </select> <input type="submit" name="" value="查询"> </form> <h3>产品列表</h3> <div id="product_list"> <table class="table" width="100%"> <tbody> <tr> <th>产品编号</th> <th>产品图片</th> <th>产品名称</th> <th>产品介绍</th> <th>产品分类</th> <th>城市</th> <th>更新时间</th> <th>状态</th> <th>操作</th> </tr> <?php foreach ($data as $product){ $pic_arr = explode(";",$product['pic_list']); ?> <tr> <td><?=$product['id']?></td> <td> <a target="_blank" href="/product/preview/<?=$product['id']?>"><img src="<?=$pic_arr[0] ?>!190" /> </a> </td> <td><a target="_blank" href="/product/preview/<?=$product['id']?>"><?=$product['name']?></a> </td> <td><?=strlen($product['description']) > 10 ? sub_string($product['description'],10) : $product['description']?></td> <td> <?=$product['type_name'].'/'.$product['topic_name'].'/'.$product['category_name']?> </td> <td> <?=$product['continent']?><br/> <?=$product['country']?><br/> <?=$product['city']?><br/> <?=$product['address']?> </td> <td><?=$product['update_time']?></td> <td><?=$status[$product['verify_status']]?></td> <td> <?php if (!$product['verify_status']){?> <a class="verify btn btn-info" id="<?=$product['id']?>">通过</a> <a href="/admin/product_refund/<?=$product['id']?>" class="btn btn-danger">驳回</a> <?php }elseif ($product['verify_status'] == 2){?> <a href="/admin/product_refund/<?=$product['id']?>" class="btn btn-default">查看</a> <?php }?> </td> </tr> <?php }?> </tbody> </table> <div class="page"><?=$page?></div> </div> </div> </div> <script> //审核通过 $("#product_list").delegate(".verify","click",function(){ var that = this; var post_data = {}; post_data.id = $(this).attr("id"); post_data.verify_status = 1; $.post("/admin/product_pass_save",post_data, function(r){ if(r.status == 'ok'){ location.href="/admin/product_list"; } },'json') }) </script> <?php V ('admin/footer.php');?><file_sep>/1/protected/view/home/index.php <?php include 'header.php';?> <<style> <!-- .body .ui-nav .cover{ background-image:url(<?=$main_pic?>!home); } --> </style> <div class="body"> <div class="ui-nav"> <div class="cover"> <div class="container" style="margin: 0 auto;position: relative;"> <div class="box"> <div class="search-box"> <h2>搜索你想去的目的地</h2> <form > <div class="input-group search-form"> <input type="text" class="form-control" placeholder="您想去哪个城市旅游?"> <span class="input-group-addon" style="background-color: #009dd5;border: 1px solid #009dd5;">搜索</span> </div> </form> </div> </div> </div> </div> <div class="banner"> <div class="container"> <h3 class='text-center'>“最接地气”体验式旅行、发现世界新玩法!</h3> <ul class="list-inline"> <li><h5 class="text-left">发现</h5><p>足不出户、先知天下</p></li> <li><h5 class="text-left">计划</h5><p>抛开攻略,轻松计划旅行</p></li> <li><h5 class="text-left">预定</h5><p>在线预定,快乐出行</p></li> </ul> </div> </div> </div> <div class="ui-content"> <div class="activity"> <div class="container"> <h1>热门活动</h1> <div class="row"> <?php $i = 0; foreach($product_list as $p){ $i++; ?> <div class="col-xs-4 col-md-4 pic"> <a href="/cf/<?=$p['id']?>.html" class="thumbnail"> <img src="<?=$p['pic_url']?>!w348"> </a> <span><?=$p['cate_label']?></span> </div> <?php }?> <?php for(;$i<9;$i++){?> <div class="col-xs-4 col-md-4 pic"> <a href="/cate.html" class="thumbnail"> <img src="<?=$THEME_URL ?>/img/demo.jpg"> </a> <span>热气球</span> </div> <?php }?> </div> </div> </div> <div class="city"> <div class="container"> <div class="panel panel-default" style="border:none"> <h3>热门城市</h3> <div class="row"> <?php $i = 0; foreach($dest_list as $p){ $i++; ?> <div class="col-xs-4 col-md-4 pic"> <a href="/cf/<?=$p['id']?>.html" class="thumbnail"> <img src="<?=$p['pic_url']?>!w348"> </a> <span><?=$p['cate_label']?></span> </div> <?php }?> <?php for(;$i<9;$i++){?> <div class="col-xs-4 col-md-4 pic"> <a href="/cate.html" class="thumbnail"> <img src="<?=$THEME_URL ?>/img/city.jpg"> </a> <span>曼谷</span> </div> <?php }?> </div> </div> </div> </div> </div> <div class="container"> <div class="row good"> <div class="col-xs-12 col-md-4 clearfix"> <img src="/static/img/f1.png" style="float:left;"> <div class="f_label"> 靠谱<br/> 精选终端商家直销<br/> 资质认证层层把关 </div> </div> <div class="col-xs-12 col-md-4 clearfix"> <img src="/static/img/f2.png" style="float:left;"> <div class="f_label"> 专业<br/> 精选终端商家直销<br/> 资质认证层层把关 </div> </div> <div class="col-xs-12 col-md-4 clearfix"> <img src="/static/img/f3.png" style="float:left;"> <div class="f_label"> 透明<br/> 精选终端商家直销<br/> 资质认证层层把关 </div> </div> </div> </div> </div> <?php include 'footer.php';?> <file_sep>/1/protected/action/AdminFrontAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 管理员后台 前端管理 * @author lili * */ class AdminFrontAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_admin_auth($this, true); $this->assign("js_group","admin_home"); if($this->admin_user['role_id'] != 2 && $this->admin_user['role_id'] != 4){ $this->no_admin(); exit(); } Configure::load('cms'); $cms = Configure::getItems('cms'); $this->load_helper('TaoDian'); $this->api = new TaoDian($cms['app_id'],$cms['app_secret']); $this->assign("nav_main", "front"); } public function index(){ $this->home_page(); } public function home_page(){ $m = new AdminModel(); $pic = $m->load_main_pic(); $this->assign("dest_list", $m->load_cate_filter("home", "dest")); $this->assign("product_list", $m->load_cate_filter("home", "product_type")); $this->assign("main_pics", $pic); $this->assign("nav_index", "home_page"); $this->display("admin/front/home_page.php"); } /* public function load_main_pic(){ $m = new AdminModel(); $pic = $m->load_main_pic(); $this->assign("main_pics", $pic); $this->assign("nav_index", "home_page"); $this->display("admin/front/home_page.php"); } */ public function save_cate_filter(){ $m = new AdminModel(); $cid = $_REQUEST['cid']; $data = array('page_view'=>$_REQUEST['page_view'], 'cate_type'=>$_REQUEST['cate_type'], 'cate_label'=>$_REQUEST['cate_label'], 'cate_value'=>$_REQUEST['cate_value'], 'pic_url'=>$_REQUEST['pic_url'], 'view_order'=>$_REQUEST['view_order'], 'status'=>$_REQUEST['status'], 'user_id'=>$this->admin_user['id'] ); if($cid > 0){ $m->db->updateData("app_cate_filter", $data, "`id`='{$cid}'"); }else { $m->db->insertData("app_cate_filter", $data); } $r = array('status'=>'ok'); if($m->db->errno != 0){ $r['status'] = 'err'; } $this->json($r); } public function update_cate_status(){ $m = new AdminModel(); $st = $_REQUEST['active']; $m->db->runSql("update app_cate_filter set status = '{$st}' where `id`='{$_REQUEST['pid']}'"); $this->json(array('status'=>'ok')); } public function save_home_pic(){ $m = new AdminModel(); $m->db->insertData("app_home_page", array('url'=>$_REQUEST['url'], 'active'=>0, 'user_id'=>$this->admin_user['id'], 'create_time'=>time())); $this->json(array('status'=>'ok')); } public function update_home_pic(){ $m = new AdminModel(); $st = $_REQUEST['active']; if($st == 1){ $m->db->runSql("update app_home_page set active = 0 where active=1"); } $m->db->runSql("update app_home_page set active = '{$st}' where `id`='{$_REQUEST['pid']}'"); $this->json(array('status'=>'ok')); } } ?><file_sep>/1/protected/view/shop/enter/message.php <?php V ('shop/header.php');?> <div class="body"> </div> <?php V ('shop/footer.php');?><file_sep>/1/protected/view/admin/front/home_page.php <?php V('admin/header.php');?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V('admin/front/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10" > <ul class="nav nav-tabs" id="mytab"> <li class="active"><a href="#main_pic" data-toggle="tab">首页焦点图</a></li> <li><a href="#topic" data-toggle="tab">热门主题</a></li> <li><a href="#dest" data-toggle="tab">热门目的地</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="main_pic"> <?php include 'home_page_tab_main.php';?> </div> <div class="tab-pane fade" id="topic"> <?php include 'home_page_tab_topic.php';?> </div> <div class="tab-pane fade" id="dest"> <?php include 'home_page_tab_dest.php';?> </div> </div> </div> <script> $('#myTab a').click(function (e) { e.preventDefault() $(this).tab('show') }) </script> </div> <?php V('admin/footer.php');?><file_sep>/1/protected/action/ShopAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 商家后台。商品管理 * * @author deonwu * */ class ShopAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this,true); if(!($this->shop['shop_id'] > 0) || $this->shop['verify_status'] !== '1'){ header("location: /shopEnter/index"); return false; } $this->assign('main_nav','shop'); } public function index(){ $this->product(); } public function product(){ $model = new ShopModel(); $product_list = $model->product_list($this->shop['shop_id']); $this->assign('product_list',$product_list); $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_list'); $this->display("shop/product/product_list.php"); } public function product_done($pid){ $m = new ProductModel(); $p = $m->get_product($pid); $this->assign("product", $p); $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_add'); $this->display("shop/product/product_done.php"); } public function product_pending(){ $model = new ShopModel(); $product_list = $model->product_list($this->shop['shop_id'], "0, 2"); $this->assign('product_list',$product_list); $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_pending'); $this->display("shop/product/product_pending_list.php"); } public function product_remove(){ $model = new ShopModel(); $this->json($model->product_remove()); } public function product_add(){ $model = new ShopModel(); $languange = array('中国语','俄语','印度语','孟加拉语','希腊语','德语','意大利语', '日语','法语','英语','荷兰语','葡萄牙语','西班牙语','阿拉伯语','韩语'); $this->assign('lan',$languange); $travel_type = $model->product_travel_type(); $this->assign('travel_type',$travel_type); if ($_REQUEST['id']){ $product_info = $model->product_one($_REQUEST['id']); $this->assign('product_one',$product_info); $travel_topic = $model->product_travel_topic(); $this->assign('travel_topic',$travel_topic); $travel_category = $model->product_travel_category(); $this->assign('travel_category',$travel_category); } $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_add'); $this->assign('js_group','business_product'); $this->display("shop/product/product_add_base.php"); } public function product_travel_topic(){ $model = new ShopModel(); $data = $model->product_travel_topic(); $this->json(array('status'=>'ok','data'=>$data)); } public function product_travel_category(){ $model = new ShopModel(); $data = $model->product_travel_category(); $this->json(array('status'=>'ok','data'=>$data)); } public function product_add_price(){ $model = new ShopModel(); if ($_REQUEST['pid']){ $product_info = $model->product_one($_REQUEST['pid']); $this->assign('product_one',$product_info); } if ($_REQUEST['id']){ $price_one = $model->product_price_one($_REQUEST['id']); }else { $price_one['start_date'] = date("Y-m-d"); $price_one['end_date'] = date("Y-m-d", time() + 30 * 24 * 60 * 60); $price_one['adult_descrip'] = "超过12岁"; $price_one['child_descrip'] = "12岁以下儿童"; $price_one['start_time'] = "09:00"; $price_one['advance_day'] = "3"; } $this->assign('price_one',$price_one); $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_add'); $this->assign('js_group','business_product'); $this->display("shop/product/product_add_price.php"); } public function price_list(){ $model = new ShopModel(); if ($_REQUEST['pid']){ $price_list = $model->product_price_list($_REQUEST['pid']); $product_info = $model->product_one($_REQUEST['pid']); $this->assign("product_info", product_info); $this->assign('price_list',$price_list); } //商家自家不是 if($product_info['shop_id'] != $this->shop['shop_id']){ header("location: /shop/"); return; } $this->assign('title','活动管理-极旅'); $this->assign('nav_index','product_add'); $this->assign('js_group','business_product'); $this->display("shop/product/price_list.php"); } public function product_base_save(){ $shopModel = new ShopModel(); $_REQUEST['shop_id'] = $this->shop['shop_id']; $data = $shopModel->product_base_save(); $this->json($data); } public function product_price_save(){ $shopModel = new ShopModel(); $_REQUEST['shop_id'] = $this->shop['shop_id']; $return = $shopModel->product_price_save(); if ($_REQUEST['save_type'] == 'base_price'){ $this->json($return); }else{ if ($return['status'] == 'err'){ $this->json($return); }else{ $_REQUEST['item_id'] = $return['item_id']; $this->generate_price(); } } } public function generate_price(){ $item_id = $_REQUEST['item_id'] + 0; $st = $_REQUEST['start_date']; $et = $_REQUEST['end_date']; $m = new ShopModel(); $sql = "select 1 from shop_product_price_item where `id`='{$item_id}' and shop_id='{$this->shop['shop_id']}'"; $is_own = $m->db->getVar($sql); if(DEBUG){ echo "check onwer:{$sql}"; } if($is_own > 0){ $data= $m->generate_item_price($this->shop['shop_id'], $item_id, $st, $et, $_REQUEST['adult_price'], $_REQUEST['child_price'], $_REQUEST['inventory']); }else { $data = array('status'=>'err', "code"=>'not_onwer'); } $this->json($data); } public function save_date_price(){ $item_id = $_REQUEST['item_id'] + 0; $st = $_REQUEST['price_date']; $m = new ShopModel(); $sql = "select 1 from shop_product_price_item where `id`='{$item_id}' and shop_id='{$this->shop['shop_id']}'"; $is_own = $m->db->getVar($sql); if(DEBUG){ echo "check onwer:{$sql}"; } if($is_own > 0){ $data= $m->save_item_date_price($this->shop['shop_id'], $item_id, $st, $_REQUEST['adult_price'], $_REQUEST['child_price'], $_REQUEST['inventory']); }else { $data = array('status'=>'err', "code"=>'not_onwer'); } $this->json($data); } public function load_calendar(){ $this->load_helper("Calender"); $this->load_helper("CalenderRenders"); $c = new Calendar(); $start = $_REQUEST['start']; if(strlen($start) >= 7){ $c->year = substr($start, 0, 4); $c->month = substr($start, 5,2); }else { $c->year = date('Y'); $c->month = date('m'); } $m = new ShopModel(); $item_id = $_REQUEST['item_id']; $s = "{$c->year}{$c->month}00"; $e = "{$c->year}{$c->month}32"; $sql = <<<SQL select * from shop_product_price_detail where item_id='{$item_id}' and price_date >= {$s} and price_date <= {$e} SQL; $data = $m->db->getData($sql); if(DEBUG){ echo "sql:{$sql}, data:" . var_export($data); } $c->render = new SimpleRender($data); $this->assign("c", $c); $this->display("common/calender.php"); } }<file_sep>/1/protected/view/shop/enter/enter_alert.php <?php if($enter['shop_id'] > 0){?> <?php if (!$enter['verify_status']){?> <div class="alert alert-warning"> 商家入驻信息正在审核中, 审核通过后才能,录入旅游活动信息。 </div> <?php }elseif ($enter['verify_status'] === '2'){ $refund_arr = explode(";",$enter['refund_proof']); ?> <div class="alert alert-danger" style='color:red'> <strong> 已被管理员驳回 </strong><br/> <div style="background-color:white;display:block;padding:10px;color:black;margin-top:10px;"> <p>驳回原因:&nbsp;&nbsp;<?=$enter['refund_excuse']?></p> <p>驳回材料:&nbsp;&nbsp; <?php if ($refund_arr){?> <?php foreach ($refund_arr as $refund){?> <a href="<?=$refund?>" target="_blank">点击查看</a> <?php }?> <?php }?> </p> </div> </div> <?php }?> <?php } ?><file_sep>/1/protected/action/HomeAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 首页 * @author lili * */ class HomeAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this); $this->assign("HOST",host_url()."/home/"); } } ?><file_sep>/1/protected/view/home/header.php <?php $THEME_URL = host_url()."/static"; ?> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=1"> <meta name="generator" content="SAE at <?php echo date("Y-m-d h:i:s"); ?>" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?=$title?></title> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/bootstrap.min.css" media="screen"> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/font-awesome.min.css"> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/home/index.css"> <?php if($css_path) {?> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/<?=$css_path ?>"> <?php }?> </head> <body> <script src="<?=$THEME_URL ?>/js/jquery/jquery-1.9.1.min.js"></script> <script src="<?=$THEME_URL ?>/js/bootstrap/bootstrap.min.js"></script> <!-- <script src="<?=$THEME_URL ?>/js/bootstrap/bootstrap-validation.js"></script> --> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand td-logo" href="/" target="_blank"> <img src="/static/img/logo.png"> </a> <h4>说走就走的智慧旅行</h4> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="user_info_nav nav navbar-nav"> <li> <a href="/index/welcome_shop"> <span>商家入驻</span> </a> </li> <li class="dropdown" index="2"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> 帮助 <span class="caret"></span> </a> <ul class="dropdown-menu "> <li><a href="/shop/"><i class="icon-lock"></i> &nbsp;联系我们</a></li> <li><a href="/shop/tourist"><i class="icon-user"></i> &nbsp;常见问题</a></li> <li><a href="/shop/message"><i class="icon-lock"></i> &nbsp;客服:</a></li> </ul> </li> <?php if($shop){?> <li> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-user" style="font-size:1.3em;color:black"></i><?=$nick?> <span class="caret"></span> </a> <ul class="dropdown-menu "> <li><a href="/shop/"><i class="icon-lock"></i> &nbsp;我是游客</a></li> <li><a href="/shop/"><i class="icon-lock"></i> &nbsp;我是服务商</a></li> <?php if($shop['is_admin'] == 1){?> <li><a href="/admin/"><i class="icon-lock"></i> &nbsp;管理员后台</a></li> <?php }?> <li><a href="/user/logout"><i class="icon-lock"></i> &nbsp;退出</a></li> </ul> </li> <?php } else {?> <li> <a href="/user/login"> <i class="icon-comments"></i> <span>登录</span> </a> </li> <li> <a href="/user/register"> <i class="icon-comments"></i> <span>注册</span> </a> </li> <?php }?> </ul> </div> </div> </nav> <file_sep>/1/protected/view/product/product_item.php <?php V("product/header.php"); ?> <div class="row"> <div class = "col-lg-12 col-md-12"> <h1><?=$item['name']?></h1> </div> <div class = "col-lg-12 col-md-12"> <div class = "col-lg-9 col-md-9 hd" > <div class="pics"> <div class="thumbnail"> <img src="<?=$item['imgs'][0] ?>" id="main_pic" > </div> <div class="row item_thumbs"> <div class = "col-lg-12 col-md-12"> <?php foreach($item['imgs'] as $p){ ?> <div class="col-xs-2 col-md-2"> <a href="#" class="thumbnail"> <img src="<?=$p ?>" > </a> </div> <?php } ?> </div> </div> </div> <div class = "price_items"> <div> 选择活动时间: </div> <?php foreach($item['price_items'] as $price) {?> <div class="well clearfix"> <div><?=$price['price_name']?></div> <div class="pull-right"> <div>RMB <span class='item_price_val'><?=$price['base_price'] ?></span> 每人起</div> <a class="btn btn-success" href="">预订</a> </div> <div> <div><i class="icon-comments-alt"></i> <label>服务语言:</label> <?=$item['language'] ?> </div> <?php if($price['duration'] > 0) {?> <div><i class="icon-time"></i> <label>持续时间:</label> <?=$price['duration_label'] ?> </div> <?php }?> </div> <div class="center-block clearfix"><a class="show_more" href="#" iid="<?=$price['id'] ?>">查看详细信息</a></div> <div class="price_detail center-block" style="display:none;"> <img src="/static/img/loading.gif" /> </div> </div> <?php }?> </div> <?php V("product/product_detail_info.php"); ?> <div style="margin-top:20px;margin-bottom:20px;"> 产品编号: <?=$item['id'] ?> </div> </div><!-- col-lg-11 --> <div class = "col-lg-3 col-md-3 sidebar-nav"> <?php V ('product/nav_bar.php');?> </div > </div> </div> <script src="/static/js/product/item_detail.js"></script> <?php V("product/footer.php"); ?><file_sep>/1/protected/module/CateModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class CateModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function get_cate_list(){ $cates = $this->db->getData("select * from app_cate_filter where status=0 order by cate_type, view_order asc"); $cat_groups = array(); foreach($cates as $c){ $cat_groups[$c['cate_type']][] = $c; } return $cat_groups; } }<file_sep>/1/index.php <?php $begin_time = microtime(); if($_REQUEST['debug'] == 'true'){ define('DEBUG',TRUE); if(function_exists('sae_set_display_errors')){ sae_set_display_errors(TRUE); } ini_set('display_errors', 1); define('SETUP_APP', 0); }else { define('DEBUG', FALSE); if(function_exists('sae_set_display_errors')){ sae_set_display_errors(FALSE); } ini_set('display_errors', 0); } $host = $_SERVER['HTTP_HOST']; $n = explode(".", $host); if($n[0] > 1000 && $n[0] < 9999){ header("location: http://s8.mty5.com/m/{$n[0]}.html"); return; } function session_start_new(){ if(define("OPNED", 1)){ if(isset($_GET['view']) && $_GET['view'] == 'html'){ session_cache_limiter(''); header("Cache-Control: max-age=600"); } $host = $_SERVER['HTTP_HOST']; if(preg_match("/s\d+\.m\./", $host) > 0){ ini_set("session.cookie_domain", $host); } session_start(); } } //open the output buffer, otherwise can't change the header info. ob_start (); //session_start(); //xhprof —— facebook 搞的一个测试php性能的扩展 define('XHPROF', FALSE); if(XHPROF){ sae_xhprof_start(); } //定义YunPHP的类库的路径 $dir_yunphp = 'YunPHP'; $dir_protected = 'protected'; //决定是否让系统使用memcache, define('USE_MEM',TRUE); //定义量目录,DOCROOT为项目的目录,YUNPHP为系统目录 define('WEBROOT',realpath(dirname(__FILE__))); define('YUNPHP',WEBROOT.'/'.$dir_yunphp.'/'); define('DOCROOT',WEBROOT.'/'.$dir_protected.'/'); /* 过滤函数 */ //整型过滤函数 function get_int($number) { return intval($number); } //字符串型过滤函数 function get_str($string) { if (!get_magic_quotes_gpc()) { return addslashes($string); } return $string; } /* 过滤所有GET过来变量 */ foreach ($_GET as $get_key=>$get_var) { if (is_numeric($get_var)) { $_GET[$get_key] = get_int($get_var); } else { $_GET[$get_key] = get_str($get_var); } } /* 过滤所有POST过来的变量 */ foreach ($_POST as $post_key=>$post_var) { if (is_numeric($post_var)) { $_POST[$post_key] = get_int($post_var); } else { $_POST[$post_key] = get_str($post_var); } } define('RUNTIME','saemc:/'); require_once 'YunPHP/main.php'; if(XHPROF){ sae_xhprof_end(); } $end_time = microtime(); $escaped_time = $end_time - $begin_time; // echo "escaped time $escaped_time"; <file_sep>/1/protected/action/ShopEnterAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 商家后台。商家信息 * * @author deonwu * */ class ShopEnterAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this,true); $this->assign('main_nav','shop'); } public function index(){ $this->enter(); } public function enter(){ $model = new ShopEnterModel(); $enter = $model->select_enter_info($this->shop['id']); $this->assign('enter',$enter); if (DEBUG){ var_dump($enter); } $this->assign('title','商家入驻-极旅'); $this->assign('nav_index','shop_enter'); $this->assign('js_group','business_enter'); $this->display("shop/enter/enter.php"); } public function save_enter_info(){ $shopModel = new ShopEnterModel(); $_REQUEST['sid'] = $this->shop['id']; $data = $shopModel->save_enter_info(); if(!($this->shop['shop_id'] > 0)){ $shop_info = $shopModel->db->getVar("select shop_id,verify_status from shop_business_enter_info where sid='{$this->shop['id']}'"); $_SESSION['shop']['shop_id'] = $shop_info['shop_id']; $_SESSION['shop']['verify_status'] = $shop_info['verify_status']; } $this->json($data); } public function my(){ if(!($this->shop['shop_id'] > 0)){ header("location: /shopEnter/"); return; }else { header("location: /shop/product/"); return; } $this->assign('title','首页-极旅'); $this->assign('nav_index','1'); $this->display("shop/enter/my.php"); } public function tourist(){ $this->assign('title','游客-极旅'); $this->assign('nav_index','3'); $this->display("shop/enter/tourist.php"); } public function message(){ $this->assign('title','消息中心-极旅'); $this->assign('nav_index','4'); $this->display("shop/enter/message.php"); } public function setting(){ $this->assign('title','设置-极旅'); $this->assign('nav_index','5'); $this->assign('sub_nav_index','1'); $this->display("shop/enter/setting.php"); } public function setting_password(){ $this->assign('title','设置-极旅'); $this->assign('nav_index','5'); $this->assign('sub_nav_index','2'); $this->display("shop/enter/setting_password.php"); } }<file_sep>/1/protected/config/cms.php <?php if(IN_QCLOUD == 'true'){ $config['app_id'] = '85'; $config['app_secret'] = '<KEY>'; $config['user_domain'] = 'http://m.mty5.com'; $config['wx_api_domain'] = "wx.mty5.com"; $config['market_id'] = '24'; }else { $config['app_id'] = '51'; $config['app_secret'] = 'efca4eb89432d23696458ad132d43fc8'; $config['user_domain'] = 'http://m.mty365.com'; $config['wx_api_domain'] = "wx.mty365.com"; $config['market_id'] = '23'; $config['market_url'] = 'http://www.mty365.com'; } if(isset($_SERVER['HTTP_X_C_HOST']) && $_SERVER['HTTP_X_C_HOST']){ $config['user_domain'] = "http://{$_SERVER['HTTP_X_C_HOST']}"; $config['wx_api_domain'] = "{$_SERVER['HTTP_X_C_HOST']}"; } if(isset($_SERVER['HTTP_X_WC_HOST']) && $_SERVER['HTTP_X_WC_HOST']){ $config['wx_api_domain'] = "{$_SERVER['HTTP_X_WC_HOST']}"; } $config['api_route'] = 'http://api.zaol.cn/api/route'; $config['weibo_app_id'] = '64'; $config['weibo_app_secret'] = '<KEY>'; <file_sep>/1/protected/view/shop/product/product_add_base.php <?php V ('shop/shop_common_head.php');?> <?php $width = "400px"; $must = "<span class='red'>*</span>"; $product_info = $product_one; ?> <style> #base_info{padding-left:0px;} #base_info .control-label{font-weight:normal;} #base_info h4{border-bottom:1px solid #ccc;font-weight: bold;width: 80%;padding-bottom: 10px; } #base_info .red{color:red;font-weight:bold;padding-right: 2px;vertical-align: middle;font-size: 1.3em;} #base_info img{max-width:220px;max-height:200px;overflow:hidden;margin:5px;} #base_info .del{cursor:pointer;} </style> <ol class="breadcrumb"> <li><a href="/shop/product">活动管理</a></li> <li class="active"><?=$product_info['id'] ? '修改活动':'新增活动'?></li> </ol> <?php if ($product_info['id']){ include 'product_alert.php'; } ?> <?php if (!$product_info['id']){ ?> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: 33%"> 填写基本信息 </div> <div class="progress-bar progress-bar-warning" style="width: 34%"> 填写可售产品 </div> <div class="progress-bar progress-bar-warning" style="width: 33%"> 完成 </div> </div> <?php } ?> <div class="form-horizontal" role="form" id="base_info"> <h4>1.基本信息</h4> <input name="id" type="hidden" value="<?=$product_info['id']?>"> <?php if ($product_info){?> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">活动编号</label> <div class="col-sm-10"> <p class="form-control-static"><strong><?=$product_info['id']?></strong></p> </div> </div> <?php }?> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>活动名称</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="name" value="<?=$product_info['name']?>" placeholder="名称" style="width:<?=$width?>;" check-type="required" required-message="名称不能为空!"> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>活动介绍</label> <div class="col-sm-10 controls"> <textarea name="description" class="form-control" check-type="required" required-message="介绍不能为空!" style="width:<?=$width?>;min-height:100px;"><?=$product_info['description']?></textarea> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>分类选择</label> <div class="col-sm-10" style="padding-left: 30px;"> <div class="form-group"> <select name="type_select" class="form-control" style="width:300px;"> <option value="-1">--大类--</option> <?php foreach ($travel_type as $type){?> <option value="<?=$type['id']?>" <?=$type['id'] == $product_info['type_select'] ? "selected='selected'":''?>><?=$type['name']?></option> <?php }?> </select> </div> <div class="form-group"> <select name="topic_select" class="form-control" style="width:300px;"> <option value="-1">--中类--</option> <?php foreach ($travel_topic as $topic){?> <option value="<?=$topic['id']?>" <?=$topic['id'] == $product_info['topic_select'] ? "selected='selected'":''?>><?=$topic['name']?></option> <?php }?> </select> </div> <div class="form-group"> <select name="detail_select" class="form-control" style="width:300px;"> <option value="-1">--小类--</option> <?php foreach ($travel_category as $category){?> <option value="<?=$category['id']?>" <?=$category['id'] == $product_info['detail_select'] ? "selected='selected'":''?>><?=$category['name']?></option> <?php }?> </select> </div> </div> </div> <div class="form-group "> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>城市</label> <div class="col-sm-10 controls" style="padding-left: 30px;"> <div class="form-group address_p rel control-group"> <select id="continent" name="continent" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="3"> <option value="-1">--洲--</option> </select> </div> <div class="form-group address_p rel"> <select id="country" name="country" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="4"> <option value="-1">--国家--</option> </select> </div> <div class="form-group address_p rel"> <select id="city" name="city" check-type="required" class=" form-control" style="max-width: 300px;" tabindex="5"> <option value="-1">--城市--</option> </select> </div> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>地址</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" value="<?=$product_info['address']?>" name="address" placeholder="地址" style="width:<?=$width?>;" check-type="required" required-message="地址不能为空!"> </div> </div> <div class="form-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>支持语言</label> <div class="control col-sm-10 languange"> <?php foreach ($lan as $l){?> <label class="checkbox-inline"> <input type="checkbox" name="lan" value="<?=$l?>" <?=strpos("select".$product_info['language'],$l) ? "checked=checked":''?>> <?=$l?> </label> <?php }?> </div > </div > <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>如何抵达</label> <div class="col-sm-10 controls"> <textarea name="arrive_way" class="form-control" style="width:340px;min-height:100px;" check-type="required"><?=$product_info['arrive_way']?></textarea> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>温馨提示</label> <div class="col-sm-10 controls"> <textarea name="tips" class="form-control" style="width:340px;min-height:100px;" check-type="required"><?=$product_info['tips']?></textarea> </div> </div> <div class="form-group up-pic"> <label for="input<PASSWORD>" class="col-sm-2 control-label"><?=$must?>图片列表</label> <div class="col-sm-10"> <input type="file" name="file" style="width:<?=$width?>;" class="product_pic"> <input type="hidden" name="pic_list" value="<?=$product_info['pic_list']?>"> </div> </div> <div class="form-group"> <lable class="col-sm-2 control-label"></lable> <div id="pic_list" class="col-sm-10"> <?php if ($product_info['pic_list']){ $pic_array = explode(";",$product_info['pic_list']); foreach ($pic_array as $pic){?> <div class="item"> <img src="<?=$pic?>!190"> <input type='hidden' name='img' value='<?=$pic?>'> <span class="del"> <i class='icon-remove-sign' style='font-size:2em;'></i></span> </div> <?php } } ?> </div> </div> <div class="mt50" style="text-align:center"> <input type="button" class="btn btn-primary btn-lg" id="to_act_second" value="下一步"> </div> </div><!-- form-horizontal --> <!-- 此部分为加载分类 --> <script> var PRODUCT_ID = "<?=$_REQUEST['id']?>"; $("[name=type_select]").change(function(e){ load_trvale_topic(e.currentTarget); }) function load_trvale_topic(e){ var type_id = $(e).find("option:selected").val(); $.get("/shop/product_travel_topic",{type_id:type_id}, function(r){ if(r.status == 'ok' && r.data){ var $_topic = $("[name=topic_select]"); $_topic.empty(); $_topic.append("<option value='-1'>--中类--</option>"); $.each(r.data,function(i,item){ $_topic.append("<option value='"+item.id+"'>"+item.name+"</option>"); }) } },'json') } $("[name=topic_select]").change(function(e){ load_travle_cateory(e.currentTarget); }) function load_travle_cateory(e){ var topic_id = $(e).find("option:selected").val(); $.get("/shop/product_travel_category",{topic_id:topic_id}, function(r){ if(r.status == 'ok' && r.data){ var $_detail = $("[name=detail_select]"); $_detail.empty(); $_detail.append("<option value='-1'>--小类--</option>"); $.each(r.data,function(i,item){ $_detail.append("<option value='"+item.id+"'>"+item.name+"</option>"); }) } },'json') } </script> <!-- 此部分为js加载地区控件 --> <script src="<?=$THEME_URL?>/js/continent.js"></script> <script> //几大洲长度 var a_l=continents.length; var continent = document.getElementById("continent"); var country = document.getElementById("country"); var city = document.getElementById("city"); for_add(continent,continents,a_l); continent.addEventListener("change",function(){ var that = this; var _index = that.selectedIndex; country.length = 1; city.length = 1; if(_index != 0){ that.setAttribute("data-continent-id",continents[_index-1]); var children_l = continents[_index-1]["countries"].length; for_add(country,continents[_index-1]["countries"],children_l); } },false) country.addEventListener("change",function(){ var _parent_index = continent.selectedIndex; var that = this; var _index = that.selectedIndex; city.length = 1; if(_index != 0){ that.setAttribute("data-country-id",continents[_parent_index-1]["countries"][_index-1]); var children_l = continents[_parent_index-1]["countries"][_index-1]["cities"].length; for_add(city,continents[_parent_index-1]["countries"][_index-1]["cities"],children_l); } },false) city.addEventListener("change",function(){ var _parent_index = continent.selectedIndex; var _country_index = country.selectedIndex; var that = this; var _index = that.selectedIndex; if(_index != 0){ that.setAttribute("data-city-id",continents[_parent_index-1]["countries"][_country_index-1]["cities"][_index-1]); } },false) function for_add(obj,arr,l){ for(var i = 0; i < l; i++){ var newOption = new Option(arr[i].name,i); obj.add(newOption,undefined); } } </script> <!-- 此部分为根据数据库里的地址显示到界面上 --> <script> <?php if ($product_info){?> render_continents("<?=$product_info['continent']?>","<?=$product_info['country']?>","<?=$product_info['city']?>"); <?php }?> function render_continents(param1,param2,param3){ var CURRENT = { continent : param1, country : param2, city : param3, }; //注册 continent var c = continents; var i = register(c,$("#continent"),CURRENT.continent); for_add(country,c[i].countries,c[i].countries.length); //注册coutry var t = c[i].countries; var j = register(t,$("#country"),CURRENT.country); for_add(city,t[j].cities,t[j].cities.length); //注册city var y = t[j].cities; var h = register(y,$("#city"),CURRENT.city); } function register(obj,$_new,current){ for(var $i=0;$i<obj.length;$i++){ if (obj[$i].name == current){ $_new.find("option").each(function($j,item){ if($(item).text() == obj[$i].name){ item.selected=true; } }) return $i; } } } </script> <script> //图片删除 $("#pic_list").delegate(".del","click",function(){ $(this).parent('.item').remove(); }) //基本验证 function check_start(){ var select = new Array(); select.push($("[name=type_select]")); select.push($("[name=topic_select]")); select.push($("[name=detail_select]")); select.push($("[name=continent]")); select.push($("[name=country]")); select.push($("[name=city]")); var sel_falg = false; $.each(select,function(i,item){ if($(item).find("option:selected").val()=='-1'){ $(item).css("border","1px solid #b94a48"); sel_falg = true; } }) var checkbox = $("[name=lan]"); var temp = true; for(var i=0;i<checkbox.length;i++){ if($(checkbox[i]).prop("checked")){ temp = false; } } var err = ""; if(temp){ err = "<span style='color:#b94a48'>请选择支持语言</span>"; $(".languange").append(err); } var pic_flag = false; if($("#pic_list .item").length ===0){ pic_flag = true; err = "<span style='color:#b94a48'>请上传产品图片!</span>"; $("[name=pic_list]").after(err); } var base_falg = false; if(!$("#base_info").validation()){ base_falg = true; } if(sel_falg || temp || pic_flag || base_falg){ return false; } return true; } </script> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/protected/action/AdminMemberAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 管理员后台 游客管理 * @author lili * */ class AdminMemberAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_admin_auth($this, true); $this->assign("js_group","admin"); if($this->admin_user['role_id'] != 2 && $this->admin_user['role_id'] != 4){ $this->no_admin(); exit(); } Configure::load('cms'); $cms = Configure::getItems('cms'); $this->load_helper('TaoDian'); $this->api = new TaoDian($cms['app_id'],$cms['app_secret']); $this->assign('nav_main', "member"); } public function index(){ $this->display("admin/member/user_list.php"); } } ?><file_sep>/1/protected/view/shop/order/order_list.php <?php V('shop/header.php');?> <?php $sex_array = array('1'=>'男','2'=>'女'); $status = array(0=>'未审核',1=>'审核通过'); ?> <div class = "col-lg-12"> <div class = "col-lg-1 col-md-1 sidebar-nav"> <?php V('shop/order/order_left_nav.php');?> </div > <div class = "col-lg-11 col-md-11 hd" style="padding-left: 30px;"> 订单管理开发中 </div> </div> <?php V('shop/footer.php');?><file_sep>/1/protected/view/product/product_detail_info.php <div class="product_info"> <ul class="nav nav-tabs" id="mytab"> <li class="active"><a href="#detail" data-toggle="tab">详细信息</a></li> <li><a href="#user_discuss" data-toggle="tab">顾客讨论</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="detail"> <div> <?=$item['description']?> </div> </div> <div class="tab-pane fade" id="user_discuss"> <div> 用户讨论信息 </div> </div> <script> $('#myTab a').click(function (e) { e.preventDefault() $(this).tab('show') }) </script> </div> </div><file_sep>/1/protected/hooks/AppHook.class.php <?php defined('YUNPHP') or exit('can not access!'); define('USER_KEY', "emop_client_uid"); class AppHook extends Hook{ public function __construct(){ parent::__construct(); $this->menu_nav = array(); } public function start_request($action){ $host_url = host_url(); $action->assign("THEME_URL", "{$host_url}/static"); $action->assign("BASE_URL", "{$host_url}"); } public function check_shop_auth($action,$force_login=false){ session_start_new(); if ($_SESSION['shop']['id']>0){ $action->assign("nick",$_SESSION['shop']['name']); $action->assign("shop",$_SESSION['shop']); $action->shop = $_SESSION['shop']; }elseif ($force_login){ $_SESSION['LOGIN_OK_NEXT'] = $_SERVER['REQUEST_URI']; header("location: /user/login"); exit(); } } public function check_admin_auth($action,$force_login=false){ session_start_new(); if ($_SESSION['shop']['id']>0 && $_SESSION['shop']['is_admin'] == 1){ $action->admin_user = $_SESSION['shop']; $action->admin_user['user_nick'] = $action->admin_user['name']; $action->admin_user['role_id'] = 2; $action->assign("admin_user", $action->admin_user); /* $action->assign("nick",$_SESSION['shop']['name']); $action->assign("shop",$_SESSION['shop']); $action->shop = $_SESSION['shop']; */ }elseif ($force_login){ $_SESSION['LOGIN_OK_NEXT'] = $_SERVER['REQUEST_URI']; header("location: /user/login"); exit(); } } public function check_admin_auth_emop($action){ session_start_new(); if($_SESSION['admin_uid_token']){ Configure::load('cms'); $cms = Configure::getItems('cms'); $this->load_helper('TaoDian'); $this->emop = new TaoDian($cms['app_id'], $cms['app_secret']); $u = $this->emop->emop_user_profile(array(access_token=>$_SESSION['admin_uid_token']), 10, true); if($u['status'] == 'err'){ $u = $this->emop->emop_user_profile(array(access_token=>$_SESSION['admin_uid_token']), 0, true); } if($u['status'] == 'ok'){ $action->admin_user = $u['data']; $action->assign("admin_user", $action->admin_user); }else { $_SESSION['LOGIN_OK_NEXT'] = $_SERVER['REQUEST_URI']; header("location: /user/admin_login"); exit(); } }else { $_SESSION['LOGIN_OK_NEXT'] = $_SERVER['REQUEST_URI']; header("location: /user/admin_login"); exit(); } } } ?><file_sep>/1/protected/action/ProductAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 前端,产品展示 * @author deonwu * */ class ProductAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); } public function item_view($pid){ $m = new ProductModel(); $p = $m->get_product($pid); if($p['shop_id'] > 0 && $p['verify_status'] == 1){ $this->assign("item", $p); $this->display("product/product_item.php"); }else if($p['shop_id'] > 0 && $p['verify_status'] != 1){ $this->no_sale(); }else { $this->not_found(); } } public function preview($pid){ $m = new ProductModel(); $p = $m->get_product($pid); $this->app->check_shop_auth($this, true); if($p['shop_id'] == $this->shop['shop_id'] || $_SESSION['admin_user_id'] > 0){ $this->assign("item", $p); $this->display("product/product_item.php"); }else { $this->not_found(); } } public function not_found(){ echo "没有找到商品"; } public function no_sale(){ echo "商品不在销售中"; } public function load_price_item($iid){ $m = new ProductModel(); $p = $m->get_product_price_item($iid); if($p['shop_id'] > 0){ $this->assign("item", $p); $this->display("product/product_price_item.php"); }else { $this->not_found_price(); } } public function not_found_price(){ echo "没有找到价格详情"; } public function load_calendar(){ $this->load_helper("Calender"); $this->load_helper("CalenderRenders"); $c = new Calendar(); $c->weeks = $c->weeks2; $start = $_REQUEST['start']; if(strlen($start) >= 7){ $c->year = substr($start, 0, 4); $c->month = substr($start, 5,2); }else { $c->year = date('Y'); $c->month = date('m'); } $m = new ShopModel(); $item_id = $_REQUEST['item_id']; $s = "{$c->year}{$c->month}00"; $e = "{$c->year}{$c->month}32"; $sql = <<<SQL select * from shop_product_price_detail where item_id='{$item_id}' and price_date >= {$s} and price_date <= {$e} SQL; $data = $m->db->getData($sql); if(DEBUG){ echo "sql:{$sql}, data:" . var_export($data); } $c->render = new UserRender($data); $this->assign("c", $c); $this->display("product/calender.php"); } //p } ?><file_sep>/1/protected/errors/debug_error.php <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><?php echo $title ?>></title> </head> <body> <h1>网站宕机了,管理员快回家吃饭!</h1> <div style=" background: #f7f7f7; border:#ddd; padding:15px;"> <?php echo $message.' '.$file.' on line '.$line."<br/>"; ?> </div> </body> </html><file_sep>/1/protected/view/cate/item_list_row.php <?php foreach($item_list as $item) {?> <div class="item clearfix"> <div class = "col-lg-12 col-md-12"> <div class = "col-lg-9 col-md-9"> <h4><?=$item['name']?></h4> <div class="product"> <div class="pic pull-left"> <a href="/i/<?=$item['id']?><?=HTML_VIEW ? ".html" : "" ?>"> <img src="<?=$item['imgs'][0]?>" /> </a> </div> <div class="product_info"> <div><label>简介:</label><span><?=$item['short_description']?></span></div> <div><label>城市:</label><span><?=$item['city']?></span></div> <!-- <div><label>活动:</label><span>xx</span></div> --> <div><label>语言:</label><span><?=$item['language']?></span></div> </div> </div> <div class='shop'>商家: <?=$item['shop_name']?></div> </div > <div class = "col-lg-3 col-md-3" style="background:#eeeeee;height:160px;"> <div> 低值: <?=$item['min_price']?> 元 </div> <a class="btn btn-success" href="/i/<?=$item['id']?><?=HTML_VIEW ? ".html" : "" ?>">查看详情</a> </div > </div> </div> <?php }?><file_sep>/1/protected/helper/Mail.class.php <?php class Mail{ private $smtp_user = "<EMAIL>"; private $smtp_pass = "<PASSWORD>"; private $smtp_host = "smtp.exmail.qq.com"; private $smtp_port = "465"; private $smtp_tls = false; private $content_type = "TEXT"; public function __construct(){ $this->mail = new SaeMail(); } public function sendMail($subject, $content, $tos){ $config ['smtp_password'] = $this->smtp_pass; $config ['smtp_username'] = $this->smtp_user; $config ['smtp_host'] = $this->smtp_host; $config ['smtp_port'] = $this->smtp_port; $config["subject"] = $subject; $config ['charset'] = "utf-8"; $config ['content_type'] = $this->content_type; $config ['to'] = $tos; $config["content"] = $content; $config["from"]="<EMAIL>"; $this->mail->setOpt($config); $ret = $this->mail->send(); $this->mail->clean(); if($ret){ return true; }else{ var_dump($this->mail->errno(), $this->mail->errmsg()); return false; } } public function setContentType($content_type){ $this->content_type = $content_type; } }<file_sep>/1/protected/view/product/nav_bar.php <div class="well well-lg"> <a class="btn btn-success" href="#" onclick="window.scrollTo(0, $('._journeys').offset().top); return false;">立即预订</a> <div class="overall-price"><em>RMB</em><span>¥111</span></div><div class="price-expla">(每人) </div> </div> <div class="box"> <a href="">咨询该活动</a> </div> <div class="box"> <h4>我们的承诺</h4> <div>服务商家资质认证</div> <div>底价承诺品质保证</div> <div>活动透明,明明白白消费</div> </div> <div class="box"> <h4>服务商家</h4> <div><?=$item['shop']['shop_name']?></div> </div> <div class="panel"> <div class="panel-heading">最近浏览</div> </div> <file_sep>/1/protected/view/admin/shop/shop_list.php <?php V ('admin/header.php');?> <?php $sex_array = array('1'=>'男','2'=>'女'); $status = array(0=>'未审核',1=>'审核通过',2=>'已驳回'); $subject_array = array('个体','企业','机构','组织','旅行社'); ?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V ('admin/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10 "> <h3>查询商家</h3> <form action="?" method="get"> 商家名称: <input id="shop_name" name="shop_name" value="<?=$_REQUEST['shop_name']?>" placeholder="例如:淘点科技"> 运营主体: <select name="subject"> <option value="">全部</option> <?php foreach ($subject_array as $subject){?> <option value="<?=$subject?>" <?=$subject == $_REQUEST['subject'] ? "selected='selected'":''?>><?=$subject?></option> <?php }?> </select> 审核状态 : <select name="verify_status"> <option value="">全部</option> <?php foreach ($status as $k=>$s){?> <option value="<?=$k?>" <?=$_REQUEST['verify_status'] === "$k" ? "selected='selected'":""?>><?=$s?></option> <?php }?> </select> <input type="submit" name="" value="查询"> </form> <h3>商家列表</h3> <div id="shop_list"> <table class="table" width="100%"> <tbody> <tr> <th>商家ID</th> <th>运营主体</th> <th>商家名称</th> <th>名字</th> <th>性别</th> <th>身份认证</th> <th>工商注册名称</th> <th>所在地</th> <th>营业执照</th> <th>电话</th> <th>LOGO</th> <th>提交时间</th> <th>状态</th> <th>操作</th> </tr> <?php foreach ($data as $shop){?> <tr> <td><?=$shop['shop_id']?></td> <td><?=$shop['subject']?></td> <td><span style='color:blue'><?=$shop['shop_name']?></span></td> <td><?=$shop['surname'].$shop['forename']?></td> <td><?=$sex_array[$shop['sex']]?></td> <td><a href="<?=$shop['authentication']?>" target="_blank">点击查看</a></td> <td><?=$shop['registration_name']?></td> <td> <?=$shop['continent']?><br/> <?=$shop['country']?><br/> <?=$shop['city']?><br/> <?=$shop['address']?> </td> <td><a href="<?=$shop['license']?>" target="_blank">点击查看</a></td> <td><?=$shop['tel']?></td> <td><a href="<?=$shop['logo']?>" target="_blank">点击查看</a></td> <td> <?=$shop['create_time'] ?> </td> <td><?=$status[$shop['verify_status']]?></td> <td> <?php if (!$shop['verify_status']){?> <a class="verify btn btn-info" shop_id="<?=$shop['shop_id']?>">通过</a> <a href="/admin/shop_refund/<?=$shop['shop_id']?>" class="btn btn-danger">驳回</a> <?php }elseif ($shop['verify_status'] == 2){?> <a href="/admin/shop_refund/<?=$shop['shop_id']?>" class="btn btn-default">查看</a> <?php }?> </td> </tr> <?php }?> </tbody> </table> <div class="page"><?=$page?></div> </div> </div> </div> <script> //审核通过 $("#shop_list").delegate(".verify","click",function(){ var that = this; var post_data = {}; post_data.shop_id = $(this).attr("shop_id"); post_data.verify_status = 1; $.post("/admin/shop_pass_save",post_data, function(r){ if(r.status == 'ok'){ location.href="/admin/shop_list"; } },'json') }) </script> <?php V ('admin/footer.php');?><file_sep>/1/protected/view/shop/product/price_table.php <div class="form-group"> <label for="<PASSWORD>" class="col-sm-2 control-label"><?=$must?>活动报价</label> <div class="col-sm-10"> <ul class="nav nav-tabs" id="mytab"> <li class="active"><a href="#lot" data-toggle="tab">批量添加价格</a></li> <li><a href="#appoint" data-toggle="tab">添加指定时间段价格</a></li> <li><a href="#quick" data-toggle="tab">快速编辑模式</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="lot"> <?php include 'price_table_lot.php';?> </div> <div class="tab-pane fade" id="appoint"> <?php include 'price_table_appoint.php';?> </div> <div class="tab-pane fade" id="quick"> <?php include 'price_table_quick.php';?> </div> </div> </div> </div> <script> $('#myTab a').click(function (e) { e.preventDefault() $(this).tab('show') }) </script><file_sep>/1/protected/helper/CalenderRenders.class.php <?php class SimpleRender{ private $data; public function __construct($data){ $this->data = array(); // $data; foreach($data as $row){ $this->data[$row['price_date']] = $row; } } /** * 展示一天的价格。 * @param unknown_type $d */ public function show($d){ $r = $d['n_date']; $row = $this->data[$r]; if(!$row){ $row['adult_price'] = 0; $row['child_price'] = 0; $row['inventory'] = 0; } $view = <<<END <div class='c' date='{$d['date']}'> <div class='day'>{$d['day']}</div> <div class='adult_price'><label>成人:</label><span>{$row['adult_price']}</span></div> <div class='child_price'><label>儿童:</label><span>{$row['child_price']}</span></div> <div class='inventory'><label>数量:</label><span>{$row['inventory']}</span></div> </div> END; return $view; } } class UserRender{ private $data; public function __construct($data){ $this->data = array(); // $data; foreach($data as $row){ $this->data[$row['price_date']] = $row; } } /** * 展示一天的价格。 * @param unknown_type $d */ public function show($d){ $r = $d['n_date']; $row = $this->data[$r]; if(!$row){ $row['adult_price'] = 0; $row['child_price'] = 0; $row['inventory'] = 0; } //<div class='adult_price'><label>成人:</label><span>{$row['adult_price']}</span></div> //<div class='child_price'><label>儿童:</label><span>{$row['child_price']}</span></div> //<div class='inventory'><label>数量:</label><span>{$row['inventory']}</span></div> $has = $row['inventory'] > 0 ? 'remain' : ''; $view = <<<END <div class='c {$has}' date='{$d['date']}'> <div class='day' adult='{$row['adult_price']}' child='{$row['child_price']}' remain='{$row['inventory']}' >{$d['day']}</div> </div> END; return $view; } } ?><file_sep>/1/YunPHP/lib/Log.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class Log { public static $log_place =''; public static $log_table = ''; public static $log_write_level = ''; public static $level = array(); /** * 打日志的函数,静态函数,可以直接调用 * system app debug * @param unknown_type $level * @param unknown_type $message */ public static function write_log($level='ERROR',$message){ self::$level = array('ERROR' => '1', 'INFO' => '2', 'DEBUG' => '3', 'ALL' => '4'); self::$log_write_level = Configure::getItem('log_write_level','config'); if(self::$log_write_level >= self::$level[$level]){ self::$log_place = Configure::getItem('log_place','config'); if(self::$log_place == 'sae'){ sae_debug("$message"); }else if (self::$log_place == 'mysql'){ self::$log_table = Configure::getItem('log_table','config'); $log_time = date('Y-m-d H:i:s'); $log_table = self::$log_table; import_class('Db'); $db = new Db(); $sql = "INSERT INTO `$log_table` (`id` ,`level` ,`log_time` ,`msg`)VALUES (NULL , '$level', '$log_time', '$message')"; if($db->run_sql($sql)){ return true; }else{ throw new Exception("Log ==>can't write log in mysql,please create a table <b>self::$log_table</b> in your database !"); } }else{ throw new Exception("Log ==>".self::$log_place."can only be 'sae' or 'mysql'!"); } }else{ return false; } } /** * 显示日志 */ public static function show_log(){ $log_table = Configure::getItem('log_table'); $sql = "select * from $log_table order by id desc"; import_class('Db'); $db = new Db(); $data = $db->get_data($sql); $i = 1; foreach ($data as $val) { echo $val['id'].' '.$val['level'].' '.$val['log_time'].' '.$val['msg']."<br/>"; if($i%5 == 0){ echo "<hr style='color:#f7f7f7;margin:10px;'/>"; } $i++; } } } ?><file_sep>/1/YunPHP/lib/Db.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class Db extends SaeMysql { public function __construct($do_replicaton=true){ parent::__construct(false); } /** * 通过主键获取数据 * * @param unknown_type $table * @param unknown_type $id * @return unknown */ public function getById($table,$id){ if($table == ''|| $id == ''){ if(DEBUG){ throw new Exception("Error == > Parameter Error!"); } @Log::write_log('ERROR',"Table $table is empty or $id is null"); return false; } $sql = "select * from $table where id = $id"; $res = $this->get_line($sql); return $res; } /** * 删除单条记录 * * @param 表名 $table * @param 主键 $id * @return */ public function delById($table,$id){ if($table == ''|| $id == ''){ if(DEBUG){ throw new Exception("Error ==> Parameter Error!"); } @Log::write_log('ERROR',"Table $table not empty or $id is null"); return false; } $sql = "delete from $table where id = $id"; $this->run_sql($sql); if($this->errno() != 0){ if(DEBUG){ throw new Exception("Sql Error ==> $sql"); } @Log::write_log("Sql Error ==> $sql "); return false; }else{ return true; } } /** * 插入一条数据 * * @param 表名 $table * @param 要插入的数组 $data * @return unknown */ public function insertData($table, $data=array(), $debug=false){ if($table == '' || !is_array($data)){ if(DEBUG){ throw new Exception("Error ==> Paramter Error!"); } @Log::write_log('ERROR',"Parameter error!"); return false; } $keys = ''; $values = ''; foreach ($data as $k => $v){ $keys .=" `$k` ,"; if(strpos($k, "_time") && is_numeric($v) && !strpos($k,"_times")){ #;$k == 'update_time' $values .= " FROM_UNIXTIME($v) ,"; }else if("{$v}" == 'timestamp'){ $values .= " UNIX_TIMESTAMP() ,"; }else { $values .= " '$v' ,"; } } $keys = substr($keys,0,-1); $values = substr($values,0,-1); $sql = "INSERT INTO `$table` ($keys) VALUES ($values)"; if(DEBUG || $_REQUEST['state'] == 'test'|| $debug){ //var_dump(""$sql); echo "sql:" . $sql; } $this->run_sql($sql); $errno = $this->errno(); if($errno != 0){ if(DEBUG){ throw new Exception("error:($errno)" . $this->error () . "\nSql Error ==> $sql"); } @Log::write_log("Sql Error == >$sql"); return false; }else{ return true; } } /** * 插入一条数据 * * @param 表名 $table * @param 要插入的数组 $data * @return unknown */ public function insertOrUpdate($table, $data = array(), $ignore = array(), $extra='') { if ($table == '' || ! is_array ( $data )) { if (DEBUG) { throw new Exception ( "Error ==> Paramter Error!" ); } @Log::write_log ( 'ERROR', "Parameter error!" ); return false; } $keys = ''; $values = ''; $fields = array (); foreach ( $data as $k => $v ) { $keys .= " `$k` ,"; if (strpos ( $k, "_time" ) && is_numeric($v)) { // $k == 'update_time' $values .= " FROM_UNIXTIME($v) ,"; } else { $values .= " '$v' ,"; } if (! in_array ( $k, $ignore )) { $fields [] = "`$k` = VALUES(`$k`)"; } } $keys = substr ( $keys, 0, - 1 ); $values = substr ( $values, 0, - 1 ); $sql = "INSERT INTO `$table` ($keys) VALUES ($values)"; $sql = $sql . " ON DUPLICATE KEY UPDATE " . join ( ",", $fields ) . $extra; $this->run_sql ( $sql ); if(DEBUG){ echo "sql=>$sql\n"; } if ($this->errno () != 0) { if (DEBUG ) { throw new Exception ( "Sql Error ==> $sql" . " error:" . $this->errmsg () ); } @Log::write_log ( "Sql Error == >$sql" ); return false; } else { $last_id = $this->lastId (); return $last_id > 0 ? $last_id : 1; } } public function updateData($table,$data,$condition = ''){ if($table == '' || !is_array($data)){ if(DEBUG){ throw new Exception("Error ==> Paramter Error!"); } @Log::write_log('ERROR',"$table $data Parameter error!"); return false; } $str = ''; foreach ($data as $k => $v) { if(strpos($k, "_time") && is_numeric($v) && !strpos($k,"_times")){ #;$k == 'update_time' $str .= " `$k` = FROM_UNIXTIME($v),"; }else { $str .= " `$k` = '$v',"; } } $str = substr($str,0,-1); if($condition != ''){ $str .= "WHERE $condition"; } $sql = "UPDATE $table SET $str"; $this->run_sql($sql); if(DEBUG || $_REQUEST['state'] == 'test'){ echo "sql: $sql \n"; } if($this->errno() != 0){ if(DEBUG){ throw new Exception("Sql Error ==> $sql"); } @Log::write_log('ERROR',"Sql Error ==> $sql"); return false; }else{ return true; } } /** * 删除记录 * * @param unknown_type $table * @param unknown_type $condition * @return unknown */ public function deleteData($table,$condition){ if($table == '' ||$condition == ''){ if(DEBUG){ throw new Exception("Error ==> Paramter Error!"); } @Log::write_log('ERROR',"$table $data Parameter error!"); return false; } $sql = "delete from $table WHERE $condition"; $this->run_sql($sql); if($this->errno() != 0 ){ if(DEBUG){ throw new Exception("Sql Error ==>$sql"); } @Log::write_log('ERROR',"Sql Error ==> $sql"); return false; }else{ return true; } } /** * 读取数据 * * @param unknown_type $table * @param unknown_type $condition */ public function selectData($table,$condition=''){ if($table == ''){ @Log::write_log('ERROR',"$table $data Parameter error!"); return false; } $sql = "select * from $table "; if($condition !=''){ $sql .= " WHERE $condition"; } $res = $this->get_data($sql); if($this->errno() != 0){ @Log::write_log('ERROR',"Sql Error ==>$sql"); return false; }else{ return $res; } } public function __destruct(){ $this->close_db(); } } ?><file_sep>/1/protected/view/shop/product/product_list.php <?php V ('shop/shop_common_head.php');?> <style> .panel-heading{height:42px;border-bottom:none;padding-top: 2px;padding-left: 10px;} #product_list ul li{border:1px solid #ccc;border-bottom:none;width: 120px;text-align: center;margin-right: 10px;height:40px;} #product_list ul li.active{background-color:white;} #product_list ul li.active a{background-color:#f5f5f5;font-size:14px;} #product_list ul li a{width:70%;height:26px;margin:8px auto;padding-top:5px;font-size:16px;font-weight:bold;color:#494444; } </style> <div class="panel panel-default" id="product_list"> <div class="panel-heading"> <h4>已发布活动列表</h4> <a class="btn btn-default pull-right" href="/shop/product_add" style="margin-bottom: 10px;"> <i class="icon-plus"></i> 新增活动 </a> </div> <div class="panel-body"> <table class="table table-bordered box-content"> <thead> <tr> <th>产品ID</th> <th>图片</th> <th>产品名称</th> <th>地址</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <?php foreach($product_list as $t) {?> <tr> <td><?=$t['id']?> </td> <td><?php $p = explode(";", $t['pic_list']); echo "<img src='{$p[0]}!190' />"; ?> </td> <td><a href="/i/<?=$t['id']?>" target="_blank"><?=$t['name']?></a></td> <td><?=$t['city']?>, <?=$t['address']?></td> <td> <?php if (!$t['verify_status']){ echo "审核中"; }elseif ($t['verify_status'] === '2'){ echo "已驳回, 点击【修改】查看"; }elseif ($t['verify_status'] === '1'){ echo "已发布"; } ?></td> <td> <a href="/shop/product_add?id=<?=$t['id']?>">修改</a> &nbsp;&nbsp;<a href="/shop/price_list?pid=<?=$t['id']?>">价格类型</a> &nbsp;&nbsp;<a href="javascript:;" class="del" pid="<?=$t['id']?>">删除</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- panel --> <script src="<?=$THEME_URL ?>/js/app_dailog.js"></script> <script> $("#product_list").delegate(".del","click",function(e){ $.show_confirm("该删除操作不可恢复,您确定删除吗?",function(){ var pid = $(e.currentTarget).attr('pid'); $.post("/shop/product_remove",{pid:pid}, function(r){ if(r.status == 'ok'){ $(e.currentTarget).parent().parent().fadeOut(); }else{ $.show_error('删除出错!'+r.msg); } },'json') }) }) </script> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/protected/view/product/calender.php <h4> <a class="btn btn-default pull-left prev" href="#" month="<?=$c->preMonth() ?>"><i class="icon-angle-left"></i></a> <span><?=$c->year . "-" . $c->month ?></span> <a class="btn btn-default pull-right next" href="#" month="<?=$c->nextMonth() ?>"><i class="icon-angle-right"></i></a> </h4> <?php $c->display(); ?><file_sep>/1/protected/view/admin/front/home_page_tab_dest.php <div class="panel" > <div class=""> <a href="#" class="btn btn-primary" id="add_dest_filter">添加</a> </div> <table class='table' id="dest_list_table"> <tr> <th>ID</th> <th>图片</th> <th>名字</th> <th>搜索值</th> <th>操作</th> <th>上传人</th> <th>上传日期</th> </tr> <?php foreach($dest_list as $p){?> <tr pid='<?=$p['id'] ?>' view_order='<?=$p['view_order']?>' <?=$p['status'] == 1 ? 'class="success"' : '' ?>> <td><?=$p['id']?></td> <td> <a href="<?=$p['pic_url']?>" class='thumbnail' style='max-width:300px;'><img src="<?=$p['pic_url']?>"></a> </td> <td> <?=$p['cate_label']?> </td> <td> <?=$p['cate_value']?> </td> <td class='action' pid='<?=$p['id']?>'> <a href="#" class="edit btn btn-success">编辑</a> <?php if($p['status'] == 1){?> <a href="#" class="item_hide btn btn-success">暂停发布</a> <?php }else {?> <a href="#" class="item_show btn btn-success">发布</a> <?php } ?> <a href="#" class="remove btn btn-danger">删除</a> </td> <td><?=$p['name']?></td> <td><?=$p['create_time']?></td> </tr> <?php }?> </table> </div> <div class="modal fade" id="myDestEditor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">目的地</h4> </div> <div class="modal-body"> <form role="form"> <div class="form-group"> <label for="cate_label">名字</label> <input type="text" name='cate_label' class="form-control" id="cate_label" placeholder="前端展示名字"> </div> <div class="form-group"> <label for="cate_value">过滤条件</label> <input type="text" name='cate_value' class="form-control" id="cate_value" placeholder="内部使用的过滤条件,默认为空"> </div> <div class="form-group"> <label for="view_order">显示顺序</label> <input type="number" name='view_order' id="view_order" value="1"> <p class="help-block">值小的排在前面</p> </div> <div class="form-group"> <label for="upload_img">图片文件</label> <input type="file" id="upload_img" name='file'> <p class="help-block">前端显示图片</p> <img class='preview' src='' style='width:100px;' /> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消编辑</button> <button type="button" class="btn btn-primary save_btn">保存</button> </div> </div> </div> </div> <file_sep>/1/static/js/admin/home_page.js function save_home_page_file(url){ } $("#main_file").uploadfile({ bucket:'jilv-ad', return_url: 'http://'+window.location.host+'/api/upload_callback/jilv-ad', callback: function(data, file){ if(typeof(data) == 'object'){ if(data.code == '200'){ $.post("/adminFront/save_home_pic", data, function(d){ $.show_ok("文件保存成功,刷新页面后显示。"); }, 'json'); } } }}); $("#main_pic_table .action a").click(function(){ var active = 0; if($(this).hasClass("active")){ active = 1; }else if($(this).hasClass("remove")){ active = 9; } var row = $(this).parents('tr')[0]; $.post("/adminFront/update_home_pic", {'active': active, 'pid': $(this).parent().attr('pid')}, function(e){ $.show_ok("操作成功"); if(row && active == 9){ $(row).hide(); } }, 'json'); }); function CateFilterEditor(container, data_list, add_btn, settings){ var that = this; that.editor = $(container); that.settings = settings; $(add_btn).click(function(){ that.editor.modal('show'); }); $(data_list).on("click", ".action a", function(data){ var row = $($(this).parents('tr')[0]); var btn = $(this); if($(this).hasClass('edit')){ that.edit_item(row); }else if($(this).hasClass('item_show')){ $.post("/adminFront/update_cate_status", {'active': 1, 'pid':row.attr("pid")}, function(data){ if(data.status == 'ok'){ row.addClass("success"); btn.removeClass("item_show"); btn.removeClass("item_hide"); btn.text("暂停发布"); }else { $.show_err("数据操作错误"); } }, 'json'); }else if($(this).hasClass('item_hide')){ $.post("/adminFront/update_cate_status", {'active': 0, 'pid':row.attr("pid")}, function(data){ if(data.status == 'ok'){ row.removeClass("success"); btn.removeClass("item_hide"); btn.removeClass("item_show"); btn.text("发布"); }else { $.show_err("数据操作错误"); } }, 'json'); } else if($(this).hasClass('remove')){ $.post("/adminFront/update_cate_status", {'active': 9, 'pid':row.attr("pid")}, function(data){ if(data.status == 'ok'){ row.hide(); }else { $.show_err("数据操作错误"); } }, 'json'); } }); container.find("[name=file]").uploadfile({ bucket:'jilv1', return_url: 'http://'+window.location.host+'/api/upload_callback/jilv1', callback: function(data, file){ if(typeof(data) == 'object'){ if(data.code == '200'){ that.upload_file(data); } } }}); container.find(".save_btn").click(function(){ that.save_item(); }); } CateFilterEditor.prototype.add_new = function(){ this.cur_id = 0; this.editor.find("[name=cate_label]").val(); this.editor.find("[name=cate_value]").val(); this.editor.find("[name=view_order]").val('1'); this.editor.find(".preview").hide(); } CateFilterEditor.prototype.save_item = function(){ var param = {cate_label:this.editor.find("[name=cate_label]").val(), cate_value:this.editor.find("[name=cate_value]").val(), view_order:this.editor.find("[name=view_order]").val(), pic_url:this.editor.find(".preview").attr("src"), cid: this.cur_id }; param.page_view = this.settings.page_view; param.cate_type = this.settings.cate_type; var that = this; $.post("/adminFront/save_cate_filter", param, function(data){ //console.log(data); if(data.status == 'ok'){ that.editor.modal("hide"); $.show_ok("文件保存成功,刷新页面后显示。"); } }, 'json'); } CateFilterEditor.prototype.edit_item = function(row){ this.cur_id = row.attr("pid"); this.editor.modal('show'); this.editor.find("[name=cate_label]").val(row.find('td:eq(2)').text().trim()); this.editor.find("[name=cate_value]").val(row.find('td:eq(3)').text().trim()); this.editor.find("[name=view_order]").val(row.attr('view_order')); this.editor.find(".preview").attr("src", row.find('img').attr("src")); this.editor.find(".preview").show(); } CateFilterEditor.prototype.upload_file = function(data){ this.editor.find(".preview").attr("src", data.url); this.editor.find(".preview").show(); } var a = new CateFilterEditor($("#myDestEditor"), $("#dest_list_table"), $("#add_dest_filter"), {'page_view': 'home', 'cate_type': 'dest'}); var b = new CateFilterEditor($("#myTopicEditor"), $("#topic_list_table"), $("#add_topic_filter"), {'page_view': 'home', 'cate_type': 'product_type'}); <file_sep>/1/protected/view/shop/enter/setting_left_nav.php <ul class="nav nav-stacked left-menu"> <li <?php if($sub_nav_index == '1'){ echo 'class="active"'; }?> > <a href="/shopEnter/index"> <i class="icons-user-gray"></i> 个人资料 </a> </li> <li <?php if($sub_nav_index == '2'){ echo 'class="active"'; }?> > <a href="/shopEnter/setting_password"> <i class="icons-lock-gray"></i> 修改密码 </a> </li> <li <?php if($sub_nav_index == '3'){ echo 'class="active"'; }?> > <a href="icons-edit-gray"> <i class="icon-group"></i> 支付设置 </a> </li> </ul><file_sep>/1/protected/view/product/product_price_item.php <div class = "col-lg-12 col-md-12 price_detil clearfix"> <div class = "col-lg-6 col-md-6 hd text-left" > <div><i class="icon-calendar"></i> <label>提前预约:</label>至少提前<?=$item['advance_day'] ?>天</div> <div><i class="icon-money"></i> <label>费用说明:</label><?=$item['fee_descrip'] ?></div> <div><i class="icon-remove"></i> <label>退改说明:</label><?=$item['refund_rule'] ?></div> <div><label>其他说明:</label><?=$item['lightspot'] ?></div> </div> <div class = "col-lg-6 col-md-6 "> <div class="panel well"> <div class="panel-heading">立即预定</div> <div class="price_calender" id="price_calender_<?=$item['id']?>" item_id="<?=$item['id']?>"> <img src="/static/img/loading.gif" /> <script> $("#price_calender_<?=$item['id']?>").load("/product/load_calendar/?item_id=<?=$item['id']?>"); </script> </div> <div class="text-left price_form"> <div> <div><label>活动时间:</label><span class="start_time"><?=$item['start_time']?> </span> </div> </div> <div> <div><label>成人(<?=$item['adult_descrip'] ? $item['adult_descrip'] : "12周岁以上" ?>)</label></div> <input value="1" name="adult_count" size="3" /> <span>RMB <span class="adult_price"><?=$item['base_price']?></span>/人</span> </div> <div> <div><label>儿童(<?=$item['child_descrip'] ? $item['child_descrip'] : '未满12周岁' ?>)</label></div> <input value="0" name="child_count" size="3" /> <span>RMB <span class="child_price"><?=$item['base_price']?></span>/人</span> </div> <div> <div><label>总价:</label> <span class="pull-right"> <span class=" total_price">0</span>元</span></div> <a class="btn btn-success" href="#">预定活动</a> </div> </div> </div> </div> </div> <file_sep>/1/protected/view/shop/product/product_alert.php <?php if($product_info['verify_status'] === '2'){ $refund_arr = explode(";",$product_info['refund_proof']); ?> <div class="alert alert-danger" style='color:red'> <strong> 已被管理员驳回 </strong><br/> <div style="background-color:white;display:block;padding:10px;color:black;margin-top:10px;"> <p>驳回原因:&nbsp;&nbsp;<?=$product_info['refund_excuse']?></p> <p>驳回材料:&nbsp;&nbsp; <?php if ($refund_arr){?> <?php foreach ($refund_arr as $refund){?> <a href="<?=$refund?>" target="_blank">点击查看</a> <?php }?> <?php }?> </p> </div> </div> <?php } ?><file_sep>/1/static/js/app_dailog.js !function ($) { function Toast(){ var that = this; $("#msgbox").remove(); //<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> var box="<div id='msgbox' class='modal succeed fade in'><div class='modal-dialog'><div class='modal-content'>" + "<div class='modal-body'>" + " <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>" + " <p class='info'>内容</p>" + "</div></div></div></div>"; $('body').append($(box)); this.model = $("#msgbox"); }; Toast.prototype.show = function(msg_type, title, msg, time, callback){ this.model.removeClass("succeed"); this.model.removeClass("error"); this.model.addClass(msg_type); this.model.find(".info").html(msg); this.model.modal({}); if(time > 0){ var that = this; setTimeout(function(){ that.model.modal('hide'); if(callback){callback();} }, time); } }; Toast.prototype.setConfirmBox = function(msg){ var box="<div id='msgbox' class='modal notice fade'><div class='modal-dialog'><div class='modal-content'>" + "<div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>" + "<h4>提示</h4></div>" + "<div class='modal-body'>" + "<p class='info'>"+msg+"</p>" + "</div><div class='modal-footer'>" + "<a href='javascript:;' class='btn btn-default cancel_choose' data-dismiss='modal' aria-hidden='true' >取消</a>" + "<a href='javascript:;' class='btn btn-primary confirm_choose' >确定</a>" + "</div></div></div></div>"; this.init_box(box); } Toast.prototype.init_box = function(box){ $("#msgbox").remove(); $('body').append($(box)); this.model = $("#msgbox"); } var toast = null; $.show_error = function(msg, time, callback){ if(!toast){toast = new Toast();} return toast.show("error", '', msg, time, callback); }; $.show_ok = function(msg, time, callback){ if(!toast){toast = new Toast();} return toast.show("succeed", '', msg, time, callback); }; $.show_confirm = function(msg, callback){ if(!toast){toast = new Toast();} toast.setConfirmBox(msg); toast.model.modal("show"); $("#msgbox").on("click", ".confirm_choose", function(){ toast.model.modal("hide"); $("#msgbox").remove(); $(".modal-backdrop").hide(); callback(); }); } }(window.jQuery); <file_sep>/1/protected/view/admin/header.php <!DOCTYPE html> <html> <head> <meta name="generator" content="SAE at <?php echo date("Y-m-d h:i:s"); ?>" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?=$title?></title> <link href="<?=$THEME_URL ?>/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="/static/css/font-awesome.min.css"> <link rel="stylesheet" href="/static/css/shop/base.css"> <script src="<?=$THEME_URL ?>/js/jquery/jquery-1.9.1.min.js"></script> <script src="<?=$THEME_URL ?>/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript"> <?php echo "var S='" . json_encode ( $admin_user ) . "';"; ?> $('.header-user .dropdown-toggle').dropdown(); </script> </head> <body> <div class="header"> <nav class="navbar navbar-default" role="navigation"> <div class="collapse navbar-collapse navbar-ex1-collapse"> <div class="container"> <ul class="nav navbar-nav"> <li> <a href="/"> <i class="icon-bar-chart"></i> <span>首页</span> </a> </li> <li <?=$nav_main == 'shop'? "class='active'":""?>> <a href="/admin/shop_list"> <i class="icon-comments"></i> <span>商家管理</span> </a> </li> <li <?=$nav_main == 'member'? "class='active'":""?>> <a href="/adminMember/"> <i class="icon-book"></i> <span>游客管理</span> </a> </li> <li <?=$nav_main == 'front'? "class='active'":""?>> <a href="/adminFront/"> <i class="icon-globe"></i> <span>前端管理</span> </a> </li> <li class="nav-separator"></li> <li> <a href="/weixin/help"> <i class="icon-question-sign"></i> </a> </li> <li> <a href="#feedback" data-toggle="modal"> <i class="icon-envelope"></i> </a> </li> <li class="nav-separator"></li> </ul> </div> <div class="pull-right btn-group header-user"> <a class="btn btn-success" href="#"> <i class="icon-user"></i> <?=$admin_user['user_nick'] ? $admin_user['user_nick'] :"未登录" ?></a> <a class="btn btn-success dropdown-toggle" data-toggle="dropdown" href="#"> <span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <a href="/user/logout"> <i class="icon-off"></i> 退出 </a> </li> </ul> </div> </div> </nav> <div id="feedback" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" style="width: 700px;"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4>联系我们</h4> </div> <div class="modal-body"> </div> </div> </div> </div> </div><file_sep>/1/protected/action/UserAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; require_once DOCROOT . "/common/global_func.php"; /** * 还没有登录时用户页面。 * * @author deonwu * */ class UserAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->assign("HOST",host_url()."/home/"); Configure::load('cms'); $this->cms = Configure::getItems('cms'); } public function admin_login(){ $callback = host_url() . "/user/auth_emop"; $url = "http://www.emop.cn/user/sso?client_id={$this->cms['app_id']}&redirect_uri={$callback}"; header("location: {$url}"); } public function auth_emop(){ $session = $_REQUEST['session']; $sign = $_REQUEST['sign']; $user = $this->get_emop_user(urldecode($session), $sign); //exit(); if($user['access_token']){ if(DEBUG){ echo "user:" . var_export($_SESSION['user'], true); } session_start(); $_SESSION['admin_uid_token'] = $user['access_token']; $next = $_SESSION['LOGIN_OK_NEXT'] ? $_SESSION['LOGIN_OK_NEXT'] : "/admin/index"; if(strpos($next, 'admin') === false){ $next = "/admin/index"; } $_SESSION['LOGIN_OK_NEXT'] = false; if(DEBUG){ echo "next:{$next}"; exit(); }else { header("location: {$next}"); } }else { //header("location: /user/admin_login"); echo "Error no access token."; } } private function get_emop_user($param, $sign){ $param = urldecode(str_replace(" ", "+", $param)); //$data = base64_decode($param); $user = parse_url_data($param); //5e969f648a49364841936ad6da0b18a9 $key = "{$param},{$this->cms['app_secret']}"; $new_sign = md5($key); $sign = str_replace(" ", "+", $sign); if($new_sign != $sign){ echo "param:{$param}, sign key:{$key}"; echo "sign error:{$new_sign} != {$sign}\n"; exit(); } return $user; } public function logout(){ session_start(); $_SESSION['shop'] = array(); $_SESSION['admin_uid_token'] = false; session_destroy(); header("location: /user/login"); } public function register(){ $this->assign('title','注册-极旅'); $this->display("home/register.php"); } public function save_register_info(){ $uModel = new UserModel(); $result = $uModel->save_register_info(); if ($result['status'] == 'ok'){ $_SESSION['shop'] = $result['shop']; } $this->json($result); } public function login(){ session_start(); $login_ok_text = $_SESSION['LOGIN_OK_NEXT']; if (!$login_ok_text) $login_ok_text = "/shopEnter/my"; if($_SESSION['shop']['id']>0){ header("location: $login_ok_text"); return; } if (($_REQUEST['email'] && $_REQUEST['password'])){ $model = new UserModel(); $return = $model->check_login_info(); if($return['shop']['is_admin'] == 1){ $_SESSION['admin_user_id'] = $return['shop']['id']; } if ($return['status'] == 'ok'){ $_SESSION['shop'] = $return['shop']; header("location: $login_ok_text"); }else{ $this->assign("msg",$return['code']); $this->assign("email",$_REQUEST['email']); } } $this->assign('title','登录-极旅'); $this->display("home/login.php"); } } ?><file_sep>/1/protected/view/shop/enter/enter.php <?php V ('shop/header.php');?> <div class = "col-lg-12" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V('shop/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10 "> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> 注册成为供应商 </h4> </div> <div class="panel-body"> <?php include 'enter_alert.php';?> <?php include 'enter_form.php';?> </div> </div> </div><!-- col-lg-11 --> </div> <!-- 此部分为js加载地区控件 --> <script src="<?=$THEME_URL?>/js/continent.js"></script> <script> //几大洲长度 var a_l=continents.length; var continent = document.getElementById("continent"); var country = document.getElementById("country"); var city = document.getElementById("city"); for_add(continent,continents,a_l); continent.addEventListener("change",function(){ var that = this; var _index = that.selectedIndex; country.length = 1; city.length = 1; if(_index != 0){ that.setAttribute("data-continent-id",continents[_index-1]); var children_l = continents[_index-1]["countries"].length; for_add(country,continents[_index-1]["countries"],children_l); } },false) country.addEventListener("change",function(){ var _parent_index = continent.selectedIndex; var that = this; var _index = that.selectedIndex; city.length = 1; if(_index != 0){ that.setAttribute("data-country-id",continents[_parent_index-1]["countries"][_index-1]); var children_l = continents[_parent_index-1]["countries"][_index-1]["cities"].length; for_add(city,continents[_parent_index-1]["countries"][_index-1]["cities"],children_l); } },false) city.addEventListener("change",function(){ var _parent_index = continent.selectedIndex; var _country_index = country.selectedIndex; var that = this; var _index = that.selectedIndex; if(_index != 0){ that.setAttribute("data-city-id",continents[_parent_index-1]["countries"][_country_index-1]["cities"][_index-1]); } },false) function for_add(obj,arr,l){ for(var i = 0; i < l; i++){ var newOption = new Option(arr[i].name,i); obj.add(newOption,undefined); } } </script> <!-- 此部分为根据数据库里的地址显示到界面上 --> <script> <?php if ($enter){?> render_continents("<?=$enter['continent']?>","<?=$enter['country']?>","<?=$enter['city']?>"); <?php }?> function render_continents(param1,param2,param3){ var CURRENT = { continent : param1, country : param2, city : param3, }; //注册 continent var c = continents; var i = register(c,$("#continent"),CURRENT.continent); for_add(country,c[i].countries,c[i].countries.length); //注册coutry var t = c[i].countries; var j = register(t,$("#country"),CURRENT.country); for_add(city,t[j].cities,t[j].cities.length); //注册city var y = t[j].cities; var h = register(y,$("#city"),CURRENT.city); } function register(obj,$_new,current){ for(var $i=0;$i<obj.length;$i++){ if (obj[$i].name == current){ $_new.find("option").each(function($j,item){ if($(item).text() == obj[$i].name){ item.selected=true; } }) return $i; } } } </script> <?php V ('shop/footer.php');?> <file_sep>/1/protected/view/shop/product/product_add_price.php <?php V ('shop/shop_common_head.php');?> <link rel="stylesheet" href="<?=$THEME_URL?>/css/bootstrap-datetimepicker.min.css"> <script src="<?=$THEME_URL."/js/bootstrap/bootstrap-datetimepicker.min.js"?>"></script> <script src="<?=$THEME_URL."/js/bootstrap/bootstrap-datetimepicker.zh-CN.js"?>"></script> <?php $width = "400px"; $must = "<span class='red'>*</span>"; $product_info = $product_one; ?> <style> #price_info{padding-left:0px;} #price_info .control-label{font-weight:normal;} #price_info h4{border-bottom:1px solid #ccc;font-weight: bold;width: 80%;padding-bottom: 10px; } #price_info .red{color:red;padding-right: 2px;vertical-align: middle;} #price_info img{max-width:220px;max-height:200px;overflow:hidden;} </style> <ol class="breadcrumb"> <li><a href="/shop/product">活动管理</a></li> <li class="active">新增活动</li> </ol> <?php if (!$price_one['id']){ ?> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: 33%"> 填写基本信息 </div> <div class="progress-bar progress-bar-success" style="width: 34%"> 填写可售产品 </div> <div class="progress-bar progress-bar-warning" style="width: 33%"> 完成 </div> </div> <?php } ?> <div role= "form" class="form-horizontal" id="price_info"> <h4>2.价格类型</h4> <input type="hidden" name="pid" value="<?=$price_one['pid'] ? $price_one['pid'] : $_REQUEST['pid']?>"> <input type="hidden" name="id" value="<?=$price_one['id']?>"> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>价格类型名称</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="price_name" value="<?=$price_one['price_name']?>" check-type="required" placeholder="名称" style="width:<?=$width?>;"> </div> </div> <div class= "form-group control-group" > <label for = "exampleInputEmail1" class= "col-sm-2 control-label" > <?=$must ?>门市价 </label > <div class = "col-sm-10 controls"> <div class = "input-group " style= "width:<?=$width?> ;" > <input type = "text" class= "form-control" name = "base_price" value= "<?=$price_one['base_price' ]?> " check-type = "required"> <span class = "input-group-addon"> 元</span> </div > </div > </div > <?php include 'price_table.php';?> <?php $duration_unit = array('h'=>'小时','d'=>'天','m'=>'分钟'); $time_range = array('上午','下午','晚上','一日','超值套餐'); $suit_group = array('家庭','亲子','情侣','商务','背包','户外','奢华','新婚蜜月','团体'); ?> <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>活动开始时间</label> <div class="controls col-sm-10"> <input type="time" class="form-control" check-type="required" style="width:120px" name="start_time" value="<?=$price_one['start_time']?>"> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>活动持续时间</label> <div class="controls col-sm-10"> <input type="text" class="form-control" check-type="required" style="width: 110px; float: left; margin-right: 10px;" name="duration" value="<?=$price_one['duration']?>"> <select name="duration_unit" class="form-control" style="width:100px;"> <?php foreach ($duration_unit as $k=>$unit){?> <option value="<?=$k?>" <?=$k == $price_one['duration_unit'] ? "selected='selected'":""?>><?=$unit?></option> <?php }?> </select> </div> </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>需提前</label> <div class="controls col-sm-10"> <div class="input-group" style="width: 150px;"> <input class="form-control" name="advance_day" type="text" value="<?=$price_one['advance_day']?>" check-type="required" required-message="亲,这个很重要哦!"> <span class="input-group-addon">天预定</span> </div> </div > </div > <div class="form-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>活动时间</label> <div class="control col-sm-10 languange"> <?php foreach ($time_range as $j=>$l){?> <label class="radio-inline"> <input type="radio" name="time_range" value="<?=$l?>" <?=strpos("select".$price_one['time_range'],$l) || (!$price_one['time_range'] && $j == 0) ? "checked=checked":''?>> <?=$l?> </label> <?php }?> </div > </div > <div class="form-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>适合群体</label> <div class="control col-sm-10 languange"> <?php foreach ($suit_group as $i=>$l){?> <label class="checkbox-inline"> <input type="checkbox" name="suit_group" value="<?=$l?>" <?=strpos("select".$price_one['suit_group'],$l) || (!$price_one['suit_group'] && $i == 0) ? "checked=checked":''?>> <?=$l?> </label> <?php }?> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>人数限制</label> <div class="controls col-sm-10"> <input type="text" class="form-control" check-type="required" style="width:<?=$width?>" name="people_limit" value="<?=$price_one['people_limit']?>"> </div > </div > <div class="form-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>接送服务</label> <div class="col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="pickup" <?=$price_one['pickup'] ? "checked=checked":''?>> 是 </label> </div> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>活动亮点</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="lightspot" style="width:<?=$width?>"><?=$price_one['lightspot']?></textarea> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>费用说明</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="fee_descrip" style="width:<?=$width?>"><?=$price_one['fee_descrip']?></textarea> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>退改规则</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="refund_rule" style="width:<?=$width?>"><?=$price_one['refund_rule']?></textarea> </div > </div > <div class="mt50" style="text-align:center"> <input type="button" class="btn btn-primary btn-lg" id="to_act_third" value="下一步"> </div> </div ><!-- form-horizontal --> <script> //价格保存验证 function check_second(){ var price_flag = false; if(!$("#price_info").validation()){ price_flag = true; } if(price_flag){ return false; } return true; } </script> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/YunPHP/lib/SAECache.class.php <?php class SAECache{ var $mmc; function __construct($table) { $this->mmc = memcache_init(); if(!$this->mmc){ echo "mc init failed\n"; } $prefix = 'c'; if($_SERVER['HTTP_APPVERSION'] > 0){ $prefix = "{$prefix}_{$_SERVER['HTTP_APPVERSION']}"; } $this->prefix = $prefix; } function get_cache($key){ $show_c = isset($_REQUEST['show_c']) ? $_REQUEST['show_c']:''; if($show_c == 'y'){ echo "mc key:{$this->prefix}_{$key}\n"; } if($this->mmc){ return memcache_get($this->mmc, "{$this->prefix}_{$key}"); } } function set_cache($key, $data, $expire){ $show_c = isset($_REQUEST['show_c']) ? $_REQUEST['show_c']:''; if($show_c == 'y'){ echo "mc key:{$this->prefix}_{$key}\n"; } if($this->mmc){ return memcache_set($this->mmc, "{$this->prefix}_{$key}", $data, 0, $expire); } } function add_cache($key, $data, $expire){ if($this->mmc){ return memcache_add($this->mmc, "{$this->prefix}_{$key}", $data, 0, $expire); } } } ?><file_sep>/1/protected/view/product/header.php <?php $THEME_URL = host_url()."/static"; ?> <!DOCTYPE html> <html> <head> <meta name="generator" content="SAE at <?php echo date("Y-m-d h:i:s"); ?>" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?=$title?></title> <link href="<?=$THEME_URL ?>/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/font-awesome.min.css"> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/home/item.css"> </head> <body> <script src="<?=$THEME_URL ?>/js/jquery/jquery-1.9.1.min.js"></script> <script src="<?=$THEME_URL ?>/js/bootstrap/bootstrap.min.js"></script> <script src="<?=$THEME_URL ?>/js/bootstrap/bootstrap-validation.js"></script> <script> $('.dropdown-toggle').dropdown(); </script> <div class="header"> <div class="container"> <ul class="nav nav-pills"> <li><a href="/">首页</a></li> <li><a href="/shopEnter">商家入驻</a></li> <li class="dropdown" index="1"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-question-sign" style="font-size:1.3em;color:black"></i>&nbsp;帮助 <span class="caret"></span> </a> <ul class="dropdown-menu pull-right"> <li><a href="#"><i class="icon-user"></i> &nbsp;联系我们</a></li> <li><a href="#"><i class="icon-question-sign"></i> &nbsp;常见问题</a></li> <li style="border:none"><a href="#"><i class="icon-phone"></i> &nbsp;客服</a></li> </ul> </li> <?php if ($shop){ ?> <li class="dropdown" index="2"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-user" style="font-size:1.3em;color:black"></i>&nbsp;<?=$nick?> <span class="caret"></span> </a> <ul class="dropdown-menu pull-right"> <li><a href="/shop/"><i class="icon-lock"></i> &nbsp;商家</a></li> <li><a href="/shop/tourist"><i class="icon-user"></i> &nbsp;游客</a></li> <li><a href="/shop/message"><i class="icon-lock"></i> &nbsp;消息</a></li> <li><a href="/shop/setting"><i class="icon-user"></i> &nbsp;设置</a></li> <li><a href="/user/logout"><i class="icon-user"></i> &nbsp;退出</a></li> </ul> </li> <?php }else{ ?> <li class="dropdown" index="2"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-user" style="font-size:1.3em;color:black"></i>&nbsp;注册 <span class="caret"></span> </a> <ul class="dropdown-menu pull-right"> <li><a href="/user/login"><i class="icon-lock"></i> &nbsp;登录</a></li> <li><a href="/user/register"><i class="icon-user"></i> &nbsp;注册</a></li> </ul> </li> <?php } ?> </ul> </div> </div><file_sep>/1/static/js/app_fileupload.plugin.js /**调用方式 * file:上传按钮 * settings:参数对象 * bucket,return_url * callback(status,file){} * $(file).uploadfile(settings) * * */ function TaodianCMS(proxy_url){ this.proxy_url = proxy_url; } TaodianCMS.prototype.call = function(param, cb){ $.post(this.proxy_url, param, cb); } var TC = new TaodianCMS("/api/get_upyun_key"); !function ($,TC){ $.fn.uploadfile = function(settings) { // 传进来的settings对象与已知的对象合并成新的settings settings = jQuery.extend( { bucket: 'jilv1', allow_file_type : "jpg,jpeg,gif,png", content_length_range:'1024,5120000', image_width_range:'0,5600', image_height_range:'0,10240', save_key: "/jilv/{year}_{mon}_{day}/jilv_{hour}{min}{sec}{.suffix}", return_url: 'http://'+window.location.host+'/api/upload_callback/jilv1', callback: function(e){} }, settings ); //当前上传按钮对象 var jQueryMatchedObj = this; function _upload_callback(status, file){ $(file.parents("form")[0]).find(".uploading").hide(); settings.callback(status, file); }; if(!$.__file_upload_iframe_index){ $.__file_upload_iframe_index = 100; } jQueryMatchedObj.each(function(){ if(!$(this).attr("name")){ $(this).attr("name", "file01"); } var file = $(this); $.__file_upload_iframe_index++; var _form = $("<form target='upload_frame_" + $.__file_upload_iframe_index + "' action='http://v0.api.upyun.com/" + settings.bucket + "/'" + "method='post' enctype='multipart/form-data'>" + "<input class='policy' type='hidden' name='policy' value=''>" + "<input class='signature' type='hidden' name='signature' value=''>" + "<div class='help-inline uploading' style='display:none;color:red'>上传中...</div>"+ "</form>"); var tmp = $(this).replaceWith(_form); _form.append(tmp); var _iframe = $("<iframe class='upload_frame' name='upload_frame_" + $.__file_upload_iframe_index + "' src='' style='display: none'></iframe>"); _iframe.load(function(){ var s = $(this).contents().find('body').text(); var status = $.parseJSON(s); // var aa = typeof(status); //console.log("xx:" + aa); if(status){ _upload_callback(status, file); } }); $("body").append(_iframe); }); /* 修改一个文件内容。 */ function _start(){ start_upload($(this)); }; function start_upload(file){ var form = $(file.parents("form")[0]); if(file.val()){ form.find(".uploading").text("图片上传中……"); form.find(".uploading").show(); TC.call(settings,function(data){ if(data.status == 'ok'){ form.find(".policy").val(data.policy); form.find(".signature").val(data.sign); form.submit(); }else { form.find(".uploading").text("上传图片出错。没有得到上传授权码。"); } }) } }; //先取消上个change绑定事件,再执行新的change事件 return this.unbind('change').change(_start); }; }(window.jQuery,TC);<file_sep>/1/protected/view/shop/left_nav.php <div class="panel panel-default navbar-panel"> <div class="panel-heading"> <h4 class="panel-title"> 我是商家 </h4> </div> <div class="panel-body"> <h4><a href="#">商家信息</a></h4> <ul class="nav nav-stacked left-menu"> <li <?=($nav_index == 'shop_enter') ? 'class="active"' : '' ?>> <a href="/shopEnter/" > <i class="icon-yen"></i> 商家资料 </a> </li> <li <?=($nav_index == 'shop_home') ? 'class="active"' : '' ?>> <a href="/shop/product" > <i class="icon-yen"></i> 商家首页 </a> </li> </ul> <h4><a href="#">活动管理</a></h4> <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == 'product_add'){ echo 'class="active"'; }?> > <a href="/shop/product_add" > <i class="icon-yen"></i> 新增活动 </a> </li> <li <?php if($nav_index == 'product_list'){ echo 'class="active"'; }?>> <a href="/shop/product" > <i class="icon-yen"></i> 已发布活动 </a> </li> <li <?php if($nav_index == 'product_pending'){ echo 'class="active"'; }?>> <a href="/shop/product_pending" > <i class="icon-yen"></i> 审核中活动 </a> </li> </ul> <h4><a href="#">订单管理</a></h4> <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == '2_2'){ echo 'class="active"'; }?>> <a href="/shop/product" > <i class="icon-yen"></i> 新增订单 </a> </li> <li <?php if($nav_index == '2_2'){ echo 'class="active"'; }?>> <a href="/shop/product" > <i class="icon-yen"></i> 交易中订单 </a> </li> <li <?php if($nav_index == '2_2'){ echo 'class="active"'; }?>> <a href="/shop/product" > <i class="icon-yen"></i> 完成订单 </a> </li> </ul> <h4><a href="#">我的消息</a></h4> <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == '2_2'){ echo 'class="active"'; }?>> <a href="/shop/product" > <i class="icon-yen"></i> 消息列表 </a> </li> </ul> </div> </div> <file_sep>/1/protected/view/shop/shop_common_foot.php </div><!-- col-lg-11 --> </div> <?php V ('shop/footer.php');?> <file_sep>/1/protected/module/ShopEnterModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class ShopEnterModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function select_enter_info($sid){ $condition = "sid=$sid"; $data = $this->db->selectData("shop_business_enter_info",$condition); return $data[0]; } public function save_enter_info(){ $fields = array('id','sid','subject','shop_name','surname','forename','sex', 'authentication','registration_name','postcode','continent', 'country','city','address','web_url','license','tel','qq', 'wx','wb','logo','description'); $data = array(); foreach ($fields as $f){ if ($_REQUEST[$f]){ $data[$f] = addslashes(trim($_REQUEST[$f])); } } $data['create_time'] = time(); $data['update_time'] = time(); $data['verify_status'] = 0; $this->db->insertOrUpdate('shop_business_enter_info',$data); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } }<file_sep>/1/protected/module/UserModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class UserModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function save_register_info(){ $data = array(); $data['name'] = addslashes(trim($_REQUEST['name'])); $data['email'] = addslashes(trim($_REQUEST['email'])); $password = trim($_REQUEST['password']); $data['password'] = md5("<PASSWORD>}"); //检查用户名是否重复 $sql_name=<<<SQL select id from shop_login_info where name = '{$data['name']}' limit 1 SQL; $var_name = $this->db->getVar($sql_name); if ($var_name){ return array( 'status'=>'err', 'msg'=>'该用户名已被占用', 'type'=>'name', 'email'=>$data['email'] ); } //检查邮箱是否重复 $sql_email=<<<SQL select id from shop_login_info where email = '{$data['email']}' limit 1 SQL; $var = $this->db->getVar($sql_email); if ($var){ return array( 'status'=>'err', 'msg'=>'该邮箱已经被占用', 'type'=>'email', 'name'=>$data['name'] ); } $data['create_time'] = time(); $this->db->insertData("shop_login_info",$data); $sid = $this->db->lastId(); if ($sid){ $data['id'] = $sid; return array('status'=>'ok','shop'=>$data); }else{ return array('status'=>'err','msg'=>'保存出错啦','type'=>'sql'); } } public function check_login_info(){ $password = trim($_REQUEST['password']); $shop = array('email'=>addslashes(trim($_REQUEST['email'])), 'password'=>md5("<PASSWORD>}") ); $SQL=<<<END select * from shop_login_info where email = '{$shop['email']}' END; $login_info = $this->db->getLine($SQL); if (!($login_info['id']>0)) { return array('status'=>'err','code'=>'邮箱错误!'); } if ($login_info['password'] != $shop['password']){ return array('status'=>'err','code'=>'密码错误!'); } $shop_sql = <<<END select shop_id, verify_status from shop_business_enter_info where sid='{$login_info['id']}' END; $shop_info = $this->db->getLine($shop_sql); if($shop_info){ $login_info = array_merge($login_info, $shop_info); } return array('status'=>'ok','shop'=>$login_info); } }<file_sep>/1/protected/module/ShopModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class ShopModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } /** * 分类 * * 大类 product_travel_type * 中类 product_travel_topic * 小类 product_travel_category */ public function product_travel_type(){ $type = $this->db->selectData('travel_type'); return $type; } public function product_travel_topic(){ $table = "travel_topic"; if ($_REQUEST['type_id']){ $condition = "type_id = {$_REQUEST['type_id']}"; } $data = $this->db->selectData($table,$condition); return $data; } public function product_travel_category(){ $table = "travel_topic_category"; if ($_REQUEST['topic_id']){ $condition = "topic_id = {$_REQUEST['topic_id']}"; } $data = $this->db->selectData($table,$condition); return $data; } public function product_base_save(){ $fields = array( 'id','shop_id','name','description', 'type_select','topic_select','detail_select', 'continent','country','city','address', 'arrive_way','tips', 'language','pic_list'); $data = array(); foreach ($fields as $f){ if ($_REQUEST[$f]){ $data[$f] = addslashes(trim($_REQUEST[$f])); } } $data['create_time'] = time(); $data['update_time'] = time(); $data['verify_status'] = 0; $r = $this->db->insertOrUpdate("shop_product_info",$data); if (DEBUG){ var_dump($r); } if($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } if ($_REQUEST['id']){ $id = $_REQUEST['id']; }else{ $id = $this->db->lastId(); } return array('status'=>'ok','pid'=>$id); } public function product_price_save(){ $fields = array('id','shop_id','pid','price_name','base_price', 'adult_descrip','child_descrip', 'start_date','end_date', 'start_time','duration','duration_unit','advance_day', 'time_range','suit_group', 'people_limit','pickup', 'lightspot','fee_descrip','refund_rule'); $data = array(); foreach ($fields as $f){ if ($_REQUEST[$f]){ $data[$f] = addslashes(trim($_REQUEST[$f])); } } $data['create_time'] = time(); $data['update_time'] = time(); $r = $this->db->insertOrUpdate("shop_product_price_item",$data); if (DEBUG){ var_dump($r); } if($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } if ($_REQUEST['id']){ $id = $_REQUEST['id']; }else{ $id = $this->db->lastId(); } return array('status'=>'ok','pid'=>$_REQUEST['pid'],'item_id'=>$id); } public function product_price_list($pid){ $condition = "pid = $pid"; $data = $this->db->selectData("shop_product_price_item",$condition); return $data; } public function product_price_one($id){ $condition = "id = $id"; $data = $this->db->selectData("shop_product_price_item",$condition); return $data[0]; } public function product_one($id){ $condition = "id = $id"; $data = $this->db->selectData("shop_product_info",$condition); return $data[0]; } public function product_list($sid, $status=1){ if($status == 1){ $condition = "shop_id = $sid and verify_status={$status}"; }else { $condition = "shop_id = $sid and verify_status in ({$status})"; } $data = $this->db->selectData("shop_product_info",$condition); return $data; } public function generate_item_price($shop_id, $item_id, $st, $et, $adult_price, $child_price, $inventory){ $start_time = strtotime($st); $end_time = strtotime($et); for($i = 0; $i < 365 && $start_time <= $end_time; $i++){ $day = date("Ymd", $start_time); $this->db->insertOrUpdate("shop_product_price_detail", array("shop_id"=>$shop_id, "item_id"=>$item_id, "price_date"=>$day, "adult_price"=>$adult_price, "child_price"=>$child_price, "inventory"=>$inventory, "update_time"=>time() ), array('shop_id', 'item_id')); $start_time = $start_time + 24 * 60 * 60; } return array('status'=>'ok','item_id'=>$item_id); } public function save_item_date_price($shop_id, $item_id, $st, $adult_price, $child_price, $inventory){ $start_time = strtotime($st); $day = date("Ymd", $start_time); $this->db->insertOrUpdate("shop_product_price_detail", array("shop_id"=>$shop_id, "item_id"=>$item_id, "price_date"=>$day, "adult_price"=>$adult_price, "child_price"=>$child_price, "inventory"=>$inventory, "update_time"=>time() ), array('shop_id', 'item_id')); if($this->db->errno == 0){ return array('status'=>'ok'); }else { return array('status'=>'err', "code"=>$this->db->errno()); } } public function product_remove(){ $product_id = $_REQUEST['pid']; $this->db->delById('shop_product_info',$product_id); $sql = <<<END select group_concat(id) from shop_product_price_item where pid = $product_id END; $item_idds = $this->db->getVar($sql); $this->db->deleteData('shop_product_price_item',"pid=$product_id"); $this->db->deleteData("shop_product_price_detail","item_id in($item_idds)"); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } }<file_sep>/1/protected/view/home/login.php <?php include 'header.php';?> <script src="http://jilv.sinaapp.com/static/js/bootstrap/bootstrap-validation.js"></script> <div class="body" style="margin-top:120px;"> <div class="content"> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">登录</h3> </div> <div class="panel-body"> <form class="form-horizontal login-form" role="form" style="width:50%;" method="POST" action="?"> <div class="form-group control-group"> <div class="col-sm-10 controls"> <input type="email" class="form-control" id="inputEmail3" placeholder="邮箱" name="email" value="<?=$email?>" check-type="required" required-message="邮箱不能为空!"> </div> </div> <div class="form-group control-group"> <div class="col-sm-10 controls"> <input type="<PASSWORD>" class="form-control" id="inputPassword3" name="password" placeholder="密码" check-type="required" required-message="密码不能为空!"> </div> </div> <div class="form-group"> <div class=" col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="remeber"> 记住帐号 </label> </div> </div> </div> <div class="form-group"> <div class=" col-sm-10"> <button type="submit" id="login" class="btn btn-info btn-block">登录</button> </div> </div> <div class="control-group help" style="<?=$msg ? "":'display: none;'?>"> <label> <p style="color:red;"><?=$msg?></p> </label> </div> </form> </div> </div> </div> </div> </div> <script> var CLICK = false; $("#login").click(function(){ $(".help").hide(); if($("[name=email]").val() && $("[name=password]").val() && !CLICK){ $("#login-form").submit(); }else{ $(".help").show(); $(".help").find("p").text('请输入邮箱和密码!'); return false; } }) </script> <?php include 'footer.php';?><file_sep>/1/protected/module/AdminModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class AdminModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function all_shop_list($param){ $link_url = "?"; $page_shop = $param['page_shop'] ? $param['page_shop']:1; $page_size = 10; $start = ($page_shop-1) * $page_size; $where = "where 1"; if ($param['shop_name']){ $where.=" and shop_name like '%{$param['shop_name']}%'"; $link_url .= "shop_name={$param['shop_name']}&"; } if ($param['subject']){ $where.=" and subject = '{$param['subject']}'"; $link_url .= "subject={$param['subject']}"; } if ($param['verify_status'] || $param['verify_status'] === '0' ){ $where.=" and verify_status = {$param['verify_status']}"; $link_url .= "verify_status = {$param['verify_status']}&"; } $sql = <<<END select * from shop_business_enter_info $where order by create_time desc END; $total = count($this->db->getData($sql)); if (DEBUG){ $link_url .="debug={$_REQUEST['debug']}&"; } $link_url .="page_shop="; $page = $this->page($total, $page_size, $link_url,$page_shop); $data_sql = $sql." limit $start , $page_size"; $data = $this->db->getData($data_sql); if (DEBUG){ echo "sql".$data_sql; } return array($data,$page); } public function all_product_list($param){ $link_url = "?"; $page_no = $param['page_no'] ? $param['page_no']:1; $page_size = 10; $start = ($page_no-1) * $page_size; $where = "where 1"; if ($param['name']){ $where.=" and info.name like '%{$param['name']}%'"; $link_url .= "info.name={$param['name']}&"; } if ($param['verify_status'] || $param['verify_status'] === '0' ){ $where.=" and info.verify_status = {$param['verify_status']}"; $link_url .= "info.verify_status = {$param['verify_status']}&"; } $sql = <<<END select info.*, cate.name as category_name, topic.name as topic_name, typ.name as type_name from shop_product_info info left join travel_topic_category cate on(info.detail_select = cate.id) left join travel_topic topic on(info.topic_select = topic.id) left join travel_type typ on(info.type_select = typ.id) $where order by info.update_time desc END; $total = count($this->db->getData($sql)); if (DEBUG){ $link_url .="debug={$_REQUEST['debug']}&"; } $link_url .="page_no="; $page = $this->page($total, $page_size, $link_url,$page_no); $data_sql = $sql." limit $start , $page_size"; $data = $this->db->getData($data_sql); if (DEBUG){ echo "sql".$data_sql; } return array($data,$page); } public function one_shop($shop_id){ $table = "shop_business_enter_info"; $condition = "shop_id=$shop_id"; $data = $this->db->selectData($table,$condition); return $data[0]; } public function one_product($product_id){ $table = "shop_product_info"; $condition = "id=$product_id"; $data = $this->db->selectData($table,$condition); return $data[0]; } public function one_product_price($product_id){ $table = "shop_product_price_item"; $condition = "pid=$product_id"; $data = $this->db->selectData($table,$condition); $product = $this->one_product($product_id); return array($product,$data); } public function refund_shop(){ $refund_content = array(); $fields = array('refund_excuse','refund_proof','refund_user'); foreach ($fields as $f){ if ($_REQUEST[$f]){ $refund_content[$f] = $_REQUEST[$f]; } } $refund_content['refund_date'] = date("Y-m-d H:i:s"); $data = array(); $data['verify_status'] = $_REQUEST['verify_status']; $data['refund_content'] = addslashes(json_encode($refund_content)); $table = "shop_business_enter_info"; $condition = "shop_id={$_REQUEST['shop_id']}"; $this->db->updateData($table,$data,$condition); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } public function pass_shop(){ $table = "shop_business_enter_info"; $condition = "shop_id={$_REQUEST['shop_id']}"; $data['verify_status'] = 1; $this->db->updateData($table,$data,$condition); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } public function refund_product(){ $refund_content = array(); $fields = array('refund_excuse','refund_proof','refund_user'); foreach ($fields as $f){ if ($_REQUEST[$f]){ $refund_content[$f] = $_REQUEST[$f]; } } $refund_content['refund_date'] = date("Y-m-d H:i:s"); $data = array(); $data['verify_status'] = $_REQUEST['verify_status']; $data['refund_content'] = addslashes(json_encode($refund_content)); $table = "shop_product_info"; $condition = "id={$_REQUEST['id']}"; $this->db->updateData($table,$data,$condition); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } public function pass_product(){ $table = "shop_product_info"; $condition = "id={$_REQUEST['id']}"; $data['verify_status'] = 1; $this->db->updateData($table,$data,$condition); if ($this->db->errno()!=0){ return array('status'=>'err','msg'=>$this->db->errmsg()); } return array('status'=>'ok'); } public function page($total,$page_size,$base_url,$page_current){ $this->load_helper("Page"); $config1['base_url'] = "?debug=&type=&keyword=&page_no="; if($base_url){ $config1['base_url'] = $base_url; } $config1['total_rows'] = $total; $config1['per_page'] = $page_size; $config1['cur_page'] = $page_current; $config1['full_tag_open']= "<div style='text-align:center;'><ul class='pagination'>"; $config1['full_tag_close']= "</ul>"; $config1['first_tag_open'] = "<li>"; $config1['first_tag_close'] = "</li>"; $config1['last_tag_open'] = "<li>"; $config1['last_tag_close'] = "</li>"; $config1['prev_link'] = "上一页"; $config1['next_link'] = "下一页"; $config1['cur_tag_open'] = "<li class='active'><a href='javascript:;'>"; $config1['cur_tag_close'] = "</a></li>"; $config1['next_tag_open'] = "<li>"; $config1['next_tag_close'] = "</li>"; $config1['prev_tag_open'] = "<li>"; $config1['prev_tag_close'] = "</li>"; $config1['page_tab_open'] = "<li>"; $config1['page_tab_close'] = "</li>"; $config1['uri_segmentation'] = ""; $config1['num_links'] = 4; $config1['num_tag_open'] = "<li><a href='javascript:;'>共"; $config1['num_tag_close'] = "页</a></li>"; $pageStr1 = new Page($config1); if(DEBUG){ //var_dump($pageStr1); } return $pageStr1->create_links(); } public function load_main_pic(){ $sql = <<<SQL select p.*, u.name from app_home_page p join shop_login_info u on (u.id=p.user_id) where active < 9 order by p.create_time desc SQL; return $this->db->getData($sql); } public function load_cate_filter($page_view, $cate){ $where = "1=1"; if($page_view){ $where .= " and page_view='{$page_view}'"; } if($cate){ $where .= " and cate_type='{$cate}'"; } $sql = <<<SQL select p.*, u.name from app_cate_filter p left join shop_login_info u on (u.id=p.user_id) where status < 9 and {$where} order by p.view_order asc SQL; return $this->db->getData($sql); } } ?> <file_sep>/1/YunPHP/language/zh-cn.php <?php global $language; /** * ---------------------------------------------------------------------- * 数据库错误 */ $language['_mysql_connect_error_'] = 'mysql数据库连接失败'; $language['_mysql_write_error_'] = 'mysql写入数据失败'; $language['_module_not_exist_'] = '无法加载模块'; $language['_error_action_'] = '非法操作'; /** * ----------------------------------------------------------------------- * 系统错误 */ $language['_not_found_action'] = '控制器没有找到!'; $language['_not_found_module'] = 'module没有找到!'; $language['_not_found_lib'] = '类库没有找到!'; ?><file_sep>/1/protected/view/home/welcome_shop.php <?php include 'header.php';?> <div class="body" style=""> <div class="cover top_images" style="background-image: url('/static/img/location_img.jpg');"> <div class="container" > <div class="register_tips text-center"> <h4>极旅网-在线旅游O2O平台</h4> <div>免费为您敞开推广中国市场大门线上精准营销,线下汇聚客流。</div> <div> <?php if($shop['id'] > 0) {?> <a href="/shop/" class="btn btn-success">&nbsp;&nbsp;进入后台&nbsp;&nbsp;</a> <?php } else {?> <a href="/user/register" class="btn btn-success">&nbsp;&nbsp;免费注册&nbsp;&nbsp;</a> &nbsp; 或 <a href="/user/login">登录</a> <?php }?> </div> </div> </div> </div> <div class="container"> <div class="panel panel-default" style="margin-top:20px;"> <div class="panel-body"> <h4>为什么选择极旅</h4> <div class='row'> <div class="col-xs-6 col-md-4 clearfix"> <h1>免费入住</h1> <div>为你敞开中国市场大门</div> </div> <div class="col-xs-6 col-md-4 clearfix"> <h1>流程简便</h1> <div>入驻简便,半天即可开通账户</div> </div> <div class="col-xs-6 col-md-4 clearfix"> <h1>简单易用</h1> <div>零技术投入,零维护成本</div> </div> <div class="col-xs-6 col-md-4 clearfix"> <h1>功能强大</h1> <div>界面美观一分钟发布活动</div> </div> <div class="col-xs-6 col-md-4 clearfix"> <h1>完全开放</h1> <div>推广自身品牌,树立良好口碑</div> </div> <div class="col-xs-6 col-md-4 clearfix"> <h1>精准推广</h1> <div>轻松获取海量目标用户</div> </div> </div> </div> </div> <div class="panel panel-default"> <div class="panel-body"> <h4>入驻流程</h4> <div class="shop_follow nav-justified text-center"> <div class="col-xs-6 col-md-3"> <span class="label label-success">注册/登录账户</span> <i class="icon-arrow-right"></i> </div> <div class="col-xs-6 col-md-3"> <span class="label label-success">提交资料信息</span> <i class="icon-arrow-right"></i> </div> <div class="col-xs-6 col-md-3"> <span class="label label-success">等待审核</span> <i class="icon-arrow-right"></i> </div> <div class="col-xs-6 col-md-3"> <span class="label label-success">通过审核,发布活动</span> </div> </div> </div> </div> <div class="well"> <h4>谁可以加入</h4> <div>极旅网汇聚来自世界各地本地服务商</div> <div>服务活动包括,旅行度假,景点,活动,夜生活,表演及演出,城市通卡,户外探险,水上活动,票吴,租车,保险等</div> <div>如果您不能明确您是否适合极旅,尽请联系我们,我们将竭诚为您解答。联系方式: <EMAIL></div> </div> </div> </div> <?php include 'footer.php';?> <file_sep>/1/protected/view/shop/enter/setting_password.php <?php V ('shop/header.php');?> <div class="body"> <div class = "col-lg-12"> <div class = "col-lg-1 col-md-1 sidebar-nav"> <?php include 'setting_left_nav.php';?> </div > <div class = "col-lg-11 col-md-11 hd" style="padding-left: 30px;"> <div class="form-horizontal" role="form" id="base_info"> <h4>修改密码</h4> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">旧密码</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" value="" placeholder="旧密码" > </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><span class="red">*</span>新密码</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="name" value="" placeholder="新密码" > </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><span class="red">*</span>确认密码</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="name" value="" placeholder="确认密码" > </div> </div> <div class="mt50" style="text-align:center"> <input type="button" class="btn btn-primary btn-lg" id="to_act_second" value="修改密码"> </div> </div> </div> </div> </div> <?php V ('shop/footer.php');?><file_sep>/1/YunPHP/core/App.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ #global $view_vars; class App extends YunPHP{ public function pre_check_enabled($shop, $config){ } } ?> <file_sep>/1/protected/view/home/register.php <?php include 'header.php';?> <script src="http://jilv.sinaapp.com/static/js/bootstrap/bootstrap-validation.js"></script> <div class="body" style="margin-top:120px;"> <div class="content"> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">注册</h3> </div> <div class="panel-body"> <form class="form-horizontal register-form" role="form" style="width:50%;"> <div class="form-group control-group"> <label for="inputName3" class="col-sm-2 control-label">用户名</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" id="inputName3" placeholder="名字" name="name" check-type="required" required-message="名字不能为空!"> </div> </div> <div class="form-group control-group"> <label for="inputEmail3" class="col-sm-2 control-label">邮箱</label> <div class="col-sm-10 controls"> <input type="email" class="form-control" id="inputEmail3" placeholder="邮箱" name="email" check-type="required" required-message="邮箱不能为空!"> </div> </div> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label">密码</label> <div class="col-sm-10 controls"> <input type="password" class="form-control" id="inputPassword3" name="password" placeholder="密码" check-type="required" required-message="密码不能为空!"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="clause"> 同意极旅用户使用条款和隐私政策 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" id="register" class="btn btn-default btn-block">注册</button> </div> </div> </form> </div> </div> </div> </div> </div> <script> window.HOST = "<?=host_url()?>"; window.LOGIN_OK = HOST+"/shopEnter/my"; var click = false; $("#register").click(function(){ if(click) return false; if($(".register-form").validation()){ if(!$("[name=clause]").prop("checked")){ var err = "<span style='color:red'>请同意条款!</span>"; $("[name=clause]").parent().append(err); return false; } $("[name=name]").css('border-color','#ccc'); $("[name=email]").css('border-color','#ccc'); $("form span.error").remove(); $(this).text("数据正在保存中……"); click = true; var btn = $(this); $.post(HOST+"/user/save_register_info",$(".register-form").serialize(), function(r){ if(r.status == 'ok'){ location.href = LOGIN_OK; }else{ btn.text("注册"); click = false; if (r.type == 'name') { $("[name=email]").val(r.email); $("[name=name]").css('border-color','red'); $("[name=name]").parent().append("<span class='error' style='color:red'>"+r.msg+"</span>"); } else if(r.type == 'email'){ $("[name=name]").val(r.name); $("[name=email]").css('border-color','red'); $("[name=email]").parent().append("<span class='error' style='color:red'>"+r.msg+"</span>"); } else{ $(this).append("<p style='color:red'>"+r.msg+"</p>"); } } },'json') } }) </script> <?php include 'footer.php';?><file_sep>/1/protected/view/cate/item_list_grid.php <div class="grid"> <?php foreach($item_list as $item) {?> <div class="col-lg-3 col-md-4"> <div class="item clearfix"> <a class="thumbnail" href="/i/<?=$item['id']?><?=HTML_VIEW ? ".html" : "" ?>"> <img src="<?=$item['imgs'][0]?>" /> </a> <div> <?=$item['name']?> </div> </div> </div> <?php }?> </div><file_sep>/1/protected/action/AdminAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; include_once DOCROOT . '/common/global_func.php'; /** * 管理员 后台 商家列表,产品列表 * role 角色为2和4的管理员 * @author lili * */ class AdminAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_admin_auth($this, true); // $this->assign("js_group","admin"); if($this->admin_user['role_id'] != 2 && $this->admin_user['role_id'] != 4){ $this->no_admin(); exit(); } Configure::load('cms'); $cms = Configure::getItems('cms'); $this->load_helper('TaoDian'); $this->api = new TaoDian($cms['app_id'],$cms['app_secret']); $this->assign("nav_main", "shop"); } public function no_admin(){ echo "不是管理员。"; } public function index(){ $this->shop_list(); } public function shop_list(){ $admin = new AdminModel(); list($data,$page) = $admin->all_shop_list($_REQUEST); $this->assign('data',$data); $this->assign('page',$page); $this->assign('nav_index','shop_list'); $this->display("admin/shop/shop_list.php"); } public function shop_refund($shop_id){ $admin = new AdminModel(); $shop = $admin->one_shop($shop_id); $this->assign('shop',$shop); $this->assign('nav_index','shop_list'); $this->assign('js_group','admin_shop'); $this->display("admin/shop/shop_refund.php"); } public function shop_refund_save(){ $admin = new AdminModel(); //驳回处理 $_REQUEST['refund_user'] = $this->admin_user['user_id']; $_REQUEST['verify_status'] = 2; $return = $admin->refund_shop(); $this->json($return); } public function shop_pass_save(){ $admin = new AdminModel(); $return = $admin->pass_shop(); $this->json($return); } public function product_list(){ $admin = new AdminModel(); list($data,$page) = $admin->all_product_list($_REQUEST); $this->assign('data',$data); $this->assign('page',$page); $this->assign('nav_index','product_list'); $this->display("admin/product/product_list.php"); } public function product_price($product_id){ $admin = new AdminModel(); list($product,$price_list) = $admin->one_product_price($product_id); $this->assign('product',$product); $this->assign('price_list',$price_list); $this->assign('nav_index','product_list'); $this->display("admin/product/product_price.php"); } public function product_refund($product_id){ $admin = new AdminModel(); $product = $admin->one_product($product_id); $this->assign('product',$product); $this->assign('nav_index','product_list'); $this->assign('js_group','admin_product'); $this->display("admin/product/product_refund.php"); } public function product_refund_save(){ $admin = new AdminModel(); //驳回处理 $_REQUEST['refund_user'] = $this->admin_user['user_id']; $_REQUEST['verify_status'] = 2; $return = $admin->refund_product(); $this->json($return); } public function product_pass_save(){ $admin = new AdminModel(); $return = $admin->pass_product(); $this->json($return); } } ?><file_sep>/1/YunPHP/lib/Router.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class Router { private $default_action = 'index'; private $default_method = 'index'; private $uri_segmentation = '/'; private $uri_suffix = ''; private $uri_argvs = array(); private $uri = ''; private $class = ''; private $method = ''; private $route = ''; private $route_array = array();//route中的action的数组 public function __construct($uri){ $this->uri_segmentation = Configure::getItem('uri_segmentation'); $this->default_action = Configure::getItem('default_action'); $this->default_method = Configure::getItem('default_method'); Configure::load('route'); $this->route = Configure::getItems('route'); $this->route_array = Configure::getRouteArray(); $this->uri = $uri; $this->_parseUrl(); } private function _parseUrl(){ //处理一下uri前后的 '/' if((substr($this->uri,-1) == '/')){ if($this->uri != '/'){ $this->uri = substr($this->uri,1,-1); } }else{ $this->uri = substr($this->uri,1); } if($this->uri == '/'){ //为根目录的时候 $this->uri_argvs[0] = $this->class = $this->default_action; $this->uri_argvs[1] = $this->method = $this->default_method; }else{ $temp = explode($this->uri_segmentation,$this->uri); if(empty($this->route) or !in_array($temp[0],$this->route_array)){ //如果没有设置route,将会是/class/method/argvs/的顺序 $temp_uri = explode($this->uri_segmentation,$this->uri); if(count($temp_uri)== 1){ //如果只有action的时候 $this->uri_argvs[0] = $this->class = $temp_uri[0]; $this->uri_argvs[1] = $this->method = $this->default_method; }else{ $this->uri_argvs = & $temp_uri; $this->class = $temp_uri[0]; $this->method = $temp_uri[1]; } }else{ //如果设置了路由,这里进行路由的匹配 foreach ($this->route as $key => $val) { $key = str_replace(':any','.+',$key); $key = str_replace(':num','[0-9]+',$key); if(preg_match('#^'.$key.'$#',$this->uri)){ $val = preg_replace('#^'.$key.'$#',$val,$this->uri); $temp_uri = explode($this->uri_segmentation,$val); echo "'{$key}' -->aaa'{$val}'"; $this->uri_argvs = & $temp_uri; $this->class = $temp_uri[0]; $this->method = $temp_uri[1]; //var_dump($this->uri_argvs); return true; } } Log::write_log('ERROR',"$this->route is not in the route.php "); } } } /** * 返回从url中取出的数据,uri_argvs['class'] uri_argvs['method'] uri_argvs['argvs'] * * @return unknown */ public function getUriArgvs(){ return $this->uri_argvs; } /** * 返回操作的Class * * @return unknown */ public function getClass(){ return $this->class; } /** * 返回操作的method * * @return unknown */ public function getMethod(){ return $this->method; } } ?><file_sep>/1/protected/view/admin/member/user_list.php <?php V('admin/header.php');?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V('admin/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10" > 用户管理 开发中 </div> </div> <?php V('admin/footer.php');?><file_sep>/1/protected/view/admin/shop/shop_refund.php <?php V ('admin/header.php');?> <?php $sex_array = array('1'=>'男','2'=>'女'); $status = array(0=>'未审核',1=>'审核通过'); ?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V ('admin/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10 "> <div class="panel panel-default"> <div class="panel-heading"> <h4>【<strong>驳回处理</strong>】 <strong style='color:red'>&nbsp;&nbsp;<?=$shop['shop_name']?></strong></h4> </div> <div class="panel-body"> <div class="form" role="form" id="refund_info"> <input type="hidden" name="shop_id" value="<?=$shop['shop_id']?>"> <?php $refund = json_decode($shop['refund_content'],true)?> <div class="form-group control-group"> <label for="inputPassword3" class="control-label"><?=$must?>驳回原因</label> <div class="controls"> <textarea name="refund_excuse" class="form-control" style="width:400px;min-height:150px;" check-type="required"><?=$refund['refund_excuse']?></textarea> </div> </div> <div class="form-group control-group refund"> <label for="inputPassword3" class="control-label"><?=$must?>凭证</label> <div class="controls"> <input type="file" name="file" class="up_excuse"> <input type='hidden' name="refund_proof"> </div> </div> <div class="form-group pic_list"> <?php if ($refund['refund_proof']){ $pic_array = explode(";",$refund['refund_proof']); foreach ($pic_array as $pic){?> <div class="item"> <img src="<?=$pic?>!190"> <input type='hidden' name='img' value='<?=$pic?>'> <span class="del"> <i class='icon-remove-sign' style='font-size:2em;'></i></span> </div> <?php } }?> </div> <div class="form-group" style="text-align:center"> <a class="btn btn-info save">保存</a> </div> </div> </div> </div> </div> </div> <?php V ('admin/footer.php');?><file_sep>/1/protected/helper/Page.class.php <?php /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.0 * @the class is changed from CodeIgniter */ class Page { /*<code> <a href="#">« First</a>&nbsp;&nbsp; <a href="#">&lt;</a>&nbsp; <a href="#">1</a>&nbsp; <a href="#">2</a>&nbsp; <b>3</b>&nbsp; <a href="#">4</a>&nbsp; <a href="#">5</a>&nbsp; <a href="#">&gt;</a>&nbsp;&nbsp; <a href="#">Last »</a></code> */ var $base_url = ''; // 最基础的url,分页函数在最后加上页码 var $total_rows = ''; // 总数 var $per_page = 10; // 每页显示的数量 var $num_links = 2; // 显示在当前页左右的有几个,比如例子中就是2个 var $cur_page = 1; // 默认当前页 var $first_link = '&lsaquo;&lsaquo; 首页'; //第一页的文字 var $next_link = '&gt;'; //下一页的文字 var $prev_link = '&lt;'; //上一页的文字 var $last_link = '尾页 &rsaquo;&rsaquo;'; //最后一页的文字 var $full_tag_open = ''; //如果你想在page外面包一层div,css的标签请用这个 var $full_tag_close = ''; //后标签 var $first_tag_open = ''; //第一页的左边的div css 标签 var $first_tag_close = '&nbsp;'; //第一页右边的div css 标签,下面同 var $last_tag_open = '&nbsp;'; //最后一页 var $last_tag_close = ''; var $cur_tag_open = '&nbsp;<strong>'; //当前页 var $cur_tag_close = '</strong>'; var $next_tag_open = '&nbsp;'; //下一页 var $next_tag_close = '&nbsp;'; var $prev_tag_open = '&nbsp;'; var $prev_tag_close = ''; var $num_tag_open = '&nbsp;'; //总数 var $num_tag_close = ''; var $page_tab_open = '&nbsp;'; //其他不是当前页的页码的div css var $page_tab_close = ''; var $uri_segmentation = ''; //从配置文件中读取分隔符。本分页函数将在url最后加上页码 var $page_uri = ''; //标准生成的uri //处理url stu/list/1 /stu-list-2 function create_links(){ if($this->total_rows == 0 OR $this->per_page == 0){ return ''; } $num_pages = ceil($this->total_rows / $this->per_page); if(DEBUG){ echo "num_pages:$num_pages,total_rows:{$this->total_rows},per_page:{$this->per_page}"; } if($num_pages == 1){ return ''; } $pre_page = $this->cur_page-1; $next_page = $this->cur_page +1; if($this->cur_page >=$num_pages){ $this->cur_page = $num_pages; $next_page = $num_pages; } if($this->cur_page <= 1){ $this->cur_page = 1; $pre_page = 1; } $output = ''; $output .= "$this->full_tag_open"; $output .= "{$this->first_tag_open}<a href='{$this->base_url}1'>$this->first_link</a>{$this->first_tag_close}"; $output .="{$this->prev_tag_open}<a href='{$this->base_url}{$pre_page}'>$this->prev_link</a>{$this->prev_tag_close}"; $show_nums = $this->num_links*2+1;// 显示页码的个数,比如前后2个,加上自己一个,共 5 个 if($num_pages <= $show_nums){ for($i = 1;$i<=$num_pages;$i++){ if($i == $this->cur_page){ $output .= $this->cur_tag_open.$i.$this->cur_tag_close; }else{ $output .= "{$this->page_tab_open}<a href='{$this->base_url}$i'>$i</a>{$this->page_tab_close}"; } } }else{ if($this->cur_page < (1+$this->num_links)){ for($i = 1;$i<=$show_nums;$i++){ if($i == $this->cur_page){ $output .= $this->cur_tag_open.$i.$this->cur_tag_close; }else{ $output .= "{$this->page_tab_open}<a href='{$this->base_url}$i'>$i</a>{$this->page_tab_close}"; } } }else if($this->cur_page >= ($num_pages - $this->num_links)){ for($i = $num_pages - $show_nums ; $i <= $num_pages ; $i++){ if($i == $this->cur_page){ $output .= $this->cur_tag_open.$i.$this->cur_tag_close; }else{ $output .= "{$this->page_tab_open}<a href='{$this->base_url}$i'>$i</a>{$this->page_tab_close}"; } } }else{ $start_page = $this->cur_page - $this->num_links; $end_page = $this->cur_page + $this->num_links; for($i = $start_page ; $i<=$end_page ; $i++){ if($i == $this->cur_page){ $output .= $this->cur_tag_open.$i.$this->cur_tag_close; }else{ $output .= "{$this->page_tab_open}<a href='{$this->base_url}$i'>$i</a>{$this->page_tab_close}"; } } } } $output .="{$this->next_tag_open}<a href='{$this->base_url}{$next_page}'>$this->next_link</a>{$this->next_tag_close}"; $output .= "{$this->last_tag_open}<a href='{$this->base_url}{$num_pages}'>$this->last_link</a>{$this->last_tag_close}"; //$output .="{$this->num_tag_open}$num_pages{$this->num_tag_close}"; $output .= $this->full_tag_close; return $output; } /** * Constructor * * @access public * @param array initialization parameters */ function __construct($params = array()) { $this->uri_segmentation = Configure::getItem('uri_segmentation','config'); if (count($params) > 0) { $this->initialize($params); } } /** * 初始化分页函数 * * @param unknown_type $params */ function initialize($params = array()){ if(count($params > 0)){ foreach ($params as $k => $v){ if(isset($this->$k)){ $this->$k = $v; } } } if(substr($this->base_url,-1) != $this->uri_segmentation){ $this->base_url .= $this->uri_segmentation; } } } <file_sep>/1/YunPHP/core/Action.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ #global $view_vars; class Action extends YunPHP{ private static $_instance; public $view_vars = array(); public $platform = ""; public $style = ""; public function __construct(){ parent::__construct(); } /** * 赋值变量到模板 * * @param unknown_type $key * @param unknown_type $val */ public function assign($key,$val){ $this->view_vars[$key] = $val; } /** * 页面显示 * * @param unknown_type $path */ public function display($path, $shop_id = 0){ if(!DEBUG){ ob_clean(); } header("Content-type: text/html; charset=utf-8"); $this->view_vars['platform'] = $this->platform; $this->view_vars['style'] = $this->style; global $view_vars; $view_vars = $this->view_vars; extract($this->view_vars); $view_file = array( WEBROOT."/sites/{$this->platform}/view/{$this->style}/".$path, WEBROOT."/sites/{$this->platform}/view/".$path, DOCROOT."view/{$this->platform}/{$this->style}/".$path, DOCROOT."view/{$this->platform}/".$path, DOCROOT."view/".$path, $path ); if($shop_id > 0){ array_unshift($view_file, DOCROOT."view/shop/{$shop_id}/".$path); define("SHOP_ID", $shop_id); } $found = false; foreach($view_file as $v){ if (is_file ( $v )){ $found = true; include $v; break; } } if(!$found){ include DOCROOT."view/".$path; } } public function json($data){ if(!DEBUG){ ob_clean(); } echo json_encode($data); } /** * 加载model * * @param unknown_type $model */ public function model($model){ $model = ucfirst($model); if(file_exists(DOCROOT.'module/'.$model.'Model.class.php')){ require_once DOCROOT.'module/'.$model.'Model.class.php'; }else{ throw new Exception("Action ==> $model model not exists"); } } /** * 加载model * * @param unknown_type $model */ public function action($model){ $model = ucfirst($model); if(file_exists(DOCROOT.'action/'.$model.'Action.class.php')){ require_once DOCROOT.'action/'.$model.'Action.class.php'; }else{ throw new Exception("Action ==> $model model not exists"); } } /** * 获取当前实例 * * @return unknown */ public function getInstance(){ if(self::$_instance == NULL){ self::$_instance = new Action(); } return self::$_instance; } /** * 默认的__call函数的调用,如果上层没有重写,这里将默认出现一个404的错误提示 */ public function __call($name,$arguments){ throw new Exception("404 $name function not exist!"); } } ?><file_sep>/1/protected/view/shop/shop_common_head.php <?php V ('shop/header.php');?> <div class = "col-lg-12 clearfix" style="padding:0px;"> <div class = "col-lg-2 col-md-2 sidebar-nav" style="padding:0px;"> <?php V('shop/left_nav.php');?> </div > <div class = "col-lg-10 col-md-10 "><file_sep>/1/protected/view/admin/left_nav.php <div class="panel panel-default navbar-panel"> <div class="panel-heading"> <h4 class="panel-title"> 商家管理 </h4> </div> <div class="panel-body"> <h4><a href="#">商家审核</a></h4> <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == 'shop_list'){ echo 'class="active"'; }?>> <a href="/admin/shop_list"> <i class="icon-group"></i> 商家列表 </a> </li> <li <?php if($nav_index == 'product_list'){ echo 'class="active"'; }?>> <a href="/admin/product_list" > <i class="icon-yen"></i> 产品列表 </a> </li> </ul> </div> </div> <file_sep>/1/protected/helper/Calender.class.php <?php class Render{ function show($d){ return $d['day']; } } class Calendar { var $year; var $month; var $render; var $weeks = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六'); var $weeks2 = array('日','一','二','三','四','五','六'); function __construct($options = array()) { $vars = get_class_vars(get_class($this)); foreach ($options as $key=>$value) { if (array_key_exists($key, $vars)) { $this->$key = $value; } } } function display($render=null) { $render = $render ? $render : $this->render; if(!$render) $render = new Render(); echo '<table class="calendar">'; $this->showWeeks(); $this->showDays($this->year,$this->month, $render); echo '</table>'; } function nextMonth(){ $firstDay = mktime(0, 0, 0, $this->month, 1, $this->year); //$starDay = date('w', $firstDay); $days = date('t', $firstDay); return date("Y-m", $firstDay + $days * 24 * 60 * 60); } function preMonth(){ $firstDay = mktime(0, 0, 0, $this->month, 1, $this->year); //$starDay = date('w', $firstDay); //$days = date('t', $firstDay); return date("Y-m", $firstDay - 24 * 60 * 60); } private function showWeeks() { echo '<tr>'; foreach($this->weeks as $title) { echo '<th>'.$title.'</th>'; } echo '</tr>'; } private function showDays($year, $month, $render) { $firstDay = mktime(0, 0, 0, $month, 1, $year); $starDay = date('w', $firstDay); $days = date('t', $firstDay); echo '<tr>'; for ($i=0; $i<$starDay; $i++) { echo '<td>&nbsp;</td>'; } for ($j=1; $j<=$days; $j++) { $i++; $d = array('date' => "{$this->year}-{$this->month}-" . sprintf("%02d", $j), 'day' => $j, 'n_date'=>sprintf("%04d%02d%02d", $this->year, $this->month, $j) ); if ($j == date('d')) { echo '<td class="today">'. $render->show($d) .'</td>'; } else { echo '<td>'. $render->show($d) .'</td>'; } if ($i % 7 == 0) { echo '</tr><tr>'; } } echo '</tr>'; } } ?><file_sep>/1/YunPHP/core/common.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ /** * 没有实例化的加载类 * * @param unknown_type $class * @return unknown */ function import_class($class){ if(file_exists(DOCROOT.'lib/'.$class.'.class.php')){ require_once(DOCROOT.'lib/'.$class.'.class.php'); return true; }else if(file_exists(YUNPHP.'lib/'.$class.'.class.php')){ require_once(YUNPHP.'lib/'.$class.'.class.php'); return true; }else{ return false; } } function V($path){ global $view_vars; extract($view_vars); $view_file = array( WEBROOT."/sites/" . PLATFORM. "/view/" . STYLE . "/". $path, WEBROOT."/sites/" . PLATFORM. "/view/" . $path, DOCROOT."view/" . PLATFORM. "/" . STYLE . "/". $path, DOCROOT."view/" . PLATFORM. "/" . $path, DOCROOT."view/" . $path ); //define("SHOP_ID", $shop_id); if(defined('SHOP_ID')){ if (SHOP_ID > 0){ array_unshift($view_file, DOCROOT."view/shop/" . SHOP_ID . "/". $path); } } if(defined('BASE_APP_NAME')){ if (BASE_APP_NAME){ array_unshift($view_file, DOCROOT . "apps/" . BASE_APP_NAME . "/views/". $path); } } if(defined('APP_NAME')){ if (APP_NAME){ array_unshift($view_file, DOCROOT . "apps/" . APP_NAME . "/views/". $path); array_unshift($view_file, WEBROOT . "/sites/" . PLATFORM. "/view/" . $path); } } $found = false; foreach($view_file as $v){ if(DEBUG){ #echo "inlcude V:{$v}\n"; } if (is_file ( $v )){ $found = true; include $v; break; } } if(!$found){ echo "!!!Not found view {$path}!!!\n"; } } /** * 重定义exception的函数 * 分两种模板来处理 * */ function my_exception_handler($e){ header("Content-type: text/html; charset=utf-8"); if (DEBUG == TRUE) { $file = $e->getFile(); $line = $e->getLine(); $message = "<b>YunPHP error: </b>".$e->getMessage(); Log::write_log('ERROR',"$message $file $line "); ob_start(); include_once DOCROOT.'errors/debug_error.php'; $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } else { Log::write_log('ERROR',"$message $file $line "); $message = $e->getMessage(); $error_type = trim(array_shift(explode(" ",$message))); ob_start(); switch ($error_type) { case 404: include_once DOCROOT.'errors/show_404.php'; break; default: include_once DOCROOT.'errors/show_error.php'; break; } $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } } function host_url(){ $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https'; $host = $_SERVER['HTTP_HOST']; return $protocol . '://' . $host; } ?><file_sep>/1/protected/view/admin/front/cate_list.php <?php V('admin/header.php');?> <div class="container"> <div class="row"> <div class = "col-lg-2 col-md-1 sidebar-nav"> <?php V('admin/front/left_nav.php');?> </div > <div class = "col-lg-10 col-md-11" > 前端分类 开发中 </div> </div> </div> <?php V('admin/footer.php');?><file_sep>/README.md jilv ==== 一个旅游产品电子商务网站,基于SAE的PHP版 <file_sep>/1/protected/config/route.php <?php $config['i/(:num)'] = 'product/item_view/$1'; $config['cf/(:any)'] = 'cate/filter/$1'; $config['my'] = 'auth/my'; $config['my/(:any)'] = 'auth/my/$1'; ?><file_sep>/1/protected/action/CateAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; class CateAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this); } public function index(){ $this->search_by_cate(); } public function filter($args){ //echo "" if(DEBUG){ echo "args:{$args}"; } //$args = $m = new CateModel(); $segs = explode("-", $args); $num_ids = array(0); foreach ($segs as $s){ if($s > 0){ $num_ids[] = $s; } } $segs = join(",", $num_ids); $params = $m->db->getData("select * from app_cate_filter where `id` in ($segs)"); foreach($params as $p){ if($p['cate_value']){ $_REQUEST[$p['cate_type']] = $p['cate_value']; }else { $_REQUEST[$p['cate_type']] = $p['cate_label']; } $this->assign($p['cate_type'], $p['id']); } $this->search_by_cate(); } public function search_by_cate(){ $this->assign('title','极旅'); $m = new ProductModel(); $item_list = $m->search_products($_REQUEST); $cm = new CateModel(); $cats = $cm->get_cate_list(); $this->assign("cats_group", $cats); $this->assign("item_list", $item_list); $v = $_REQUEST['view'] ? $_REQUEST['view'] : "row"; $this->assign("view", $v); $this->display("cate/product_item_list.php"); } } ?><file_sep>/1/protected/action/IndexAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; include_once DOCROOT . '/common/global_func.php'; class IndexAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->app->check_shop_auth($this); } public function index(){ $m = new HomeModel(); //$product = $this->select_hot_product($m); if (DEBUG){ var_dump('旅游',$product); } $main_pic = $m->db->getVar("select url from app_home_page where active=1 limit 1"); $dest_list = $m->db->getData("select * from app_cate_filter where status=1 and page_view='home' and cate_type='dest' order by view_order limit 9"); $product_list = $m->db->getData("select * from app_cate_filter where status=1 and page_view='home' and cate_type='product_type' order by view_order limit 9"); $this->assign("main_pic", $main_pic); $this->assign("dest_list", $dest_list); $this->assign("product_list", $product_list); $this->assign('title','极旅'); $this->display("home/index.php"); } public function select_hot_product($m){ $travle = $m->select_travel_product(true); $new_data = array(); $sql= <<<END select type_select from shop_product_info where verify_status = 1 group by type_select order by update_time desc limit 9 END; $data = $m->db->getData($sql); foreach ($data as $d){ $new_data[$d['type_select']] = $travle[$d['type_select']]; } return $new_data; } public function select_hot_city($m){ $sql = <<<END select city,pic_list from shop_product_info where verify_status = 1 group by city order by update_time desc limit 9 END; $data = $m->db->getData($sql); return $data; } public function welcome_shop(){ $this->assign("css_path", "home/welcome_shop.css"); $this->display("home/welcome_shop.php"); } } ?><file_sep>/1/protected/view/common/calender.php <h1> <a class="btn btn-default pull-left prev"><i class="icon-angle-left"></i></a> <span><?=$c->year . "-" . $c->month ?></span> <a class="btn btn-default pull-right next"><i class="icon-angle-right"></i></a> </h1> <script type="text/javascript"> var CUR_ITEM_ID = '<?=$_REQUEST['item_id']?>'; </script> <?php $c->display(); ?><file_sep>/1/protected/common/global_func.php <?php /** *对字符串中需要加转义的字符加"\" * */ function new_addslashes($string) { if (! is_array ( $string )) return addslashes ( $string ); foreach ( $string as $key => $val ) $string [$key] = new_addslashes ( $val ); return $string; } /** * 去掉转义字符 * 例:"abc\'efg" 会被处理成 "abc'efg" */ function new_stripslashes($string) { if (! is_array ( $string )) return stripslashes ( $string ); foreach ( $string as $key => $val ) $string [$key] = new_stripslashes ( $val ); return $string; } /** * * 中文截取字符串 * @param unknown_type $start 开始位置 0 * @param unknown_type $length 结束位置 0:表示到字符串结尾 * @param unknown_type $string 需要被截取的字符串 */ function cn_substr($start, $length, $string) { $str_length = strlen ( $string ); //字符串的字节数 $string = str_replace ( array ('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;' ), array (' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…' ), $string ); // if ($str_length <= $length) { // return $string; // } $s = cn_strpos($string, $start); $e = cn_strpos($string, $start+$length); return substr($string, $s,$e-$s); } /** * * 定位中文字符串位置 * @param unknown_type $string * @param unknown_type $pos */ function cn_strpos($string,$pos){ $i = 0; $n = 0; $str_length = strlen ( $string ); if (strtolower ( CHARSET ) == 'utf-8') { while ( ($n < $pos) and ($i <= $str_length) ) { $temp_str = substr ( $string, $i, 1 ); $ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码 if ($ascnum == 252 || $ascnum == 253) { $i = $i + 6; //实际Byte计为6 $n ++; //字串长度计1 } else if (248 <= $ascnum && $ascnum <= 251) { $i = $i + 5; //实际Byte计为5 $n ++; //字串长度计1 } else if (240 <= $ascnum && $ascnum <= 247) { $i = $i + 4; //实际Byte计为4 $n ++; //字串长度计1 } else if ($ascnum >= 224) //如果ASCII位高与224, { $i = $i + 3; //实际Byte计为3 $n ++; //字串长度计1 } elseif ($ascnum >= 192) //如果ASCII位高与192, { $i = $i + 2; //实际Byte计为2 $n ++; //字串长度计1 } elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母, { $i = $i + 1; //实际的Byte数仍计1个 $n ++; //但考虑整体美观,大写字母计成一个高位字符 } else //其他情况下,包括小写字母和半角标点符号, { $i = $i + 1; //实际的Byte数计1个 $n = $n + 1; // } } return $i; } else { return $pos; } } function fixed_length($msg, $length){ $start = 0; $labelArr = array(); do{ unset($tmp); $tmp = cn_substr($start, $length, $msg); $labelArr[] = $tmp; $start+=$length; }while($tmp); return join("\n", $labelArr); } function writeover($filename, $data, $method = "rb+", $iflock = 1, $check = 1, $chmod = 1) { $check && strpos ( $filename, '..' ) !== false && exit ( 'Forbidden' ); touch ( $filename ); $handle = fopen ( $filename, $method ); if ($iflock) { flock ( $handle, LOCK_EX ); } fwrite ( $handle, $data ); if ($method == "rb+") ftruncate ( $handle, strlen ( $data ) ); fclose ( $handle ); $chmod && @chmod ( $filename, 0777 ); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } function get_post_data(){ $raw_data = file_get_contents('php://input'); $data = array(); #explode("\n", $this->get('app_keys')) foreach(explode("&", $raw_data) as $item){ list($k, $v) = explode("=", $item, 2); $v = urldecode($v); if(!isset($data[$k])){ $data[$k] = $v; }else if(is_array($data[$k])){ array_push($data[$k], $v); }else { $tmp = array($data[$k], $v); $data[$k] = $tmp; } } return $data; } function parse_url_data($raw_data){ $data = array(); #explode("\n", $this->get('app_keys')) foreach(explode("&", $raw_data) as $item){ list($k, $v) = explode("=", $item, 2); if(!isset($data[$k])){ $data[$k] = $v; }else if(is_array($data[$k])){ array_push($data[$k], $v); }else { $tmp = array($data[$k], $v); $data[$k] = $tmp; } } return $data; } function curl_fetch($url, $postFields = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (is_array($postFields) && 0 < count($postFields)) { $postBodyString = ""; $postMultipart = false; foreach ($postFields as $k => $v) { if("@" != substr($v, 0, 1))//判断是不是文件上传 { $postBodyString .= "$k=" . urlencode($v) . "&"; } else//文件上传用multipart/form-data,否则用www-form-urlencoded { $postMultipart = true; } } unset($k, $v); curl_setopt($ch, CURLOPT_POST, true); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1)); } } $reponse = curl_exec($ch); if (curl_errno($ch)) { //throw new Exception(curl_error($ch),0); if(DEBUG){ echo "error curl code:" . curl_error($ch); } } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { if(DEBUG){ echo "error http code:{$httpStatusCode}"; } //throw new Exception($reponse,$httpStatusCode); } } curl_close($ch); return $reponse; } function getip() { if (isset ( $_SERVER )) { if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) { $aIps = explode ( ',', $_SERVER ['HTTP_X_FORWARDED_FOR'] ); foreach ( $aIps as $sIp ) { $sIp = trim ( $sIp ); if ($sIp != 'unknown') { $sRealIp = $sIp; break; } } } elseif (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) { $sRealIp = $_SERVER ['HTTP_CLIENT_IP']; } else { if (isset ( $_SERVER ['REMOTE_ADDR'] )) { $sRealIp = $_SERVER ['REMOTE_ADDR']; } else { $sRealIp = '0.0.0.0'; } } } else { if (getenv ( 'HTTP_X_FORWARDED_FOR' )) { $sRealIp = getenv ( 'HTTP_X_FORWARDED_FOR' ); } elseif (getenv ( 'HTTP_CLIENT_IP' )) { $sRealIp = getenv ( 'HTTP_CLIENT_IP' ); } else { $sRealIp = getenv ( 'REMOTE_ADDR' ); } } return $sRealIp; } function sub_string($str, $len, $charset="utf-8"){ //如果截取长度小于等于0,则返回空 if( !is_numeric($len) or $len <= 0 ){ return ""; } //如果截取长度大于总字符串长度,则直接返回当前字符串 $sLen = strlen($str); if( $len >= $sLen ){ return $str; } //判断使用什么编码,默认为utf-8 if ( strtolower($charset) == "utf-8" ){ $len_step = 3; //如果是utf-8编码,则中文字符长度为3 }else{ $len_step = 2; //如果是gb2312或big5编码,则中文字符长度为2 } //执行截取操作 $len_i = 0; //初始化计数当前已截取的字符串个数,此值为字符串的个数值(非字节数) $substr_len = 0; //初始化应该要截取的总字节数 for( $i=0; $i < $sLen; $i++ ){ if ( $len_i >= $len ) break; //总截取$len个字符串后,停止循环 //判断,如果是中文字符串,则当前总字节数加上相应编码的中文字符长度 if( ord(substr($str,$i,1)) > 0xa0 ){ $i += $len_step - 1; $substr_len += $len_step; }else{ //否则,为英文字符,加1个字节 $substr_len ++; } $len_i ++; } $result_str = substr($str,0,$substr_len ); return $result_str; } function get_header_html($notice){ $header_html=<<<END <div id='output' style='min-height:200px;display:block;background-color: ivory; padding:10px;position:absolute;top:50%;'><br/><br/> <p style='color:red'>***************** *********************$notice****************** *********************</p><br/> END; return $header_html; } function get_footer_html($notice){ $footer_html=<<<HTML <br/><p style='color:red'>***************** *********************$notice*************** ************************</p> HTML; return $footer_html; } function get_content_html($array){ $content_html = get_content_string_html($array); if (!$content_html){ $content_html = get_content_array_html($array); } return $content_html; } function get_content_string_html($array){ if (!$array){ $content_html=<<<HTML <p style='color:green'>**************当前数组为空**************</p></div> HTML; return $content_html; } $type_out = (is_array($array) || is_object($array)) ? 1:0; if (!$type_out){ $content_html=<<<HTML <p style='color:red'>String</p><p style='color:red'> (</p><p style='color:green;margin-left:30px;'>$array</p><p style='color:red'>)</p> HTML; return $content_html; } return false; } function get_content_array_html($array){ $type_name = is_array($array) ? '二维数组':''; $type_name = is_object($array) ? '二维对象数组':''; $content1 = "<h5>$type_name</h5><p style='color:red'>Array</p><p style='color:red'>(</p>"; foreach ($array as $k=>$field){ if (!is_array($field)){ $content2 = "<p style='color:blank;margin-left:70px;'>"; $content2.="<strong>[$k]</strong>"; $content2.="&nbsp;&nbsp;=> &nbsp;&nbsp;$field</p>"; } else { $content2 = "<p style='color:green'>"; $content2.= "<strong style='margin-left:20px;'>[$k]=> Array</strong>"; $content2.= "</p><p style='color:green;margin-left:70px;'>(</p>"; foreach ($field as $f=>$n){ if (is_array($n)){ $data = array(); foreach($n as $key=>$value) { if (is_array($value)){ $data[$key] = $value; }else{ $data[$key] = urlencode($value); } } $n = urldecode(json_encode($data)); } $content2.="<p style='color:black;margin-left:90px;'>"; $content2.="<strong>[$f]&nbsp;&nbsp;=> &nbsp;&nbsp;$n"; $content2.="<span style='color:red'>"; $content2.="(此字段是被json_encode之后的打印信息,其实是数组)</span>"; $content2.="</strong></p>"; } $content2.="<p style='color:green;margin-left:70px;'>)</p>"; } } $content_html = $content1.$content2; return $content_html; } function print_array($notice,$array,$is_exit = true){ header("Content-type: text/html; charset=utf-8"); $notice = $notice ? $notice :'数组信息'; $header_html = get_header_html($notice); $footer_html = get_footer_html($notice); $content_html = get_content_html($array); echo $header_html; echo $content_html; echo $footer_html; if ($is_exit){ exit(); } } /** * * @param $setting * 此方法需要phpinfo配置里面 xmlwriter enable * */ function load_PHPExcel($setting = array()){ header("Content-Type: text/html; charset=utf-8"); $root = WEBROOT.'/protected/helper/'; require_once $root.'PHPExcel/PHPExcel.php'; $objPHPExcel = new PHPExcel(); // //设置文档基本属性 // if ($setting){ // $objProps = $objPHPExcel->getProperties(); // $objProps->setCreator($setting['creator']);//创建者 // $objProps->setLastModifiedBy($setting['modifyer']);//修改者 // $objProps->setTitle($setting['title']);//标题 // $objProps->setSubject($setting['subject']);//主题 // $objProps->setDescription($setting['description']);//备注 // $objProps->setKeywords($setting['keywords']);//标记 // $objProps->setCategory($setting['Category']); //类别 // } //报错,找不到XMLWriter require_once $root.'PHPExcel/PHPExcel/IOFactory.php'; //指定版本为Excel 2007 // require_once $root.'PHPExcel/PHPExcel/Reader/Excel2007.php'; return $objPHPExcel; } /** * 写入数据 * @param $data Array * 单元格Column是以0开始的,row是以1开始的 * $setting['save_dir']保存目录 * $setting['excel_name'] 保存文件名 */ function import_excel($setting,$data){ $name = isset($setting['name']) ? $setting['name'] :'未命名'; $objPHPExcel = load_PHPExcel($setting); $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(16);//設置單元格寬度 // $objPHPExcel->getActiveSheet()->setTitle($name);//設置當前工作表的名 //创建新的工作表 $objPHPExcel->createSheet(); //设置第一个内置表(一个xls文件里可以有多个表)为活动的 $objPHPExcel->setActiveSheetIndex(0); $i = 0; $r = 2; foreach ($data as $key=>$item){ if (is_array($item)){ if ($key == 0){ foreach ($item as $k=>$v){ $keyfields[] = $k; } for ($j=0;$j<count($item);$j++){ //第一行 $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($j, 1, $keyfields[$j]); } } foreach ($item as $t=>$m){ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($t, $r, $m); } $r++; } else { if (!is_numeric($key)){ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i, 1, $key); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i, 2, $item); $i++; }else{ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $key+1, $item); } } } $excelName = 'Excel_'.date("YmdHis").'.xls';//設置導出excel的文件名 $excelName = $setting['excel_name'] ? $setting['excel_name']:$excelName; $dir = WEBROOT.'/static/excel/'; $dir = $setting['save_dir']?$setting['save_dir']:$dir; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save($dir.$excelName);//保存文件 // $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); // $objWriter->save($dir.$excelName);//保存文件 } /** * 读出数据 * @param $setting['file_path'] * */ function export_excel($setting){ $objReader = PHPExcel_IOFactory::createReader ( 'Excel2007' ); $objReader->setReadDataOnly ( true ); if (!$setting['file_path']){ return false; } $objPHPExcel = $objReader->load ($setting['file_path']); /**读取excel文件中的第一个工作表*/ $objWorksheet = $objPHPExcel->getSheet (0); //取得excel的总行数 $highestRow = $objWorksheet->getHighestRow (); //取得excel的总列数 $highestColumn = $objWorksheet->getHighestColumn (); //格式化列,转换为数字索引 $highestColumnIndex = PHPExcel_Cell::columnIndexFromString ( $highestColumn ); $excelData = array (); if ($highestColumn == 1){ for ($row = 1;$row<=$highestRow;$row++){ $excelData[] = $objWorksheet->getCellByColumnAndRow ( 0, $row )->getValue (); } return $excelData; } //获取第一行作为key $keyfields = array(); for ($col = 0;$col<=$highestColumn;$col++){ $keyfields[] = $objWorksheet->getCellByColumnAndRow ( $col, 1 )->getValue (); } for($row = 2; $row <= $highestRow; $row++) { for($col = 0; $col < $highestColumnIndex; $col++) { $excelData[$row-2][$keyfields[$col]] = $objWorksheet->getCellByColumnAndRow ( $col, $row )->getValue (); } } return $excelData; } /** * 转换字符串内容 */ function convertUTF8($string){ if(empty($string)) return ''; return iconv('gb2312', 'utf-8', $str); } ?> <file_sep>/1/protected/view/shop/order/order_left_nav.php <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == '3_1'){ echo 'class="active"'; }?>> <a href="/shopEnter/index"> <i class="icon-group"></i> 订单列表 </a> </li> </ul><file_sep>/1/protected/view/shop/product/price_table_lot.php <style> #generate_source{ margin:10px;padding:10px; } #generate_source tr td{ padding-top: 10px; } </style> <div class="form-horizontal" role="form" style="margin-top:20px; background-color:rgb(250, 239, 218);width:80%;" > <table id="generate_source"> <tbody> <tr> <td>时间段</td> <td><input class = "form-control" name= "start_date" value ="<?=$price_one['start_date'] ?>" type= "date"/></td> <td style="text-align: center">至</td> <td><input class = "form-control" name= "end_date" value ="<?=$price_one['end_date'] ?>" type= "date"/></td> </tr> <tr> <td>成人价</td> <td> <div class = "input-group " style= " width:200px;" > <input type = "text" class= "form-control" name = "adult_price" > <span class = "input-group-addon"> 元</span> </div > </td> <td>儿童价</td> <td> <div class = "input-group " style= " width:200px;" > <input type = "text" class= "form-control" name = "child_price" > <span class = "input-group-addon"> 元</span> </div > </td> </tr> <tr> <td></td> <td> <input type = "text" class= "form-control" value="<?=$price_one['adult_descrip'] ?>" name ="adult_descrip" style= " width:200px;" placeholder="说明"> </td> <td></td> <td> <input type = "text" class= "form-control" value="<?=$price_one['child_descrip'] ?>" name ="child_descrip" style= " width:200px;" placeholder="说明"> </td> </tr> <tr> <td>数量</td> <td colspan="2"> <input type = "text" class= "form-control" style= " width:150px " name = "inventory" > </td> <td><a class = "btn btn-success" id= "generate_price" >生成 </a ></td> </tr> </tbody> </table> <div class="calender" style="display:none;" id="calender"> <div id="price_calender"></div> <div id="calender_editor" style="display:none;"> <div class="adult_price"><label>成人价</label><span><input name="adult_price" value="1"/></span></div> <div class="child_price"><label>儿童</label><span><input name="child_price" value="1"/></span></div> <div class="inventory"><label>数量</label><span><input name="inventory" value="1"/></span></div> <div><a class="btn btn-default save">保存</a></div> </div> </div> </div><file_sep>/1/protected/config/config.php <?php /** * ---------------------------------------------------------------------- * 设置默认的编码 * ---------------------------------------------------------------------- * 默认全站的字符编码是UTF-8 */ $config['charset'] = 'UTF-8'; /** * ---------------------------------------------------------------------- * 默认允许的url字符 * ---------------------------------------------------------------------- * 一般情况下保持默认的 */ $config['permitted_uri_chars'] = 'a-zA-Z 0-9~%.:_\-'; /** * ---------------------------------------------------------------------- * 记录日志的等级 * ---------------------------------------------------------------------- * ERROR 1 * INFO 2 * DEBUG 3 * ALL 4 * 在debug模 式下可以打出很多额外的log */ $config['log_write_level'] = '2'; /** * --------------------------------------------------------------------- * log日志存放的地方,由于sae的不完善等各方面的因素,目前依旧存放在mysql中 * --------------------------------------------------------------------- * 如果放在mysql中,需要建一个表logs * 字段4个,id(auto_increament),log_time(timestamp),message,level * 如果是存放在sae中,请在后台查看 * $config['log_place']='mysql','sae'; */ $config['log_place'] = 'sae'; $config['log_table'] = 'logs'; /** * ---------------------------------------------------------------------- * url 拆分的标志 * ---------------------------------------------------------------------- * 本框架只支持这种方式的url ,默认为 '/' * /user/info/5/hema/ 表示 控制器user 模型info 参数 5 hema * /user-info-5-hema/ 表示的意义同上 * /user_info_5_hema/ * * 如果有其他的路由规则请在router.php中设置 */ $config['uri_segmentation'] = '/'; /** * --------------------------------------------------------------------- * 默认的action ,就是控制跳转器 ,默认为index * --------------------------------------------------------------------- */ $config['default_action'] ='Index'; /** * --------------------------------------------------------------------- * 默认的method ,就是控制跳转器 ,默认为index * --------------------------------------------------------------------- */ $config['default_method'] = 'index'; <file_sep>/1/protected/common/cache.class.php <?php class SimpleCache { var $backend = 'mysql'; var $c = null; var $prefix = ''; function __construct($backend='mysql', $table='cache_table', $prefix='') { if($backend == 'mysql'){ $this->c = new MysqlCache($table); }else if($backend == 'sae'){ $this->c = new SAECache($table); } /* if($_SERVER['HTTP_APPVERSION'] > 0){ $prefix = "{$prefix}_{$_SERVER['HTTP_APPVERSION']}"; } */ $this->prefix = $prefix; } /** * 从缓存中取一个数据, 如果数据过期或没有找到返回null; */ function get($key){ $key = $this->prefix . $key; return $this->c->get_cache($key); } /** * 保存数据到缓存。 * @param $key -- 数据保存的key * @param data -- php 能够序列化的array,或简单数据。 * @param expire -- 缓存时间, 单位秒. */ function set($key, $data, $expire=86400){ $key = $this->prefix . $key; return $this->c->set_cache($key, $data, $expire); } function add($key, $data, $expire=86400){ $key = $this->prefix . $key; return $this->c->add_cache($key, $data, $expire); } /** */ function set_file($key, $data){ $path = SITE_ROOT . "/_st/$key"; file_put_contents($path, $data); $url = "http://" . $_SERVER ["HTTP_HOST"] . "/apps/_st/" .$key; return $url; } function get_file($key){ $path = SITE_ROOT . "/_st/$key"; return file_get_contents($path); } function remove_file($key){ $path = SITE_ROOT . "/_st/$key"; unlink($fileName); } } /** * 使用Mysql数据库作为缓存的后端。 * 表结构: * 1. cache_id varchar(64) * 2. data longtext() * 3. expired_date datetime(); */ class MysqlCache { var $mysql; var $cache_table; function __construct($table) { $this->mysql = new db_mysql(); $this->mysql->connect(DB_HOST, DB_USER, DB_PW, DB_NAME, DB_PCONNECT, DB_CHARSET); $this->cache_table = $table; if(!SETUP_APP){ $this->_create_app_table(); } } function get_cache($key){ $sql = "select data, UNIX_TIMESTAMP(expired_date) as expired_stamp from " . $this->cache_table . " where cache_id='$key'"; $obj = $this->mysql->get_one($sql); $data = ''; if($obj && is_array($obj)){ if($obj['expired_stamp'] < time()){ return null; }else { $data = unserialize($obj['data']); } } return $data; } function set_cache($key, $data, $expire){ $sql = 'delete from ' . $this->cache_table . " where cache_id='$key'"; $re = $this->mysql->query($sql); #$this->mysql->free_result($re); $s_data = serialize($data); $expired_time = time() + $expire; $expired = "FROM_UNIXTIME('$expired_time')"; $sql = "insert into " . $this->cache_table . "(cache_id, data, expired_date) values('$key', '$s_data', $expired)"; $re = $this->mysql->query($sql); return $data; } private function _create_app_table(){ $table_list = $this->mysql->table_list(); if(!in_array($this->cache_table, $table_list)){ $table_name = $this->cache_table; $create_sql = <<<END CREATE TABLE `$table_name` ( `cache_id` varchar(64) NOT NULL, `data` text, `expired_date` datetime DEFAULT NULL, PRIMARY KEY (`cache_id`), index(expired_date) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; END; $re = $this->mysql->query($create_sql); if(!$re){ die("failed to execute sql '${create_sql}'\n" . mysql_error()); } } } } ?> <file_sep>/1/YunPHP/core/Autoloader.class.php <?php defined('YUNPHP') or exit('can not access!'); class Autoloader{ public $cache = array(); public function __construct(){ } public function loadClass($name){ $file = ''; if($this->str_ends($name, 'Model')){ $file = DOCROOT.'module/'. $name. '.class.php'; }else if($this->str_ends($name, 'Trigger')){ $file = DOCROOT.'trigger/'. $name. '.class.php'; }else if($this->str_ends($name, 'Builder')){ $file = DOCROOT.'builder/'. $name. '.class.php'; }else if($this->str_ends($name, 'Hook')){ $file = DOCROOT.'hooks/'. $name. '.class.php'; }else if($this->str_ends($name, 'Helper')){ $file = DOCROOT.'helper/'. $name. '.class.php'; } if(DEBUG){ echo "include:{$file}\n"; } if(file_exists($file)){ require_once $file; } } private function str_ends($str, $e){ $slen = strlen($str) - strlen($e); if($slen > 0){ return substr($str, $slen) == $e; } return false; } public function init(){ spl_autoload_register(array($this, "loadClass")); } } ?><file_sep>/1/YunPHP/core/YunPHP.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class YunPHP{ private static $_instance = array(); const VERSION = '1.0.0'; static $herlpers = array(); static $libs = array(); /** * 构造函数 */ public function __construct(){ self::$_instance = &$this; } /** * 加载类库,也就是加载系统lib目录中的东西,但是没有new * * @param unknown_type $class * @return unknown */ public function load_class($class){ if(in_array($class,self::$libs)){ return true; } if(file_exists(YUNPHP.'lib/'.$class.'.class.php')){ require_once(YUNPHP.'lib/'.$class.'.class.php'); return true; }else{ throw new Exception("Libs error ==> $class.class.php not eixst!"); } } /** * 加载项目的helper类库 * * @param unknown_type $helper */ public function load_helper($helper){ if(in_array($helper,self::$herlpers)){ return true; } if(file_exists(DOCROOT.'helper/'.$helper.'.class.php')){ require_once(DOCROOT.'helper/'.$helper.'.class.php'); self::$herlpers[] = $helper; return true; }else if(file_exists(DOCROOT.'helper/'.$helper.'.php')){ require_once (DOCROOT.'helper/'.$helper.'.class.php'); self::$helpers[] = $helper; return true; }else{ throw new Exception("Helper load Error ==> $helper.class.php or $helper.php not found!"); } } public static function getVersion(){ return self::VERSION; } /* * 析构函数 */ public function __destruct(){ } } ?><file_sep>/1/protected/view/index.php <?php $THEME_URL = host_url()."/static"; ?> <!DOCTYPE html> <html> <head> <meta name="generator" content="SAE at <?php echo date("Y-m-d h:i:s"); ?>" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>极旅</title> <link href="<?=$THEME_URL ?>/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="<?=$THEME_URL ?>/css/font-awesome.min.css"> <script src="<?=$THEME_URL ?>/js/jquery/jquery-1.9.1.min.js"></script> </head> <body> <div class="container" style="text-align:center"> <h3>this is yunPHP framwork and Html template</h3> <div> <h5>上传图片测试</h5> <input type="file" name="file" style="display: block;margin-left: auto;margin-right: auto;width:90px"> <img src="" title=""/> <p class="err"></p> </div> </div> <script src="<?=$THEME_URL ?>/js/app_fileupload.plugin.js"></script> <script> $("input[name=file]").uploadfile({ callback: function(data){ if(typeof(data) == 'object'){ if(data.code == '200'){ $("img").attr("src",data.url+"!190"); $("img").attr("title",data.url); }else{ $(".err").text(data.message); } } } }) </script> <script type="text/javascript" language="javascript" src="<?=$THEME_URL ?>/js/js_loader.php?ver=<?=$_REQUEST['ver'] ?>&group=<?=$js_group ?>&no_cache=<?=$_REQUEST['no_cache']?>&zl=<?=$_REQUEST['zl']?>&br=<?=$_REQUEST['br']?>"></script> <style> .footer{ text-align: center; margin: 5px 0; } .footer a{ font-size: 14px; color: #ccc; padding-bottom: 10px; text-align: center; display: block; text-shadow: 0 1px 0 #fff; font-family: Helvetica,Arial,sans-serif; line-height: 15px; text-decoration: none; } </style> <div class="footer"> <a href="http://m.mty5.com/app/code/4001178~serve" title="猫头鹰移动营销"> 由 猫头鹰 提供技术支持 </a> </div> </body> </html> </body> </html> <file_sep>/1/YunPHP/lib/Configure.class.php <?php defined('YUNPHP') or exit('can not access!'); /** * YunPHP4SAE php framework designed for SAE * * @author heyue <<EMAIL>> * @copyright Copyright(C)2010, heyue * @link http://code.google.com/p/yunphp4sae/ * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version YunPHP4SAE version 1.0.2 */ class Configure { public static $mainConfig = array(); public static $is_load = array(); public static $routeArray = array(); /** * 加载函数库,file为函数名 * * @param unknown_type $file * @return unknown */ public static function load($file = 'config'){ if(in_array($file,self::$is_load)){ return true; } // if(file_exists(DOCROOT."config/$file.php")){ include_once (DOCROOT."config/$file.php"); // if(is_array($config)){ self::$mainConfig[$file] = &$config; self::$is_load[] = $file; // }else{ // throw new Exception("configure ==> the config in config/$file.php not an array!"); // } // }else{ // throw new Exception("configure ==> config/$file.php not exists!"); // } } /** * 返回某种配置文件的数组,无参数时候返回所有的配置文件 * * @param unknown_type $index * @return unknown */ public static function getItems($index = ''){ if($index == ''){ return self::$mainConfig; } if(isset(self::$mainConfig[$index])){ return self::$mainConfig[$index]; }else{ self::load($index); if(isset(self::$mainConfig[$index])){ return self::$mainConfig[$index]; }else{ throw new Exception("configure ==> config/$index.php not exists!"); } } } /** * 获取某一个项的配置配置参数 * * @param 参数项 $item * @param 配置文件名称 $index */ public static function getItem($item,$index = 'config'){ if(! in_array($index,self::$is_load)){ self::load($file); } return self::$mainConfig[$index][$item]; } /** * 返回已经加载的列表 * * @return unknown */ public static function getIsLoad(){ return self::$is_load; } /** * 取得当前已经配置的route数组中的所有前缀 * * @return unknown */ public static function getRouteArray(){ if(!is_array(self::$mainConfig['route'])){ return array(); } $uri_segmentation = self::$mainConfig['config']['uri_segmentation']; foreach (self::$mainConfig['route'] as $key => $val){ if(strpos($key,$uri_segmentation)){ $temp = explode($uri_segmentation,$key); self::$routeArray[] = $temp[0]; unset($temp); }else{ self::$routeArray[] = $key; } } return self::$routeArray; } } // var_dump(Config::getIsLoad()); // Config::cleanIsLoad(); // // Config::load('config'); // $res = Config::getItems(); // var_dump($res); // var_dump(Config::getIsLoad()); // echo 'the fist to load config<br/>'; // // Config::load('route'); // var_dump(Config::getItems()); // var_dump(Config::getIsLoad()); // // echo 'the first time to load route<br/>'; // // Config::load('config'); // $res = Config::getItems(); // var_dump($res); // var_dump(Config::getIsLoad()); // echo 'the second time to load config<br/>'; ?><file_sep>/1/static/js/product/item_detail.js $(".price_items .show_more").click(function(e){ event.preventDefault(); var detail = $(this).parent().parent().find(".price_detail"); if($(this).hasClass("expaned")){ detail.hide(); $(this).removeClass("expaned"); }else { $(this).addClass("expaned"); show_detail(detail, $(this).attr("iid")); } }); $(".item_thumbs a").click(function(e){ event.preventDefault(); $("#main_pic").attr('src', $(this).find('img').attr("src")); }); function show_detail(container, iid){ container.show(); container.load("/product/load_price_item/" + iid, {}, function(){ container.find('.price_calender').on('mouseenter', "td", function(){ if($(this).hasClass("t")) return; var r = $(this).find(".day"); $(this).addClass("t"); var p = r.attr("remain"); var tips = p > 0 ? "成人价:" + r.attr("adult") + ",儿童价:" + r.attr("child") + ",库存:" + r.attr("remain") : "不能预订"; $(this).tooltip({'placement': 'top', 'title': tips, 'container':'body'} ).tooltip('show'); }); container.find('.price_calender').on('click', "td", function(){ container.find('.price_calender td .cur').removeClass("cur"); var day = $(this).find(".c"); if(day.find(".day").attr('remain') > 0){ day.addClass("cur"); /** * 更新输入框价格,和从新计算总价。 */ var curDay = day.find(".day"); container.find(".price_form .adult_price").text(curDay.attr("adult")); container.find(".price_form .child_price").text(curDay.attr("child")); computer_total_price(container); } }); container.find('.price_calender').on('click', "a", function(){ event.preventDefault(); var month = $(this).attr('month'); var item_id = container.find('.price_calender').attr("item_id"); $("#price_calender_" + item_id).load("/product/load_calendar/?item_id=" + item_id + "&start=" + month); }); container.on('change', "input", function(){ computer_total_price(container); }); }); } /** * 计算一个面板里面的总价。因为一个商品会展开多个价格方案。只选择一个方案计算价格。 */ function computer_total_price(container){ var ap = container.find(".price_form .adult_price").text(); var cp = container.find(".price_form .child_price").text(); var ac = container.find(".price_form [name=adult_count]").val(); var cc = container.find(".price_form [name=child_count]").val(); var total = ap * ac + cp * cc; container.find(".price_form .total_price").text(total + ""); } <file_sep>/1/protected/view/shop/enter/setting.php <?php V ('shop/header.php');?> <div class="body"> <div class = "col-lg-12"> <div class = "col-lg-1 col-md-1 sidebar-nav"> <?php include 'setting_left_nav.php';?> </div > <div class = "col-lg-11 col-md-11 hd" style="padding-left: 30px;"> </div> </div> </div> <?php V ('shop/footer.php');?><file_sep>/1/protected/view/cate/nav_bar.php <div class="panel panel-default"> <div class="panel-heading">服务时间</div> <div class="panel-body"> <div>从<input name="start_time"></div> <div>到<input name="end_time" ></div> </div> </div> <?php $dest = $dest > 0 ? $dest : 0; $product_type = $product_type > 0 ? $product_type : 0; $lang = $lang > 0 ? $lang : 0; $active_time = $active_time > 0 ? $active_time : 0; $user_type = $user_type > 0 ? $user_type : 0; $q = $_SERVER['QUERY_STRING']; $suffix = HTML_VIEW ? ".html?{$q}" : "?{$q}"; ?> <div class="panel panel-default"> <div class="panel-heading">目的地</div> <div class="panel-body"> <a <?=(0 == $dest) ? 'class="cur"' : '' ?> href="/cf/<?="0-{$product_type}-{$lang}-{$active_time}-{$user_type}{$suffix}" ?>">全部</a> <?php foreach($cats_group['dest'] as $c) { $cur = $c['id'] == $dest ? 'class="cur"' : ''; ?> <a <?=$cur?> href="/cf/<?="{$c['id']}-{$product_type}-{$lang}-{$active_time}-{$user_type}{$suffix}" ?>"><?=$c['cate_label']?></a> <?php } ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading">产品分类</div> <div class="panel-body"> <a <?=(0 == $product_type) ? 'class="cur"' : '' ?> href="/cf/<?="{$dest}-0-{$lang}-{$active_time}-{$user_type}{$suffix}" ?>">全部</a> <?php foreach($cats_group['product_type'] as $c) { $cur = $c['id'] == $product_type ? 'class="cur"' : ''; ?> <a <?=$cur?> href="/cf/<?="{$dest}-{$c['id']}-{$lang}-{$active_time}-{$user_type}{$suffix}" ?>"><?=$c['cate_label']?></a> <?php } ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading">服务语言</div> <div class="panel-body"> <a <?=(0 == $lang) ? 'class="cur"' : '' ?> href="/cf/<?="{$dest}-{$product_type}-0-{$active_time}-{$user_type}{$suffix}" ?>">全部</a> <?php foreach($cats_group['lang'] as $c) { $cur = $c['id'] == $lang ? 'class="cur"' : ''; ?> <a <?=$cur?> href="/cf/<?="{$dest}-{$product_type}-{$c['id']}-{$active_time}-{$user_type}{$suffix}" ?>"><?=$c['cate_label']?></a> <?php } ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading">活动时间</div> <div class="panel-body"> <a <?=(0 == $active_time) ? 'class="cur"' : '' ?> href="/cf/<?="{$dest}-{$product_type}-{$lang}-0-{$user_type}{$suffix}" ?>">全部</a> <?php foreach($cats_group['active_time'] as $c) { $cur = $c['id'] == $active_time ? 'class="cur"' : ''; ?> <a <?=$cur?> href="/cf/<?="{$dest}-{$product_type}-{$lang}-{$c['id']}-{$user_type}{$suffix}" ?>"><?=$c['cate_label']?></a> <?php } ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading">适合群体</div> <div class="panel-body"> <a <?=(0 == $user_type) ? 'class="cur"' : '' ?> href="/cf/<?="{$dest}-{$product_type}-{$lang}-{$active_time}-0{$suffix}" ?>">全部</a> <?php foreach($cats_group['user_type'] as $c) { $cur = $c['id'] == $user_type ? 'class="cur"' : ''; ?> <a <?=$cur?> href="/cf/<?="{$dest}-{$product_type}-{$lang}-{$active_time}-{$c['id']}{$suffix}" ?>"><?=$c['cate_label']?></a> <?php } ?> </div> </div> <file_sep>/1/protected/helper/TaoDian.class.php <?php class TaoDian{ private $api_route = 'http://fmei.sinaapp.com/api/route'; private $app_id = 0; private $app_secret = 0; public function __construct($app_id, $app_secret, $api_route=null) { $this->app_id = $app_id; $this->app_secret = $app_secret; $this->mmc = memcache_init(); $this->mm_cache = array(); if($api_route){ $this->api_route = $api_route; } } public function __call($name, $arguments){ $api_args = $arguments[0]; $cache_time = $arguments[1]; $as_array = $arguments[2]; if(DEBUG){ echo "api:{$name} cache time:{$cache_time}\n"; } if($cache_time > 0){ $cache_key = $this->_cache_keys($name, $arguments); $data = $this->get_cache($cache_key); if(!$data || $_REQUEST['no_cache'] == 'y'){ $data = $this->_api_call($name, $api_args, $as_array); $this->set_cache($cache_key, $data, $cache_time * 60); }else{ if(DEBUG){ echo "hit api result from cache, key:{$cache_key}\n"; } } }else { $data = $this->_api_call($name, $api_args, $as_array); } return $data; } private function _cache_keys($name, $arguments){ $arg = md5(var_export($arguments, true)); return "ck_{$name}_{$arg}"; } function get_cache($key){ $v = $this->mm_cache[$key]; if($v) return $v; if($this->mmc){ $v = memcache_get($this->mmc, $key); $this->mm_cache[$key] = $v; }else { return false; } return $v; } function set_cache($key, $data, $expire){ $this->mm_cache[$key] = $data; if($this->mmc){ memcache_set($this->mmc, $key, $data, 0, $expire); } } private function _api_call($name, $args, $as_array){ $post_data = array(name=>$name, app_id=>$this->app_id, ); $stamp = date("YmdHis"); $sign = md5("{$this->app_id},{$stamp},{$this->app_secret}"); $param = json_encode($args); $post_data['time'] = $stamp; $post_data['sign'] = $sign; $post_data['params'] = $param; try{ $reps = $this->curl_fetch($this->api_route, $post_data); if(DEBUG){ echo "remote api, name:$name, api: $name\n param:{$param}\n cache key:{$cache_key} \n response:$reps"; } }catch(Exception $e){ if(DEBUG){ echo "remote api error:\n" . $e; } $reps = '""'; } $data = json_decode($reps, $as_array==true); return $data; } private function curl_fetch($url, $postFields = null){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); if (is_array($postFields) && 0 < count($postFields)) { $postBodyString = ""; $postMultipart = false; foreach ($postFields as $k => $v) { if("@" != substr($v, 0, 1))//判断是不是文件上传 { $postBodyString .= "$k=" . urlencode($v) . "&"; } else//文件上传用multipart/form-data,否则用www-form-urlencoded { $postMultipart = true; } } unset($k, $v); curl_setopt($ch, CURLOPT_POST, true); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1)); } } $reponse = curl_exec($ch); if (curl_errno($ch)) { throw new Exception(curl_error($ch),0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { throw new Exception($reponse,$httpStatusCode); } } curl_close($ch); return $reponse; } } ?><file_sep>/1/protected/view/shop/product/price_list.php <?php V ('shop/shop_common_head.php');?> <style> #price_list{padding-left:0px;} #price_list h4{border-bottom:1px solid #ccc;font-weight: bold;width: 80%;padding-bottom: 10px; } </style> <ol class="breadcrumb"> <li><a href="/shop/product">活动管理</a></li> <li class="active">新增活动</li> </ol> <div id="price_list" > <input type="hidden" name="pid" value="<?=$_REQUEST['pid']?>"> <h4>2.价格类型</h4> <table class ="table table-bordered"> <thead > <tr > <th >类型名称 </th > <th >门市价 </th > <th >开始时间</th > <th >结束时间</th > <th >操作 </th > </tr > </thead > <tbody > <?php foreach ($price_list as $price){?> <tr> <td><?=$price['price_name']?></td > <td><?=$price['base_price']?></td > <td><?=$price['start_date']?></td > <td><?=$price['end_date']?></td > <td> <a href="/shop/product_add_price?id=<?=$price['id']?>">修改价格</a> </td > </tr > <?php }?> <tr> <td colspan="7" style="text-align:center"> <a class="btn btn-info add_price" href="/shop/product_add_price?pid=<?=$_REQUEST['pid']?>"> <i class="icon-plus"></i>&nbsp;增加价格类型</a> </td> </tr> </tbody > </table > <?php if($product_info['verify_status'] == 0) {?> <a class="btn btn-info" href="/shop/product_done/<?=$_GET['pid'] ?>">发布完成</a> <?php }else {?> <a class="btn btn-info" href="/shop/product">完成</a> <?php }?> </div> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/static/js/bootstrap/bootstrap-validation.js /* ========================================================= * bootstrap-validation.js * Original Idea: http:/www.newkou.org (Copyright 2012 <NAME>) * Updated by 不会飞的羊 (https://github.com/FateSheep/Validation-for-Bootstrap) * ========================================================= * * 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. * ========================================================= */ !function($) { $.fn.validation = function(options) { var isOk = true; this.each(function() { globalOptions = $.extend({}, $.fn.validation.defaults, options); if(!validationForm(this)){ isOk = false; } }); return isOk; }; $.fn.validation.defaults = { validRules : [ {name: 'required', validate: function(value) {return ($.trim(value) == '');}, defaultMsg: '请输入内容。'}, {name: 'name', validate: function(value) {return (!($.trim(value).length>2 && $.trim(value).length<30));}, defaultMsg: '请输入店铺名称'}, {name: 'number', validate: function(value) {return (!/^[0-9]\d*$/.test(value));}, defaultMsg: '请输入数字。'}, {name: 'mail', validate: function(value) {return (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}$/.test(value));}, defaultMsg: '请输入邮箱地址。'}, {name: 'char', validate: function(value) {return (!/^[a-z\_\-A-Z]*$/.test(value));}, defaultMsg: '请输入英文字符。'}, {name: 'chinese', validate: function(value) {return (!/^[\u4e00-\u9fff]$/.test(value));}, defaultMsg: '请输入汉字。'}, {name: 'mobile', validate: function(value) {return (!/^[1-9]\d{10}$/.test(value));}, defaultMsg: '手机号必须是11位数字'}, ] }; var formState = false, fieldState = false, wFocus = false, globalOptions = {}; var validateField = function(field, valid) { // 验证字段 var el = $(field), error = false, errorMsg = ''; for (i = 0; i < valid.length; i++) { var x = true, flag = valid[i], msg = (el.attr(flag + '-message')==undefined)?null:el.attr(flag + '-message');; if (flag.substr(0, 1) == '!') { x = false; flag = flag.substr(1, flag.length - 1); } var rules = globalOptions.validRules; for (j = 0; j < rules.length; j++) { var rule = rules[j]; if (flag == rule.name) { if (rule.validate.call(field, el.val()) == x) { error = true; errorMsg = (msg == null)?rule.defaultMsg:msg; break; } } } if (error) {break;} } var controls = el.parents('.controls'), controlGroup = el.parents('.form-group'), errorEl = controls.children('.help-block, .help-inline'); if (error) { if (!controlGroup.hasClass('has-error')) { if (errorEl.length > 0) { var help = errorEl.text(); controls.data('help-message', help); errorEl.text(errorMsg); } else { controls.append('<span class="help-block">'+errorMsg+'</span>'); } controlGroup.addClass('has-error'); } } else { if (fieldState) { if (errorEl.length > 0) { var help = controls.data('help-message'); if (help == undefined) { errorEl.remove(); } else { errorEl.text(help); } } if(el.parents('.prize_modlum')){ var extra=true; } controlGroup.attr('class','form-group'); if(extra){ controlGroup.addClass('prize_modlum'); } } else { if (errorEl.length > 0) { var help = errorEl.text(); controls.data('help-message', help); } } } return !error; }; var validationForm = function(obj) { // 表单验证方法 formState = true; var validationError = false; $('input, textarea', obj).each(function () { var el = $(this), valid = (el.attr('check-type')==undefined)?null:el.attr('check-type').split(' '); if (valid != null && valid.length > 0) { if (!validateField(this, valid)) { if (wFocus == false) { scrollTo(0, el[0].offsetTop - 50); wFocus = true; } validationError = true; } } }); wFocus = false; fieldState = true; if (validationError) { formState = false; $('input, textarea').each(function() { var el = $(this), valid = (el.attr('check-type')==undefined)?null:el.attr('check-type').split(' '); if (valid != null && valid.length > 0) { el.focus(function() { // 获取焦点时 var controls = el.parents('.controls'), controlGroup = el.parents('.form-group'), errorEl = controls.children('.help-block, .help-inline'); if (errorEl.length > 0) { var help = controls.data('help-message'); if (help == undefined) { errorEl.remove(); } else { errorEl.text(help); } } if(el.parents('.prize_modlum')){ var extra=true; } controlGroup.attr('class','form-group'); if(extra){ controlGroup.addClass('prize_modlum'); } }); el.blur(function() { // 失去焦点时 validateField(this, valid); }); } }); return false; } return true; }; }(window.jQuery);<file_sep>/1/protected/view/shop/product/product_add_price_new.php <?php V ('shop/shop_common_head.php');?> <link rel="stylesheet" href="<?=$THEME_URL?>/css/bootstrap-datetimepicker.min.css"> <script src="<?=$THEME_URL."/js/bootstrap/bootstrap-datetimepicker.min.js"?>"></script> <script src="<?=$THEME_URL."/js/bootstrap/bootstrap-datetimepicker.zh-CN.js"?>"></script> <?php $width = "400px"; $must = "<span class='red'>*</span>"; $product_info = $product_one; ?> <style> #price_info{padding-left:0px;} #price_info .control-label{font-weight:normal;} #price_info h4{border-bottom:1px solid #ccc;font-weight: bold;width: 80%;padding-bottom: 10px; } #price_info .red{color:red;font-weight:bold;padding-right: 2px;vertical-align: middle;font-size: 1.3em;} #price_info img{max-width:220px;max-height:200px;overflow:hidden;} </style> <ol class="breadcrumb"> <li><a href="/shop/product">活动管理</a></li> <li class="active">新增活动</li> </ol> <div role= "form" class="form-horizontal" id="price_info"> <h4>2.价格类型</h4> <input type="hidden" name="pid" value="<?=$price_one['pid'] ? $price_one['pid'] : $_REQUEST['pid']?>"> <input type="hidden" name="id" value="<?=$price_one['id']?>"> <div class="form-group control-group"> <label for="inputPassword3" class="col-sm-2 control-label"><?=$must?>价格类型名称</label> <div class="col-sm-10 controls"> <input type="text" class="form-control" name="price_name" value="<?=$price_one['price_name']?>" check-type="required" placeholder="名称" style="width:<?=$width?>;"> </div> </div> <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"> <?=$must?>门市价</label> <div class="col-sm-10 controls"> <div class="input-group " style="width:<?=$width?>;"> <input type="text" class="form-control" name="base_price" value="<?=$price_one['base_price']?>" check-type="required"> <span class="input-group-addon">元</span> </div> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"> <?=$must?>成人价</label> <div class="controls col-sm-10"> <div class="input-group " style="width:<?=$width?>;"> <input type="text" class="form-control" name="adult_price" value="<?=$price_one['adult_price']?>" check-type="required"> <span class="input-group-addon">元</span> </div> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?> 儿童价</label> <div class="controls col-sm-10"> <div class="input-group " style="width:<?=$width?>;"> <input type="text" class="form-control" name="child_price" value="<?=$price_one['child_price']?>" check-type="required"> <span class="input-group-addon">元</span> </div> </div > </div > <div class="form-group atime"> <label class="col-sm-2 control-label">指定时间段:</label> <div class="col-sm-3 controls form-inline"> <input class="form-control" name="start_time" value="<?=date("Y-m-d",strtotime($price_one['start_time']))?>" type="datetime" readonly autocomplete="off" style="max-width: 150px;" check-type="required" required-message="请填写活动开始时间" /> 至 <input class="form-control" name="end_time" value="<?=date("Y-m-d",strtotime($price_one['end_time']))?>" type="datetime" readonly autocomplete="off" style="max-width: 150px;" check-type="required" required-message="请填写活动结束时间" /> </div> <div class="col-sm-2"> <a class="btn btn-default">生成表格</a> </div> </div> <?php include 'price_table.php'; ?> <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>库存</label> <div class="controls col-sm-10"> <input type="text" class="form-control" check-type="required" value="<?=$price_one['inventory']?>" style="width:<?=$width?>" name="inventory" > <a href=""></a> </div > </div > <div class="form-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>接送服务</label> <div class="col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="pickup" <?=$price_one['pickup'] ? "checked=checked":''?>> 是 </label> </div> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>活动亮点</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="lightspot" style="width:<?=$width?>"><?=$price_one['lightspot']?></textarea> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>费用说明</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="fee_descrip" style="width:<?=$width?>"><?=$price_one['fee_descrip']?></textarea> </div > </div > <div class="form-group control-group"> <label for= "exampleInputEmail1" class="col-sm-2 control-label"><?=$must?>退改规则</label> <div class="controls col-sm-10"> <textarea class="form-control" check-type="required" name="refund_rule" style="width:<?=$width?>"><?=$price_one['refund_rule']?></textarea> </div > </div > <div class="mt50" style="text-align:center"> <input type="button" class="btn btn-primary btn-lg" id="to_act_third" value="下一步"> </div> </div ><!-- form-horizontal --> <script> //价格保存验证 function check_second(){ var price_flag = false; if(!$("#price_info").validation()){ price_flag = true; } if(price_flag){ return false; } return true; } </script> <script> $("#price_info [name=start_time]").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', todayBtn: 1, autoclose: 1, showMeridian: true }); $("#price_info [name=end_time]").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', todayBtn: 1, autoclose: 1, showMeridian: true, }); </script> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/protected/view/admin/footer.php <?php V("foot_links.php"); ?> <script type="text/javascript" language="javascript" src="<?=$THEME_URL ?>/js/js_loader.php?ver=<?=$_REQUEST['ver'] ?>&group=<?=$js_group ?>&no_cache=<?=$_REQUEST['no_cache']?>&zl=<?=$_REQUEST['zl']?>&br=<?=$_REQUEST['br']?>"></script> </body> </html> <file_sep>/1/protected/module/HomeModel.class.php <?php require_once DOCROOT . "common/cache.class.php"; class HomeModel extends Module { var $client; //客户端信息. var $kv; var $db; public function __construct(){ parent::__construct(); $this->load_class('Db'); $this->db = new Db(); $this->cache = new SimpleCache('sae', '', 'emop_'); } public function select_all_product($params){ $table = "shop_product_info"; if ($params['limit']){ $limit = "limit {$params['limit']}"; } $sql = <<<END select * from $table where verify_status = 1 order by update_time desc $limit END; $data = $this->db->getData($sql); return $data; } public function select_travel_product($new=false){ $travel = $this->db->getData("select * from travel_product_category"); if (!$new){ return $travel; }else{ $new_travle = array(); foreach ($travel as $i=>$new){ $new_travle[$new['id']] = $new['name']; } return $new_travle; } } }<file_sep>/1/protected/view/home/footer.php <?php V("foot_links.php"); ?> </body> </html> <file_sep>/1/static/js/shop/business_enter.js function businessEnter(){ var that = this; that.init(); } Bn = businessEnter.prototype; Bn.init = function(){ var that = this; that.up_auth(); that.up_license(); that.up_logo(); that.enter_event(); } Bn.enter_event = function(){ var that = this; $("#confirm-enter").click(function(){ if($("#business-enter").validation()){ var post_data = that.get_enter_info(); if(!post_data){ return false; } $(this).text('数据正在保存中……'); $.post("/ShopEnter/save_enter_info",post_data, function(r){ if(r.status == 'ok'){ $.show_ok('保存成功!'); setTimeout(function(){ location.href = "/shop/product"; },1000) }else{ $.show_error('保存出错:'+r.msg); } },'json') } }) } Bn.get_enter_info = function(){ var that = this; if($("[name=authentication]").val() == ''){ $.show_error('请上传身份认证!'); return false; } if($("[name=license]").val() == ''){ $.show_error('请上传营业执照!'); return false; } if($("[name=logo]").val() == ''){ $.show_error('请上传logo!'); return false; } if($("[name=continent] option:selected").val() == '-1'){ $.show_error('请选择洲!'); return false; } if($("[name=country] option:selected").val() == '-1'){ $.show_error('请选择国家!'); return false; } if($("[name=city] option:selected").val() == '-1'){ $.show_error('请选择城市!'); return false; } if(!$("[name=clause]").prop("checked")){ var err = "<span style='color:red'>请同意条款!</span>"; $("[name=clause]").parent().append(err); return false; } var post_data = { id : $("[name=id]").val(), shop_name : $("[name=shop_name]").val(), surname : $("[name=surname]").val(), forename : $("[name=forename]").val(), sex : $("[name=sex] option:selected").val(), authentication : $("[name=authentication]").val(), registration_name : $("[name=registration_name]").val(), postcode : $("[name=postcode]").val(), continent : $("[name=continent] option:selected").text(), city : $("[name=city] option:selected").text(), country : $("[name=country] option:selected").text(), address : $("[name=address]").val(), web_url : $("[name=web_url]").val(), license : $("[name=license]").val(), tel : $("[name=tel]").val(), qq : $("[name=qq]").val(), wx : $("[name=wx]").val(), wb : $("[name=wb]").val(), logo : $("[name=logo]").val(), description : $("[name=description]").val(), }; $("[name=subject]").each(function(){ if($(this).is(":checked")){ post_data.subject = $(this).val() return; } }) return post_data; } Bn.up_auth = function(){ var that = this; var file = $(".up-auth"); file.uploadfile({ bucket: 'jishop', return_url: 'http://'+window.location.host+'/api/upload_callback/jishop', save_key: "/jilv/authentication/{year}_{mon}_{day}/jilv_{hour}{min}{sec}{.suffix}", callback: function(data){ if(typeof(data) == 'object'){ if(data.code == '200'){ $("[name=authentication]").parent().find("img").attr("src",data.url+"!190"); $("[name=authentication]").val(data.url); file.val(data.url); }else{ var ERR = "<span style='red'>"+data.message+"</span>"; $("[name=authentication]").after(ERR); } } } }); } Bn.up_license = function(){ var that = this; var file = $(".up-license"); file.uploadfile({ bucket: 'jishop', return_url: 'http://'+window.location.host+'/api/upload_callback/jishop', save_key: "/jilv/license/{year}_{mon}_{day}/jilv_{hour}{min}{sec}{.suffix}", callback: function(data){ if(typeof(data) == 'object'){ if(data.code == '200'){ $("[name=license]").parent().find("img").attr("src",data.url+"!190"); $("[name=license]").val(data.url); file.val(data.url); }else{ var ERR = "<span style='red'>"+data.message+"</span>"; $("[name=license]").after(ERR); } } } }); } Bn.up_logo = function(){ var that = this; var file = $(".up-logo"); file.uploadfile({ //bucket: 'jishop', //return_url: 'http://'+window.location.host+'/api/upload_callback/jishop', save_key: "/jilv/logo/{year}_{mon}_{day}/jilv_{hour}{min}{sec}{.suffix}", callback: function(data){ if(typeof(data) == 'object'){ if(data.code == '200'){ $("[name=logo]").parent().find("img").attr("src",data.url+"!w348"); $("[name=logo]").val(data.url); file.val(data.url); }else{ var ERR = "<span style='red'>"+data.message+"</span>"; $("[name=logo]").after(ERR); } } } }); } var App = {}; $(function(){ App.benter = new businessEnter(); })<file_sep>/1/protected/view/admin/front/left_nav.php <div class="panel panel-default navbar-panel"> <div class="panel-heading"> <h4 class="panel-title"> 前端管理 </h4> </div> <div class="panel-body"> <h4><a href="#">首页管理</a></h4> <ul class="nav nav-stacked left-menu"> <li <?php if($nav_index == 'home_page'){ echo 'class="active"'; }?>> <a href="/adminFront/home_page"> <i class="icon-group"></i> 首页配置 </a> </li> <li <?php if($nav_index == 'product_list'){ echo 'class="active"'; }?>> <a href="/adminFront/product_list" > <i class="icon-yen"></i> 导航页面 </a> </li> </ul> </div> </div><file_sep>/1/protected/view/shop/product/product_done.php <?php V ('shop/shop_common_head.php');?> <ol class="breadcrumb"> <li><a href="/shop/product">活动管理</a></li> <li class="active">新增活动</li> </ol> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: 33%"> 填写基本信息 </div> <div class="progress-bar progress-bar-success" style="width: 34%"> 填写可售产品 </div> <div class="progress-bar progress-bar-success" style="width: 33%"> 完成 </div> </div> <div id="price_list" > <h4>发布完成</h4> <div class="alert alert-success"> 活动发布完成,等待管理员审核。审核通过后,会在前端展示推广。 </div> <a class="btn btn-info" href="/product/preview/<?=$product['id']?>">预览发布效果</a> <a class="btn btn-info" href="/shop/product">返回商品列表</a> </div> <?php V ('shop/shop_common_foot.php');?> <file_sep>/1/protected/action/MemberAction.class.php <?php include_once DOCROOT . '/helper/Page.class.php'; /** * 旅客登录后的页面 * @author deonwu * */ class MemberAction extends Action{ public function __construct(){ parent::__construct(); $this->per_page = 10; } public function hook_start_request(){ $this->app = new AppHook(); $this->app->start_request($this); $this->assign("HOST",host_url()."/home/"); } } ?><file_sep>/1/static/js/jsloader/JSLoader.php <?php class JSLoader{ private $root; private $common; private $groups; private $root_app; public function __construct($root, $common, $groups) { $this->root = $root; $this->common = $common; $this->groups = $groups; } public function clean_cache(){ header("Content-Type: text/plain; charset=utf8"); $mmc = memcache_init(); foreach($this->groups as $k => $v){ $ck = "js_loader_{$k}"; memcache_delete($mmc, $ck, 0); echo "clean up '$k'\n"; } } public function load(){ header("Content-Type: text/javascript; charset=utf8"); $ver = 'dev'; //$_GET['ver']; $group_name = $_GET['group']; $group_name = $group_name ? $group_name : "index"; if($_REQUEST['debug'] != 'true'){ ob_clean(); } if($ver == 'dev'){ header("Cache-Control: no-cache, no-store, max-age=0, must-revalidate"); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); echo $this->load_packed_content($group_name); echo $this->load_unpack_content($group_name, false); }else { header("Cache-Control: must-revalidate; max-age: 3600"); header("Expires: " . gmdate ("D, d M Y H:i:s", time() + 3600) . " GMT"); echo $this->load_cached_content($group_name); } } public function load_cached_content($group_name){ $mmc = memcache_init(); $ck = "js_loader_{$group_name}"; if($mmc){ $data = memcache_get($mmc, $ck); } if(empty($data) || $_REQUEST['no_cache'] == 'y'){ $data = $this->load_packed_content($group_name); $data .= ";\n" . $this->load_unpack_content($group_name, true); $cache_data = $data . ";\n// cached in" . date("Y-m-d H:i:s"); if($mmc){ memcache_set($mmc, $ck, $cache_data, MEMCACHE_COMPRESSED, 3600); } } return $data; } public function load_unpack_content($group_name, $is_pack){ $common_list = $this->common[1]; $common_list2 = $this->groups[$group_name][1]; if(is_array($common_list2)){ $common = array_merge($common_list, $common_list2); }else { $common = $common_list; } $zip_level = $_REQUEST['zl']; $zip_level = $zip_level ? $zip_level : 'None'; $data = $this->load_file_list($common); if($is_pack){ include "JavaScriptPacker.php"; $packer = new JavaScriptPacker($data, $zip_level); $data = $packer->pack(); $br = $_REQUEST['br']; if($br){ $data = str_replace("{$br}", "{$br}\n", $data); } } return $data; } public function load_packed_content($group_name){ $common_list = $this->common[0]; $common_list2 = $this->groups[$group_name][0]; if(is_array($common_list2)){ $common = array_merge($common_list, $common_list2); }else { $common = $common_list; } $data = $this->load_file_list($common); return $data; } private function load_file_list($files){ $data = ""; foreach($files as $f){ $file = "{$this->root}/{$f}"; if(!is_file($file)){ $file = $this->load_file_app($f); } if(!is_file($file)){ $data .= "// not found '{$f}'\n"; continue; } $data .= ";\n" . file_get_contents($file); } return $data; } private function load_file_app($file){ preg_match("/apps\.(?<dir>.*)\.(?<name>.*\.js)$/", $file, $matches); $file_dir = str_replace('.', '/', $matches['dir']); $file_name = $matches['name']; $path = <<<PATH {$this->root_app}/{$file_dir}/static/js/{$file_name} PATH; return $path; } public function set_app_root_path($path){ $this->root_app = $path; } private function load_file_list_bak($files){ $data = ""; foreach($files as $f){ $file = "{$this->root}/{$f}"; if(!is_file($file)){ $data .= "// not found '{$f}'\n"; continue; } $data .= ";\n" . file_get_contents($file); } return $data; } } ?>
7a184e48049eb82963c06a47b0919b0770d191a0
[ "JavaScript", "SQL", "Markdown", "PHP" ]
109
PHP
deonwu/jilv
e857682a7ab4475f003872b67431f4a71ed9a8c7
8530910d299cda7ba751fa66e30ca529905ce4a7
refs/heads/master
<file_sep>import React from 'react' const BottomProgressBar = (props) => { const { current, total, correctAns } = props const remQuiz = total - current const minScore = (correctAns / total) * 100 const currScore = (correctAns / current) * 100 const currProg = currScore - minScore const maxScore = ((correctAns + remQuiz) / total) * 100 const maxProg = maxScore - currScore const remProg = 100 - maxScore const vals = [minScore, currProg, maxProg, remProg] const totalVals = vals && vals.length const style = (width, opacity) => ({ width: `${width}%`, backgroundColor: 'black', minHeight: '5px', opacity }) return ( <span style={{ display: 'flex', height: '-webkit-fill-available' }}> {vals.map((val, index) => ( (index === 0) ? <div key={`BottomProgressBar${index}${val}`} style={style(val, 1)} /> : <div key={`BottomProgressBar${index}${val}`} style={style(val, (totalVals - (index + 1)) / totalVals)} /> ))} </span> ) } export default BottomProgressBar <file_sep>import { Rate } from 'antd' import React, { Component, Fragment } from 'react' import BottomProgressBar from '../components/BottomProgressBar' import Button from '../components/Button' import TopProgressBar from '../components/TopProgressBar' import myQuizes from '../questions.json' import './styles.css' class Home extends Component { constructor (props) { super(props) this.state = { currentIndex: 0, questions: [], numberOfQuiz: 0, clicked: false, answered: false, correctCount: 0, answeredCount: 0, isCorrect: false, currQuiz: { category: '', type: '', difficulty: '', question: '', correctAnswer: '', options: [], incorrectAnswer: [] } } } parseCurrentQuestion (quiz) { const correctAnswer = unescape(quiz.correct_answer) const incorrectAnswers = quiz.incorrect_answers.map(a => unescape(a)) const quizObj = {} quizObj.category = unescape(quiz.category) quizObj.type = unescape(quiz.type) quizObj.difficulty = unescape(quiz.difficulty) quizObj.question = unescape(quiz.question) quizObj.correctAnswer = correctAnswer quizObj.incorrectAnswers = incorrectAnswers quizObj.options = [...incorrectAnswers, correctAnswer].sort(() => Math.random() - 0.5) return quizObj } componentDidMount () { const currQuiz = this.parseCurrentQuestion(myQuizes[0]) this.setState({ questions: [ ...myQuizes ], numberOfQuiz: myQuizes.length, currQuiz }) } nextQuestion () { this.setState(prevState => { const { currentIndex, numberOfQuiz, questions } = prevState if (currentIndex + 1 < numberOfQuiz) { const currQuiz = this.parseCurrentQuestion(questions[currentIndex + 1]) return { currentIndex: prevState.currentIndex + 1, currQuiz, clicked: true, answered: false } } }) } parseRating (difficulty) { switch (difficulty) { case 'hard': return 3 case 'medium': return 2 case 'easy': return 1 default: return 0 } } handleSelect (el) { const text = el.innerText const { currQuiz: { correctAnswer }, answered } = this.state if (text === correctAnswer && !answered) { this.setState(prevState => ({ correctCount: prevState.correctCount + 1, answered: true, clicked: true, isCorrect: true, answeredCount: prevState.answeredCount + 1 })) } else if (!answered) { this.setState(prevState => ({ answered: true, clicked: true, isCorrect: false, answeredCount: prevState.answeredCount + 1 })) } } render () { const { currentIndex, numberOfQuiz, currQuiz, answered, currQuiz: { options }, isCorrect, clicked, answeredCount, correctCount } = this.state const isCorrectOrWrong = clicked && isCorrect ? 'Correct!' : 'Sorry!' const currScore = (correctCount / answeredCount) * 100 || 0 const remQuiz = numberOfQuiz - answeredCount const maxScore = ((correctCount + remQuiz) / numberOfQuiz) * 100 const hideThis = answered ? '' : 'hidden' const finalScoreText = remQuiz > 0 ? isCorrectOrWrong : `Final Score: ${parseInt(currScore)}%` const hideIfExtra = options.length === 2 ? 'hidden' : '' return ( <Fragment> <TopProgressBar current={answeredCount} total={numberOfQuiz} /> <div className='container'> <div className='header'> <h1>Question {currentIndex + 1 } of {numberOfQuiz}</h1> <h4>{currQuiz.category}</h4> <Rate className='rating' count={3} value={this.parseRating(currQuiz.difficulty)} defaultValue={0} disabled /> </div> <p className='quiz-text'> {currQuiz.question} </p> <div className='btn-group'> <Button pos={1} disabled={answered} text={options[0]} onClick={e => this.handleSelect(e.target)} /> <Button pos={2} disabled={answered} text={options[1]} onClick={e => this.handleSelect(e.target)} /> </div> <div className={`btn-group ${hideIfExtra}`}> <Button pos={3} disabled={answered} text={options[2]} onClick={e => this.handleSelect(e.target)} /> <Button pos={4} disabled={answered} text={options[3]} onClick={e => this.handleSelect(e.target)} /> </div> <span className={hideThis}> <h1>{finalScoreText}</h1> <Button disabled={!answered || remQuiz === 0} text='Next Question' onClick={() => this.nextQuestion()} /> </span> <div className='progress-text' > <span>Score: {parseInt(currScore)}%</span> <span>Max Score: {parseInt(maxScore)}%</span> </div> <span className='bottomBar'> <BottomProgressBar current={answeredCount} correctAns={correctCount} total={numberOfQuiz} /> </span> </div> </Fragment> ) } } export default Home
2b6b5cb5eae6311eb743103378353afcd21ab43a
[ "JavaScript" ]
2
JavaScript
danuluma/quiz-app
a09b9ae2a6ca86631679633b10f659c26ff6d456
ecbdf769cbc3c985d00f13903766ad9b3816fb34